当前位置:网站首页>.NET Core 日志系统
.NET Core 日志系统
2022-07-02 11:55:00 【DotNeter-Hpf】
文章目录
1.日志级别
Trace < Debug < Information < Warning < Error < Critical
- Critical:生死攸关
- Error:无法处理的错误信息
- Warning:不会中断应用程序,但仍需调查的警告错误
- Information:程序运行时输出重要信息,通常具有长期价值
- Debug:开发、调试过程中,短期有用的消息
- Trace:最低的日志级别,我没用过
1.1 控制台程序使用
引用包
Microsoft.Extensions.Logging
Microsoft.Extensions.Logging.Console
Program.cs代码(.NET6创建的控制台程序)
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
ServiceCollection services = new();
services.AddLogging(logBulider => {
logBulider.AddConsole();
logBulider.SetMinimumLevel(LogLevel.Debug); //设置允许日志输出的最低级别为Debug
});
services.AddScoped<Test1>();
using (var sp = services.BuildServiceProvider())
{
var test1= sp.GetRequiredService<Test1>();
test1.Test();
}
* 新建Test1.cs类并写入代码
public class Test1
{
private readonly ILogger<Test1> logger;
public Test1(ILogger<Test1> _logger)
{
this.logger = _logger;
}
public void Test()
{
logger.LogDebug("开始执行数据库同步");
logger.LogDebug("连接数据库成功");
logger.LogWarning("查找数据失败,重试第一次");
logger.LogWarning("查找数据失败,重试第二次");
logger.LogError("查找数据最终失败");
}
}
运行效果
2.记录到Windows下的事件查看器中
注意:除非程序只部署到Windows系统下,否则不建议这样写日志
在标题1中稍作修改
引用包 Microsoft.Extensions.Logging.EventLog
新增代码 logBulider.AddEventLog();
运行效果
3.使用NLog写入文本文件(ASP.NET Core 案例)
nlog.config
官方提供的配置文件Program.cs
builder.Services.AddLogging(logBulider => {
logBulider.AddConsole();
//logBulider.AddEventLog();
logBulider.AddNLog();
logBulider.SetMinimumLevel(LogLevel.Debug); //设置允许日志输出的最低级别Debug
});
控制器
public class WeatherForecastController : ControllerBase
{
private readonly IConfiguration config;
public TestController(ILogger<TestController> logger)
{
this.logger = logger;
}
[HttpPost]
public JsonResult TestLog()
{
logger.LogInformation("测试Information");
logger.LogDebug("测试Debug");
logger.LogError("测试Error");
return new JsonResult("");
}
}
- 引用包 NLog.Extensions.Logging
- 注意nlog.config 必须小写,如果大写并部署到Linux系统,会报错
- nlog.config 文件属性 设置为
始终复制 - 项目添加代码
logBulider.AddNLog();
3.1 配置文件的解读
internalLogFile=“c:\temp\internal-nlog-AspNetCore.txt” ,如果去掉 c:\temp\ 就是默认往系统根路径写入
rules 的匹配规则是由上而下,只要符合条件,就会写入日志
rules 中的 name 属性,是由
namespace+类名组成rules name=“Microsoft.*” : 匹配 Microsoft 开头的
rules logger writeTo=“lifetimeConsole, ownFile-web” 可以匹配多个
rules logger final=true 属性:一旦匹配到,就不会再往下匹配
4.使用NLog写入数据库(ASP.NET Core 案例)
nlog.config 配置
<targets>
<target name="database" xsi:type="Database" connectionstring="Server=.;Initial Catalog=cxlprod;Persist Security Info=False;User ID=DemoDB;Password=sa2008;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;">
<commandText>
insert into NLogInfo([Date],[origin],[Level],[Message]) values (DATEADD(HOUR, 8, GETDATE()), @origin, @logLevel, @message);
</commandText>
日志来源
<parameter name="@origin" layout="${callsite}" />
日志等级
<parameter name="@logLevel" layout="${level}" />
日志消息
<parameter name="@message" layout="${message}" />
</target>
</targets>
<rules>
<logger name="*" writeTo="database" />
</rules>
边栏推荐
- btrace-(字节码)动态跟踪工具
- C语言习题---(数组)
- tmall. product. schema. Get (product information acquisition schema acquisition), Taobao store upload commodity API interface, Taobao commodity publishing interface, Taobao commodity upload API interf
- 2、const 型指针
- taobao.trade.get( 获取单笔交易的部分信息),淘宝店铺订单接口,淘宝oAuth2.0接口,淘宝R2接口代码对接分享
- 871. Minimum refueling times: simple priority queue (heap) greedy question
- STM32标准固件库函数名记忆(二)
- 传感器数据怎么写入电脑数据库
- LeetCode 2310. 个位数字为 K 的整数之和
- LeetCode_字符串_简单_412.Fizz Buzz
猜你喜欢

C code audit practice + pre knowledge

C#代码审计实战+前置知识

obsidian安装第三方插件——无法加载插件

c语言入门--数组

Xilinx Vivado set *. svh as SystemVerilog Header

Base64 编码原来还可以这么理解
[email protected]: The platform “win32“ is incompatible with this module."/>info [email protected]: The platform “win32“ is incompatible with this module.

Makefile separates file names and suffixes

IE 浏览器正式退休
[email protected] : The platform “win32“ is incompatible with this module."/>info [email protected] : The platform “win32“ is incompatible with this module.
随机推荐
Error: NPM warn config global ` --global`, `--local` are deprecated Use `--location=global` instead.
Fabric. JS free draw circle
LeetCode 2310. The number of digits is the sum of integers of K
STM32库函数进行GPIO初始化
传感器数据怎么写入电脑数据库
微信小程序使用towxml显示公式
Fabric. JS dynamically set font size
蜻蜓低代码安全工具平台开发之路
taobao. trade. memo. Add (add remarks to a transaction) interface, Taobao store flag insertion interface, Taobao order flag insertion API interface, oauth2.0 interface
数据库内容输出有问题怎么解决
C# 线程传参
1、编辑利器vim
Check password
Advanced C language (learn malloc & calloc & realloc & free in simple dynamic memory management)
C RichTextBox controls the maximum number of lines displayed
Threejs controller cube space basic controller + inertia control + flight control
Fabric. Keep the original level when JS element is selected
Socket and socket address
About text selection in web pages and counting the length of selected text
C# richTextBox控制显示最大行数