欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

NetCore3.1 Serilog日志

程序员文章站 2023-12-30 16:18:22
...

系统环境

  • vs 2019 preview
  • win10
  • net core 3.1

 

一、安装nuget包

1.Serilog.AspNetCore

2.Serilog.Extensions.Logging.File        (输出到文件)

Serilog-aspnetcore GitHub:https://github.com/serilog/serilog-aspnetcore

NetCore3.1 Serilog日志

 

二、 注册Serilog,修改Program文件

新建ASPnet core3.1网站,修改Program文件

public class Program
    {
        public static void Main(string[] args)
        {
            
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureLogging((context, loggingBuilder) =>
                {
                    //这里是清空所有日志提供程序,包括aspnetcore框架自带的控制台、调试窗口等
                    //loggingBuilder.ClearProviders();

                    
                })
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                })
               
                //添加Serilog
                .UseSerilog((hostingContext, loggerConfiguration) =>
                {
                    //从appsettings.json中读取配置
                    loggerConfiguration.ReadFrom.Configuration(hostingContext.Configuration)
                    .Enrich.FromLogContext()
                    ;
                })
                ;
    }

 

三、修改appsetting.json,添加下面json

"Serilog": {
    "WriteTo": [
      {
        "Name": "RollingFile",
        "Args": {
          "pathFormat": "Serilogs\\{Date}.txt",
          "RestrictedToMinimumLevel": "Warning",
          "rollingInterval": "Day",
          "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}"
        }
      },
      {
        "Name": "Console",
        "Args": {}
      }
    ],
    "MinimumLevel": {
      "Default": "Debug",
      "Override": {
        "Microsoft": "Information",
        "System": "Information"
      }
    }
  }

 

四、使用日志

通过构造函数注入日志接口,便可直接使用了

public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;

        private readonly ILogger _logger1;
        private readonly ILogger _logger2;

        public HomeController(ILogger<HomeController> logger, ILoggerFactory _loggerFactory)
        {
            _logger = logger;
            _logger1 = _loggerFactory.CreateLogger(typeof(HomeController));
            _logger2 = _loggerFactory.CreateLogger<HomeController>();
        }

        public IActionResult Index()
        {
            _logger.LogDebug("debug");
            _logger.LogError("error");
            _logger.LogWarning("Warn");
            _logger.LogInformation("Info");

            _logger1.LogDebug("debug");
            _logger1.LogError("error");
            _logger1.LogWarning("Warn");
            _logger1.LogInformation("Info");

            _logger2.LogDebug("debug");
            _logger2.LogError("error");
            _logger2.LogWarning("Warn");
            _logger2.LogInformation("Info");


            return View();
        }
}

 

五、查看日志生成目录

NetCore3.1 Serilog日志

 

六、扩展

上面是通过读取配置文件来实现Serilog日志,可通过WriteTo方法直接通过代码可输出到文件、控制台

                //添加Serilog
                .UseSerilog((hostingContext, loggerConfiguration) =>
                {
                    
                    loggerConfiguration
                    .WriteTo.Debug()
                    //输出格式: 从头到尾分别是:日期、日志级别、日志内容、换行、异常信息
                    //输出到文件
                    .WriteTo.File("Serilogs\\serilog.txt", rollingInterval: RollingInterval.Day, outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}")
                    //输出到控制台
                    .WriteTo.Console(
                        outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj} {Properties:j}{NewLine}{Exception}");
                })

 

相关标签: NetCore

上一篇:

下一篇: