当前位置:网站首页>How to customize Net6.0 logging
How to customize Net6.0 logging
2022-07-20 08:04:00 【biyusr】
In this chapter , That is, the first part of the whole series will introduce how to customize logging ( Series content review 《 Get along well with ASP.NET 6.0 frame - preface 》). The default logging is only written to the console or debug window , This is good in most cases , But sometimes you need to write to a file or database , perhaps , You may want to expand other information logged . In these cases , You need to know how to change the default logging .
In this chapter , We will introduce the following topics :
Configure logging
Create custom logging
Use a third party logging framework
The above topics involve ASP.NET Core
Framework of the Host
layer .
technical requirement
To demonstrate , We create a ASP.NET Core MVC
Applications . Please open the console 、shell
or Bash
terminal , Then switch to the working directory , Then use the following command to create a new application :
dotnet new mvc -n LoggingSample -o LoggingSample
stay Visual Studio
Double click to open the project , Or type the following command in the console to use Visual Studio Code
Open the project :
cd LoggingSample code .
Configure logging
stay ASP.NET Core
In an earlier version ( namely 2.0 Version before version ), The log record is in Startup.cs
Configured . after Startup.cs
The document is gradually simplified , Many configurations have been moved to Program.cs
Of WebHostBuilder
, The log record is also moved to WebHostBuilder
.
stay ASP.NET Core 3.1
And later ,Program.cs
Files become more generic ,IHostBuilder
Will be created first , The key to booting the application is to boot it ( We will explain in detail later IHostBuilder
), adopt IHostBuilder
, We can create IWebHostBuilder
To configure ASP.NET Core
:
public class Program {
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args).ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
stay ASP.NET Core 6.0
in ,Microsoft
Introduced a mini..., which simplifies the configuration API(minimal API
) Method . This method does not use Startup
file , Instead, add all configurations to Program.cs
file , The following code snippet :
var builder = WebApplication.CreateBuilder(args);
// Add service to container .
builder.Services.AddControllersWithViews();
var app = builder.Build();
…
stay ASP.NET Core
, You can overwrite and customize almost everything , Including logging .IWebHostBuilder
There are many ways to extend , Allows us to override the default behavior of different functions . To override the default settings for logging , We need to use ConfigureLogging
Method .
The following code snippet shows the same logging as the one above ConfigureWebHostDefaults()
The logging configured in the method is almost identical :
Host.CreateDefaultBuilder(args).ConfigureWebHostDefaults(webBuilder =>{
webBuilder.ConfigureLogging((hostingContext, logging) => {
logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
logging.AddConsole();
logging.AddDebug();
}).UseStartup<Startup>();
Use
minimal API
Method , We no longer needConfigureLogging
Method , We can use it directlyWebApplicationBuilder
OfLogging
attribute :
builder.Logging.AddConfiguration(builder.Configuration.GetSection("Logging"));
builder.Logging.AddConsole();
builder.Logging.AddDebug();
Now we have seen how to configure logging , Next, let's look at how to customize logging .
Create custom logging
To demonstrate , Let's create a small and simple logger here , It can shade log entries in the console with a specific log level . This log record is called ColoredConsoleLogger
, It will use LoggerProvider
establish . To specify the color and log level , We also need to add a configuration class Configuration
.
In the following code snippet , These three key classes will be created separately (Configuration
、LoggerProvider
and Logger
):
1.ColoredConsoleLoggerConfiguration
Let's create a name CustomLogger.cs
In the file of , It is associated with Program.cs
In the same folder , We are CustomLogger.cs
Created in ColoredConsoleLoggerConfiguration
, This configuration class contains three settable properties :LogLevel
、EventId
and Color
:
public class ColoredConsoleLoggerConfiguration
{
public LogLevel LogLevel { get; set; } = LogLevel.Warning;
public int EventId { get; set; } = 0;
public ConsoleColor Color { get; set; } = ConsoleColor.Yellow;
}
2.ColoredConsoleLoggerProvider
Next , We need a provider to retrieve the configuration and create the actual logging instance
public class ColoredConsoleLoggerProvider : ILoggerProvider
{
private readonly ColoredConsoleLoggerConfiguration _config;
private readonly ConcurrentDictionary<string, ColoredConsoleLogger> _loggers = new ConcurrentDictionary<string,ColoredConsoleLogger>();
public ColoredConsoleLoggerProvider (ColoredConsoleLoggerConfiguration config)
{
_config = config;
}
public ILogger CreateLogger(string categoryName)
{
return _loggers.GetOrAdd(categoryName,name => new ColoredConsoleLogger(name, _config));
}
public void Dispose()
{
_loggers.Clear();
}
}
Don't forget to introduce
System.Collections.Concurrent
3.ColoredConsoleLogger
The third type is the logger we really use :
public class ColoredConsoleLogger : ILogger
{
private static readonly object _lock = new Object();
private readonly string _name;
private readonly ColoredConsoleLoggerConfiguration _config;
public ColoredConsoleLogger(
string name,
ColoredConsoleLoggerConfiguration config)
{
_name = name;
_config = config;
}
public IDisposable BeginScope<TState>(TState state)
{
return null;
}
public bool IsEnabled(LogLevel logLevel)
{
return logLevel == _config.LogLevel;
}
public void Log<TState>(
LogLevel logLevel,
EventId eventId,
TState state,
Exception exception,
Func<TState, Exception, string> formatter)
{
if (!IsEnabled(logLevel))
{
return;
}
lock (_lock)
{
if (_config.EventId == 0 || _config.EventId == eventId.Id)
{
var color = Console.ForegroundColor;
Console.ForegroundColor = _config.Color;
Console.Write($"{logLevel} - ");
Console.Write($"{eventId.Id} - {_name} - ");
Console.Write($"{formatter(state, exception)}\n");
Console.ForegroundColor = color;
}
}
}
}
Now we need lock
( lock ) Console output —— This is because the console itself is not really thread safe , Incorrect coloring may occur .
After completion , We can insert new records into Program.cs
The configuration of .
using LoggingSample;
builder.Logging.ClearProviders();
var config = new ColoredConsoleLoggerConfiguration
{
LogLevel = LogLevel.Information,
Color = ConsoleColor.Red
};
builder.Logging.AddProvider(new ColoredConsoleLoggerProvider(config));
First, we need to introduce LoggerSample
Namespace .
using LoggingSample;
If you don't want to use the existing logging framework , You can clear all previously added log framework providers
builder.Logging.ClearProviders();
then , We call AddProvider
To add ColoredConsoleLoggerProvider
example .
Different log levels are configured here , You can use this method to send an email about the error , Or log debug messages to other log receivers, and so on .
The following figure shows the color output of the log frame :
In many cases , There is no point in writing a custom logging framework , Because there are already many excellent third-party logging frameworks available , for example ELMAH
、log4net
and NLog
.
below , We'll show you how to ASP.NET Core
Use in NLog
.
Use a third party logging framework NLog
NLog
It is the first one that can be used for ASP.NET Core
The log framework of ,NLog
Provides a logging provider plug-in , It can be easily inserted ASP.NET Core
.( You can go through NuGet
find NLog)
1. To configure Nlog
We need to add a NLog.Config
The configuration file , Used to define two different logging records :
All standard messages are recorded in a log file ;
The custom message is recorded in another file
<targets>
<!-- Standard message -->
<target xsi:type="File" name="allfile" fileName="C:\git\dotnetconf\001-logging\nlog-all-${shortdate}.log"
layout="${longdate}|${event-properties:item=EventId.Id}|${logger}|${uppercase:${level}}|${message} ${exception}" />
<!-- Custom message -->
<target xsi:type="File" name="ownFile-web" fileName="C:\git\dotnetconf\001-logging\nlog-own-${shortdate}.log"
layout="${longdate}|${event-properties:item=EventId.Id}|${logger}|${uppercase:${level}}| ${message} ${exception}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}" />
<target xsi:type="Null" name="blackhole" />
</targets>
<!-- rules to map from logger name to target -->
<rules>
<!--All logs, including from Microsoft-->
<logger name="*" minlevel="Trace" writeTo="allfile" />
<!--Skip Microsoft logs and so log only own logs-->
<logger name="Microsoft.*" minlevel="Trace" writeTo="blackhole" final="true" />
<logger name="*" minlevel="Trace" writeTo="ownFile-web" />
</rules>
2. introduce NuGet package
And then we need to NuGet
add to NLog
Of ASP.NET Core
package :
dotnet add package NLog.Web.AspNetCore
3. take NLog
And IWebHostBuilder
Use a combination of
eliminate ConfigureLogging
Other providers in the method , Use UseNLog()
Methods will NLog
And IWebHostBuilder
Use a combination of :
Host.CreateDefaultBuilder(args).ConfigureWebHostDefaults(webBuilder => {
webBuilder.ConfigureLogging((hostingContext,logging) => {
// Clear other providers
logging.ClearProviders();
logging.SetMinimumLevel(LogLevel.Trace);
}).UseNLog().UseStartup<Startup>();
});
Use minimal API
It looks much simpler :
using NLog.Web;
var builder = WebApplication.CreateBuilder(args);
// Clear other providers
builder.Logging.ClearProviders();
builder.Logging.SetMinimumLevel(LogLevel.Trace);
builder.WebHost.UseNLog();
ad locum , You can add as many logging providers as you need .
review & reflection
Now? , Let's review what this article covers :
Configure logging
Create custom logging
Use a third party logging framework
reflection : How should we customize the configuration of the application ? Welcome to the next article 《 How to customize .NET 6.0 Application configuration of 》.
边栏推荐
- C#使用Objects Comparer进行对象比较
- Option classes shared by MFC and ATL
- BERT-tutorial
- Flask框架——数据库操作命令(增删改查)
- 拯救不开心!我的机器人心理医生;机器学习的KPI千里追踪术;YOLO v7的PyTorch实现;李航新书『机器学习方法』开放试读 | ShowMeAI资讯日报
- C语言编程题:简单的a+b
- Tkinter module GUI Graphical programming practice (VIII) -- Chinese chess (including super detailed and complete source code, free download link of complete program)
- Flask框架——蓝图、flask-script
- Why don't people buy a house?
- Firewall port forwarding
猜你喜欢
请求转发和请求重定向有什么区别?
Rock paper will develop ar game for San Diego priest baseball team
Flask framework - model relationships (many to many)
面试题总结(4) Tcp / Ip 四层模型,三次握手四次挥手,多一次少一次可以不,NIO的实现原理
【信号调理】用“晶体三极管”搭建CE放大器的实操经验分享
Hc-sr04 ultrasonic module driven by 51 single chip microcomputer (LCD1602 display)
Initial experience of maixhub online training
I'm confused after work. How to do a qualified test?
【玩物立志-scratch少儿编程】骑上小摩托(动态背景+摄像头控制操作)
无重叠区间[贪心练习]
随机推荐
卡尔曼滤波——超声波测距
微信小程序动态样式|参数传递
Meta CTO: Cambria will be equipped with handle for the first time, and the new product will last for 12-24 months
Alfred的常见设置
接口测试主要测试哪方面?需要哪些技能?要怎么学习?
TS之namespace与module
New concept three volume notes-01
CSimpleArray
C#中的Explicit和Implicit了解一下吧
Option classes shared by MFC and ATL
中国碳酸锶行业研究与发展前景研究报告(2022版)
.NET Core 使用 ImageSharp 生成图片
.NET 全场景开发终于到来了
升级PHP8中踩到的坑
开发提测标准(简易版)
Etcd database source code analysis -- etcdserver run apply process
YoloV7——配置YOLOV7(一)
Summary of interview questions (4) TCP / IP four-layer model, three handshakes and four waves, one more and one less. No, the implementation principle of NiO
Jetpack compose is better than XML
请求转发和请求重定向有什么区别?