aspnetcore 使用serilog日志
2022-02-19 13:25
2341 查看
而在实际项目开发中,使用第三方日志框架来记录日志也是非常多的,首先一般基础的内置日志记录器在第三方日志框架中都有实现,然后很多第三方日志框架在功能上更强大和丰富,能满足我们更多的项目分析和诊断的需求。常用的有log4net,更复杂的elk,项目中有用到exceptionless。下面说的是serilog:
首先建个aspnetcorewebapi6.0的项目
安装组件:
Seq — centralized structured logs for .NET, Java, Node.js (datalust.co)
using Serilog; using Serilog.Events; // Setup serilog in a two-step process. First, we configure basic logging // to be able to log errors during ASP.NET Core startup. Later, we read // log settings from appsettings.json. Read more at // https://github.com/serilog/serilog-aspnetcore#two-stage-initialization. // General information about serilog can be found at // https://serilog.net/ Log.Logger = new LoggerConfiguration() .MinimumLevel.Override("Microsoft", LogEventLevel.Information) .Enrich.FromLogContext() .WriteTo.Console() .CreateBootstrapLogger(); try { Log.Information("Starting the web host"); var builder = WebApplication.CreateBuilder(args); // Full setup of serilog. We read log settings from appsettings.json builder.Host.UseSerilog((context, services, configuration) => configuration .ReadFrom.Configuration(context.Configuration) .ReadFrom.Services(services) .Enrich.FromLogContext()); // Add services to the container. builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); var app = builder.Build(); // Configure the HTTP request pipeline. app.UseSerilogRequestLogging(configure => { configure.MessageTemplate = "HTTP {RequestMethod} {RequestPath} ({UserId}) responded {StatusCode} in {Elapsed:0.0000}ms"; }); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } app.UseHttpsRedirection(); app.UseAuthorization(); app.MapControllers(); app.Run(); } catch (Exception ex) { Log.Fatal(ex, "Host terminated unexpexctedly"); } finally { Log.CloseAndFlush(); }
{ //"Logging": { // "LogLevel": { // "Default": "Information", // "Microsoft.AspNetCore": "Warning" // } //}, "Serilog": { "Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File", "Serilog.Sinks.Seq" ], "MinimumLevel": "Information", // Where do we want to write our logs to? Choose from a large number of sinks: // https://github.com/serilog/serilog/wiki/Provided-Sinks. "WriteTo": [ { "Name": "Console" }, { "Name": "File", "Args": { "path": "Logs/log.txt" } }, { "Name": "Seq", "Args": { "serverUrl": "http://localhost:8888" } } ], "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ], "Properties": { "Application": "AspNetCoreSerilogDemo" } }, "AllowedHosts": "*" }
运行结果如下,已替换系统自带information:
请求跟踪分析:
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)
示例代码:
exercise/AspNetCoreSerilogDemo at master · liuzhixin405/exercise (github.com)
相关文章推荐
- AspNetCore 使用log4net+IExceptionFilter 记录错误日志
- asp.net core使用serilog将日志推送到腾讯云日志服务
- 在asp.net web api 2 (ioc autofac) 使用 Serilog 记录日志
- 在asp.net web api 2 (ioc autofac) 使用 Serilog 记录日志
- AspNetCore 使用NLog日志,NLog是基于.NET平台开的类库!(又一神器)
- 使用Global.asax在ASP.NET中记录错误日志
- 开发日志:使用Asp.Net中的"Forms"验证方式,操作用户权限
- 在ASP.NET中记录错误日志(使用Global.asax)
- 使用docker-compose搭建AspNetCore开发环境
- 在ASPnetcore MVC中使用efcore,DBfrist
- 在ASP.NET程序中使用事件日志的条件——关于注册表的访问控制表
- ASP.NET Core 开发-Logging 使用NLog 写日志文件
- log4net 使用笔记(asp.netcore)
- asp.Net Core免费开源分布式异常日志收集框架Exceptionless安装配置以及简单使用图文教程
- 使用IdentityServer4,在一个ASPNetCore项目中,配置oidc和api的AccessToken两种认证授权
- AspnetCore WebApi使用Swagger简单入门
- Asp.NetCore ResposeCache 缓存的使用
- ASP.NET使用log4Net日志组件教程(每天产生一个日志及日志按大小切割)
- 在ASP.NET MVC 3中使用日志记录组件Elmah和NLog
- 如何使用Apache log4net库与ASP.NET MVC 5日志记录