如何在NET 6.0使用结构化的日志系统

 在我们的系统里面,有一项技术是必须使用的,那就是日志记录。我们在调试系统或者跟踪系统运行情况,都可以通过日志了解具体的情况。在项目开发中,我们有可能使用系统本身所带的日志系统,也有可能使用第三方日志框架来记录日志,首先一般基础的内置日志记录器在第三方日志框架中都有实现,然后很多第三方日志框架在功能上更强大和丰富,能满足我们更多的项目分析和诊断的需求。常用的有log4net,更复杂的ELK,项目中有用到Exceptionless。下面说的是Serilog:

  首先建个AspNetCoreWebAPI6.0的项目,当然也可以是AspNetCore Web MVC项目。

安装组件:Serilog.AspNetCore(6.0.1)和Serilog.Sinks.Seq(5.2.1)

Seq — centralized structured logs for .NET, Java, Node.js (datalust.co)

运行结果如下,已替换系统自带information:

复制代码
复制代码
 1 using Serilog;
 2 using Serilog.Events;
 3 
 4 // Setup serilog in a two-step process. First, we configure basic logging
 5 // to be able to log errors during ASP.NET Core startup. Later, we read
 6 // log settings from appsettings.json. Read more at
 7 // https://github.com/serilog/serilog-aspnetcore#two-stage-initialization.
 8 // General information about serilog can be found at
 9 // https://serilog.net/
10 Log.Logger = new LoggerConfiguration()
11             .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
12             .Enrich.FromLogContext()
13             .WriteTo.Console()
14             .CreateBootstrapLogger();
15 
16 try
17 {
18     Log.Information("Starting the web host");
19     var builder = WebApplication.CreateBuilder(args);
20     // Full setup of serilog. We read log settings from appsettings.json
21     builder.Host.UseSerilog((context, services, configuration) => configuration
22         .ReadFrom.Configuration(context.Configuration)
23         .ReadFrom.Services(services)
24         .Enrich.FromLogContext());
25     // Add services to the container.
26 
27     builder.Services.AddControllers();
28     // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
29     builder.Services.AddEndpointsApiExplorer();
30     builder.Services.AddSwaggerGen();
31 
32     var app = builder.Build();
33 
34     // Configure the HTTP request pipeline.
35     app.UseSerilogRequestLogging(configure =>
36     {
37         configure.MessageTemplate = "HTTP {RequestMethod} {RequestPath} ({UserId}) responded {StatusCode} in {Elapsed:0.0000}ms";
38     });
39     // Configure the HTTP request pipeline.
40     if (app.Environment.IsDevelopment())
41     {
42         app.UseSwagger();
43         app.UseSwaggerUI();
44     }
45 
46     app.UseHttpsRedirection();
47 
48     app.UseAuthorization();
49 
50     app.MapControllers();
51 
52     app.Run();
53 }
54 catch
55 (Exception ex)
56 {
57     Log.Fatal(ex, "Host terminated unexpexctedly");
58 }
59 finally
60 {
61     Log.CloseAndFlush();
62 }
复制代码
复制代码

 

复制代码
复制代码
 1 {
 2   //"Logging": {
 3   //  "LogLevel": {
 4   //    "Default": "Information",
 5   //    "Microsoft.AspNetCore": "Warning"
 6   //  }
 7   //},
 8   "Serilog": {
 9     "Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File", "Serilog.Sinks.Seq" ],
10     "MinimumLevel": "Information",
11     // Where do we want to write our logs to? Choose from a large number of sinks:
12     // https://github.com/serilog/serilog/wiki/Provided-Sinks.
13     "WriteTo": [
14       {
15         "Name": "Console"
16       },
17       {
18         "Name": "File",
19         "Args": { "path": "Logs/log.txt" }
20       },
21       {
22         "Name": "Seq",
23         "Args": { "serverUrl": "http://localhost:8888" }
24       }
25     ],
26     "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
27     "Properties": {
28       "Application": "AspNetCoreSerilogDemo"
29     }
30   },
31   "AllowedHosts": "*"
32 }
复制代码
复制代码

 

 

请求跟踪分析:

复制代码
复制代码
复制代码
using Microsoft.AspNetCore.Mvc;

namespace AspNetCoreSerilogDemo.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class SeriLogDemoController : ControllerBase
    {
       

        private readonly ILogger<SeriLogDemoController> _logger;

        public SeriLogDemoController(ILogger<SeriLogDemoController> logger)
        {
            _logger = logger;
        }

        [HttpGet]
        public string String()
        {
            _logger.LogInformation("this is serilog...");
            return "Suscess";
        }
     
    }
}
复制代码
复制代码
复制代码

 配置文件里面输出路径有"Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File", "Serilog.Sinks.Seq" ],所以同样会输出到日志文件中,指定路径和文件名:

 

更多更详细功能参考:

Serilog — simple .NET logging with fully-structured events

Seq — centralized structured logs for .NET, Java, Node.js (datalust.co)

天下国家,可均也;爵禄,可辞也;白刃,可蹈也;中庸不可能也
 
转 https://www.cnblogs.com/PatrickLiu/p/16753606.html
posted @   dreamw  阅读(242)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
历史上的今天:
2021-03-10 docker构建镜像
2021-03-10 [C#]LINQ中如何按实体的某个属性去重
2021-03-10 .NET Core项目部署到Linux(Centos7)(九)防火墙配置,允许外网或局域网访问.NET Core站点
2021-03-10 c++ 手动加载 netcore_在基于Debian开发的Deepin上快速搭建.net core开发环境
2021-03-10 git的基本使用流程演示
2021-03-10 .NET5都来了,你还不知道怎么部署到linux?最全部署方案,总有一款适合你
2021-03-10 DotNetCore深入了解:HTTPClientFactory类
点击右上角即可分享
微信分享提示