日志级别:
Trance<Debug<Information<Waring<Error<Crirical
一:输出到控制台
1.新建控制台应用:
2.安装Nuget:
Install-Package Microsoft.Extensions.Logging
Install-Package Microsoft.Extensions.Logging.Console
3.DI依赖注入
ServiceCollection sc=new ServiceCollection(); sc.AddLogging(log => { //添加日志服务 log.AddConsole(); //输出到控制台 log.SetMinimumLevel(LogLevel.Trace);//设置监控日志级别 });
---Program.cs
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; ServiceCollection sc=new ServiceCollection(); sc.AddLogging(log => { //添加日志服务 log.AddConsole(); //输出到控制台 log.SetMinimumLevel(LogLevel.Trace);//设置监控日志级别(不增加默认Information) }); sc.AddScoped<TestService>(); using (var sp = sc.BuildServiceProvider()) { TestService ts= sp.GetRequiredService<TestService>(); ts.ConsoleLog(); } class TestService { private readonly ILogger<TestService> logger; public TestService(ILogger<TestService> _logger) { this.logger = _logger; } public void ConsoleLog() { logger.LogInformation("LogInformation"); logger.LogDebug("LogDebug"); try { int a = 0; int b = 1 / a; } catch (Exception ex) { logger.LogError(ex,"计算出错"); } } }
--查看结果:
二:输出到文本
.NET第三方日志框架 Log4Net、Nlog、SeriLog等
Log4Net:单独的一套,不能与.netCore融合。.net framework常用
Nlog:配合.netCore使用简单,配置基本日志够用,对于结构化日志ELK之类使用起来可能力不从心
SeriLog:支持.netCore 配置比较复杂,对结构化日志支持较好
Nlog使用:
1.Install-Package NLog.Extensions.Logging
2.新增nlog.config
<?xml version="1.0" encoding="utf-8" ?> <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <targets> <!--此部分中的所有目标将自动异步--> <target name="asyncFile" xsi:type="AsyncWrapper"> <!--项目日志保存文件路径说明fileName="${basedir}/保存目录,以年月日的格式创建/${shortdate}/${记录器名称}-${单级记录}-${shortdate}.txt"--> <target name="log_file" xsi:type="File" fileName="${basedir}/Logs/${shortdate}/${logger}-${level}-${shortdate}.txt" layout="${longdate} | ${message} ${onexception:${exception:format=message} ${newline} ${stacktrace} ${newline}" archiveFileName="${basedir}/archives/${logger}-${level}-${shortdate}-{#####}.txt" archiveAboveSize="102400" archiveNumbering="Sequence" concurrentWrites="true" keepFileOpen="false" /> </target> <!--使用可自定义的着色将日志消息写入控制台--> <target name="colorConsole" xsi:type="ColoredConsole" layout="[${date:format=HH\:mm\:ss}]:${message} ${exception:format=message}" /> </targets> <!--规则配置,final - 最终规则匹配后不处理任何规则--> <rules>
<logger name="Microsoft.*" minlevel="Info" writeTo="" final="true" />
<logger name="*" minlevel="Trace" writeTo="asyncFile" />
<logger name="*" minlevel="Warn" writeTo="colorConsole" />
</rules>
</nlog>
3.在日志服务中增加Nlog
ServiceCollection sc=new ServiceCollection(); sc.AddLogging(log => { //添加日志服务 log.AddConsole(); //输出到控制台 log.AddNLog(); //添加Nlog log.SetMinimumLevel(LogLevel.Trace);//设置监控日志级别(不增加默认Information) });
再运行:
来看Bin目录下:
SeriLog使用:
1.安装package:
Install-Package Serilog.AspNetCore
2.修改日志配置
sc.AddLogging(log => { //添加日志服务 //log.AddConsole(); //输出到控制台 //log.AddNLog(); //添加Nlog //log.SetMinimumLevel(LogLevel.Trace);//设置监控日志级别(不增加默认Information) Log.Logger = new LoggerConfiguration() .MinimumLevel.Debug(). Enrich.FromLogContext() .WriteTo.Console(new JsonFormatter()).CreateLogger(); log.AddSerilog(); });
--Program.cs
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using NLog.Extensions.Logging; using Serilog; using Serilog.Formatting.Json; ServiceCollection sc=new ServiceCollection(); sc.AddLogging(log => { //添加日志服务 //log.AddConsole(); //输出到控制台 //log.AddNLog(); //添加Nlog //log.SetMinimumLevel(LogLevel.Trace);//设置监控日志级别(不增加默认Information) Log.Logger = new LoggerConfiguration() .MinimumLevel.Debug(). Enrich.FromLogContext() .WriteTo.Console(new JsonFormatter()).CreateLogger(); log.AddSerilog(); }); sc.AddScoped<TestService>(); using (var sp = sc.BuildServiceProvider()) { TestService ts= sp.GetRequiredService<TestService>(); ts.ConsoleLog(); } class TestService { private readonly ILogger<TestService> logger; public TestService(ILogger<TestService> _logger) { this.logger = _logger; } public void ConsoleLog() { var serilog = new { name = "SeriLog", Package = "Serilog.AspNetCore", PackageManager= "Install - Package Serilog.AspNetCore" }; logger.LogInformation($"serilog{@serilog}");//支持直接用@结构化对象 logger.LogInformation("LogInformation"); logger.LogDebug("LogDebug"); try { int a = 0; int b = 1 / a; } catch (Exception ex) { logger.LogError(ex,"计算出错"); } } }
查看结构化输出: