当前位置:网站首页>. Net core logging system
. Net core logging system
2022-07-02 15:02:00 【DotNeter-Hpf】
List of articles
1. The level of logging
Trace < Debug < Information < Warning < Error < Critical
- Critical: be a life-and-death matter
- Error: Unhandled error messages
- Warning: Without interrupting the application , But warning errors that still need to be investigated
- Information: When the program runs, it outputs important information , Usually of long-term value
- Debug: Development 、 During commissioning , Short term useful news
- Trace: The lowest log level , I've never used
1.1 The console program uses
Reference package
Microsoft.Extensions.Logging
Microsoft.Extensions.Logging.Console
Program.cs Code (.NET6 Create a console program )
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
ServiceCollection services = new();
services.AddLogging(logBulider => {
logBulider.AddConsole();
logBulider.SetMinimumLevel(LogLevel.Debug); // Set the minimum level that allows log output to Debug
});
services.AddScoped<Test1>();
using (var sp = services.BuildServiceProvider())
{
var test1= sp.GetRequiredService<Test1>();
test1.Test();
}
* newly build Test1.cs Class and write code
public class Test1
{
private readonly ILogger<Test1> logger;
public Test1(ILogger<Test1> _logger)
{
this.logger = _logger;
}
public void Test()
{
logger.LogDebug(" Start database synchronization ");
logger.LogDebug(" Successfully connected to database ");
logger.LogWarning(" Failed to find data , Try again for the first time ");
logger.LogWarning(" Failed to find data , Retry the second time ");
logger.LogError(" The search for data finally failed ");
}
}
Running effect
2. It was recorded that Windows In the event viewer under
Be careful : Unless the program is only deployed to Windows Under the system , Otherwise, it is not recommended to log like this
In the title 1 Slightly modified in
Reference package Microsoft.Extensions.Logging.EventLog
New code logBulider.AddEventLog();
Running effect
3. Use NLog Write text file (ASP.NET Core Case study )
nlog.config
Officially provided configuration fileProgram.cs
builder.Services.AddLogging(logBulider => {
logBulider.AddConsole();
//logBulider.AddEventLog();
logBulider.AddNLog();
logBulider.SetMinimumLevel(LogLevel.Debug); // Set the minimum level that allows log output Debug
});
controller
public class WeatherForecastController : ControllerBase
{
private readonly IConfiguration config;
public TestController(ILogger<TestController> logger)
{
this.logger = logger;
}
[HttpPost]
public JsonResult TestLog()
{
logger.LogInformation(" test Information");
logger.LogDebug(" test Debug");
logger.LogError(" test Error");
return new JsonResult("");
}
}
- Reference package NLog.Extensions.Logging
- Be careful nlog.config Must be in lowercase , If capitalized and deployed to Linux System , Will report a mistake
- nlog.config File attribute Set to
Always copy
- Add code to the project
logBulider.AddNLog();
3.1 Interpretation of configuration files
The configuration file provided by the official specifies
internalLogFile=“c:\temp\internal-nlog-AspNetCore.txt” , If you remove c:\temp\ Is to write to the system root path by default
rules The matching rule of is from top to bottom , As long as the conditions are met , Will be written to the log
rules Medium name attribute , By
namespace+ Class name
formrules name=“Microsoft.*” : matching Microsoft At the beginning
rules logger writeTo=“lifetimeConsole, ownFile-web” Can match multiple
rules logger final=true attribute : Once matched to , There will be no further matching
4. Use NLog Write to database (ASP.NET Core Case study )
nlog.config To configure
<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>
Source of a log
<parameter name="@origin" layout="${callsite}" />
The log level
<parameter name="@logLevel" layout="${level}" />
Log message
<parameter name="@message" layout="${message}" />
</target>
</targets>
<rules>
<logger name="*" writeTo="database" />
</rules>
Video reference : Yang Zhongke ,NET6 course - P31 Dependency injection
Video reference : Yang Zhongke ,NET6 course - P45 Log system
边栏推荐
- 华为面试题: 没有回文串
- IE 浏览器正式退休
- 记一次报错解决经历依赖重复
- MQ tutorial | exchange (switch)
- Full of knowledge points, how to use JMeter to generate encrypted data and write it to the database? Don't collect it quickly
- About text selection in web pages and counting the length of selected text
- C#代码审计实战+前置知识
- mathML转latex
- 2. Const pointer
- 3、函数指针和指针函数
猜你喜欢
btrace-(字节码)动态跟踪工具
geoserver离线地图服务搭建和图层发布
[email protected]: The platform “win32“ is incompatible with this module."/>
info [email protected]: The platform “win32“ is incompatible with this module.
大顶堆、小顶堆与堆排序
Onnx+tensorrt: write preprocessing operations to onnx and complete TRT deployment
天猫商品详情接口(APP,H5端)
Li Chuang EDA learning notes 15: draw border or import border (DXF file)
电脑怎么设置扬声器播放麦克风的声音
forEach的错误用法,你都学废了吗
【NOI模拟赛】刮痧(动态规划)
随机推荐
Record an error report, solve the experience, rely on repetition
Implement a server with multi process concurrency
牛客练习赛101
Mfc a dialog calls B dialog function and passes parameters
蜻蜓低代码安全工具平台开发之路
报错:npm WARN config global `--global`, `--local` are deprecated. Use `--location=global` instead.
[untitled] leetcode 2321 Maximum score of concatenated array
实用调试技巧
info [email protected] : The platform “win32“ is incompatible with this module.
【题解】Educational Codeforces Round 82
obsidian安装第三方插件——无法加载插件
华为面试题: 没有回文串
Huawei interview question: no palindrome string
Makefile 分隔文件名与后缀
【NOI模拟赛】伊莉斯elis(贪心,模拟)
Obsidian installs third-party plug-ins - unable to load plug-ins
传感器数据怎么写入电脑数据库
Simple verification code generator for 51 single chip microcomputer experiment
socket(套接字)与socket地址
fatal: unsafe repository is owned by someone else 的解决方法