当前位置:网站首页>. 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
边栏推荐
- Check password
- 使用mathtype编辑公式,复制粘贴时设置成仅包含mathjax语法的公式
- Large top heap, small top heap and heap sequencing
- LeetCode 2310. 个位数字为 K 的整数之和
- 3、函数指针和指针函数
- Bit by bit of OpenCV calling USB camera
- btrace-(字节码)动态跟踪工具
- 【C语言】详解指针的初阶和进阶以及注意点(1)
- Actual combat sharing of shutter screen acquisition
- Dragonfly low code security tool platform development path
猜你喜欢
可视化搭建页面工具的前世今生
关于网页中的文本选择以及统计选中文本长度
CTO如何帮助业务?
【C语音】详解指针进阶和注意点(2)
LeetCode 2320. 统计放置房子的方式数
Simple verification code generator for 51 single chip microcomputer experiment
蜻蜓低代码安全工具平台开发之路
表格响应式布局小技巧
geoserver离线地图服务搭建和图层发布
Error: NPM warn config global ` --global`, `--local` are deprecated Use `--location=global` instead.
随机推荐
4、数组指针和指针数组
c语言入门--数组
Why can't programmers who can only program become excellent developers?
geoserver离线地图服务搭建和图层发布
Simple verification code generator for 51 single chip microcomputer experiment
C# 线程传参
Database connection pool and data source
LeetCode 209. 长度最小的子数组
Fundamentals of software testing
Edit the formula with MathType, and set it to include only mathjax syntax when copying and pasting
3. Function pointers and pointer functions
一张图彻底掌握prototype、__proto__、constructor之前的关系(JS原型、原型链)
Onnx+tensorrt: write preprocessing operations to onnx and complete TRT deployment
Base64 编码原来还可以这么理解
##51单片机实验之简易验证码发生器
mathML转latex
记一次报错解决经历依赖重复
MFC A对话框调用B对话框函数并传参
【C语言】详解指针的初阶和进阶以及注意点(1)
About text selection in web pages and counting the length of selected text