当前位置:网站首页>. 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
边栏推荐
- LeetCode - 搜索二维矩阵
- Error: NPM warn config global ` --global`, `--local` are deprecated Use `--location=global` instead.
- 4、数组指针和指针数组
- GeoServer offline map service construction and layer Publishing
- Advanced C language (realize simple address book)
- Xilinx Vivado set *.svh as SystemVerilog Header
- 广州市应急管理局发布7月高温高湿化工安全提醒
- Full of knowledge points, how to use JMeter to generate encrypted data and write it to the database? Don't collect it quickly
- Large top heap, small top heap and heap sequencing
- Fundamentals of software testing
猜你喜欢

STM32 library function for GPIO initialization

YoloV6训练:训练自己数据集遇到的各种问题

Yolov6 training: various problems encountered in training your dataset

About text selection in web pages and counting the length of selected text

Introduction to mathjax (web display of mathematical formulas, vector)

Why can't programmers who can only program become excellent developers?

MFC timer usage

广州市应急管理局发布7月高温高湿化工安全提醒

Edit the formula with MathType, and set it to include only mathjax syntax when copying and pasting

Btrace- (bytecode) dynamic tracking tool
随机推荐
Xilinx Vivado set *. svh as SystemVerilog Header
[Space & single cellomics] phase 1: single cell binding space transcriptome research PDAC tumor microenvironment
C# 线程传参
MFC CString 转 char*
【NOI模拟赛】刮痧(动态规划)
2、const 型指针
c语言入门--数组
taobao. trade. memo. Add (add remarks to a transaction) interface, Taobao store flag insertion interface, Taobao order flag insertion API interface, oauth2.0 interface
forEach的错误用法,你都学废了吗
LeetCode 2310. 个位数字为 K 的整数之和
1、编辑利器vim
[development environment] install the visual studio community 2013 development environment (download the installation package of visual studio community 2013 with update 5 version)
用户隐私协议有些汉字编码不规范导致网页显示乱码,需要统一找出来处理一下
LeetCode_滑动窗口_中等_395.至少有 K 个重复字符的最长子串
Socket and socket address
4. Array pointer and pointer array
threejs的控制器 立方体空间 基本控制器+惯性控制+飞行控制
Arithmetic operations and related exercises in C language
871. Minimum refueling times: simple priority queue (heap) greedy question
解决el-radio-group 回显后不能编辑问题