日志系统Logging


日志级别:

Trance

一:输出到控制台

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();

using (var sp = sc.BuildServiceProvider())
{
    TestService ts= sp.GetRequiredService();
    ts.ConsoleLog();
}

class TestService
{
    private readonly ILogger logger;

    public TestService(ILogger _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" ?>
"http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

    
        
        "asyncFile" xsi:type="AsyncWrapper">
            
            "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" />
        
        
        "colorConsole" xsi:type="ColoredConsole" layout="[${date:format=HH\:mm\:ss}]:${message} ${exception:format=message}" />
    

    
    
     
    "*" minlevel="Trace" writeTo="asyncFile" /> 
    "*" minlevel="Warn" writeTo="colorConsole" />
  

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();

using (var sp = sc.BuildServiceProvider())
{
    TestService ts= sp.GetRequiredService();
    ts.ConsoleLog();
}

class TestService
{
    private readonly ILogger logger;

    public TestService(ILogger _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,"计算出错");
        }
        
    }

}

查看结构化输出: