当前位置:网站首页>. 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
边栏推荐
- STM32标准固件库函数名(一)
- Stm32-dac Experiment & high frequency DAC output test
- Mfc a dialog calls B dialog function and passes parameters
- 用户隐私协议有些汉字编码不规范导致网页显示乱码,需要统一找出来处理一下
- LeetCode 2310. The number of digits is the sum of integers of K
- taobao.trade.memo.add( 对一笔交易添加备注 )接口,淘宝店铺插旗接口,淘宝订单插旗API接口,oAuth2.0接口
- Onnx+tensorrt: write preprocessing operations to onnx and complete TRT deployment
- [QNX hypervisor 2.2 user manual]6.3 communication between guest and external
- Have you learned the wrong usage of foreach
- Bit by bit of OpenCV calling USB camera
猜你喜欢
LeetCode - 搜索二维矩阵
Why can't programmers who can only program become excellent developers?
IE 浏览器正式退休
为什么只会编程的程序员无法成为优秀的开发者?
Tmall product details interface (APP, H5 end)
[development environment] install the visual studio community 2013 development environment (download the installation package of visual studio community 2013 with update 5 version)
It's no exaggeration to say that this is the most user-friendly basic tutorial of pytest I've ever seen
Introduction to mathjax (web display of mathematical formulas, vector)
STM32库函数进行GPIO初始化
实现一个多进程并发的服务器
随机推荐
vChain: Enabling Verifiable Boolean Range Queries over Blockchain Databases(sigmod‘2019)
taobao.trades.sold.get-查询卖家已卖出的交易数据(根据创建时间),淘宝店铺卖出订单查询API接口,淘宝R2接口,淘宝oAuth2.0交易接口代码分享
Bit by bit of OpenCV calling USB camera
mathjax 入门(web显示数学公式,矢量的)
IE 浏览器正式退休
MFC timer usage
mathML转latex
Ad20 cannot select the solution of component packaging in PCB editor
obsidian安装第三方插件——无法加载插件
【C语音】详解指针进阶和注意点(2)
C language exercises - (array)
Full of knowledge points, how to use JMeter to generate encrypted data and write it to the database? Don't collect it quickly
##51单片机实验之简易验证码发生器
报错:npm WARN config global `--global`, `--local` are deprecated. Use `--location=global` instead.
JMeter script parameterization
STM32标准固件库函数名(一)
C# 线程传参
Contrôleur pour threejs cube Space Basic Controller + Inertial Control + Flight Control
Edit the formula with MathType, and set it to include only mathjax syntax when copying and pasting
MQ tutorial | exchange (switch)