在我们的系统里面,有一项技术是必须使用的,那就是日志记录。我们在调试系统或者跟踪系统运行情况,都可以通过日志了解具体的情况。在项目开发中,我们有可能使用系统本身所带的日志系统,也有可能使用第三方日志框架来记录日志,首先一般基础的内置日志记录器在第三方日志框架中都有实现,然后很多第三方日志框架在功能上更强大和丰富,能满足我们更多的项目分析和诊断的需求。常用的有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)
天下国家,可均也;爵禄,可辞也;白刃,可蹈也;中庸不可能也