当前位置:网站首页>. 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 nameformrules 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
边栏推荐
猜你喜欢

kityformula-editor 配置字号和间距

可视化搭建页面工具的前世今生

MQ tutorial | exchange (switch)
[email protected] : The platform “win32“ is incompatible with this module."/>info [email protected] : The platform “win32“ is incompatible with this module.

【无标题】LeetCode 2321. 拼接数组的最大分数

解决el-radio-group 回显后不能编辑问题

c语言入门--数组

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

LeetCode 209. Minimum length subarray

LeetCode 2320. Count the number of ways to place the house
随机推荐
Makefile 分隔文件名与后缀
Some Chinese character codes in the user privacy agreement are not standardized, which leads to the display of garbled codes on the web page. It needs to be found and handled uniformly
Why can't programmers who can only program become excellent developers?
关于网页中的文本选择以及统计选中文本长度
info [email protected] : The platform “win32“ is incompatible with this module.
socket(套接字)与socket地址
threejs的控制器 立方体空间 基本控制器+惯性控制+飞行控制
电脑怎么设置扬声器播放麦克风的声音
Introduction to mathjax (web display of mathematical formulas, vector)
Li Chuang EDA learning notes 15: draw border or import border (DXF file)
数据库内容输出有问题怎么解决
Xilinx Vivado set *.svh as SystemVerilog Header
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
OpenCV调用USB摄像头的点滴
Wechat applet uses towxml to display formula
复用和分用
SQL 后计算的利器 SPL
geoserver离线地图服务搭建和图层发布
Simple verification code generator for 51 single chip microcomputer experiment