AspNetCore中使用Serilog记录日志
一、安装包
第一个是主包,第二个是将日志输出到控制台,第三个是将日志输出到文件中;
二、在Program.cs中配置
public class Program { public static void Main(string[] args) { Log.Logger = new LoggerConfiguration() .MinimumLevel.Debug() .Enrich.FromLogContext().WriteTo.Console() // 1. for debug file sink .MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Debug) .WriteTo.File($@".\Logs\{DateTime.Now.Year}-{DateTime.Now.Month}\{DateTime.Now.Day}\Info\Info.txt", restrictedToMinimumLevel: LogEventLevel.Debug, rollingInterval: RollingInterval.Day) //2. for error file sink .WriteTo.File($@".\Logs\{DateTime.Now.Year}-{DateTime.Now.Month}\{DateTime.Now.Day}\Error\Error.txt", restrictedToMinimumLevel: LogEventLevel.Error, rollingInterval: RollingInterval.Day) .CreateLogger(); CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureLogging(loggingBuilder => { //清空所有日志提供程序,包括aspnetcore框架自带的控制台、调试窗口等 loggingBuilder.ClearProviders(); }) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }) .UseSerilog(/*(hostingContext, loggerConfiguration) => //从appsettings.json中读取配置 loggerConfiguration.ReadFrom.Configuration(hostingContext.Configuration) .Enrich.FromLogContext()*/); }
其中注释掉的UseSerilog中的内容是去appsetting.json中读取配置,因为写到文件夹中的路径我是写死在上边的;
如果要在appsetting.json中配置:
//"Serilog": { // "WriteTo": [ // { // "Name": "File", // "Args": { // "path": "./Logs/.txt", // "rollingInterval": "Day" // } // }, // { // "Name": "Console", // "Args": {} // } // ] //}
三、使用
[Route("api/[controller]/[action]")] [ApiController] public class SpiderController : ControllerBase { private readonly ILogger<SpiderController> _logger; public SpiderController( ILogger<SpiderController> logger) { _logger = logger; } [HttpPost] public async Task<IActionResult> InitSpider([FromBody] TaskItemDTo taskItemDto) { try { int i = 0; int j = 1; var a = j / i; return Ok(); } catch (Exception ex) { _logger.LogError(ex,ex.Message); return BadRequest(); } } }
结果:
我是将Debug级以上的保存在Info中,将Error级的保存在Error中;
================================更新(20220701)==================================
日志通常用于记录系统的错误日志:以上具体到每一个接口中Catch出来的错误日志,当接口很多时,可以利用异常过滤器拦截错误日志;
先定义过滤器:
public class CustomerExceptionFilter : Attribute, IExceptionFilter { private readonly ILogger<CustomerExceptionFilter> _logger; public CustomerExceptionFilter(ILogger<CustomerExceptionFilter> logger) { _logger = logger; } public void OnException(ExceptionContext context) { _logger.LogError(context.Exception,context.Exception.Message); context.Result = new JsonResult(new { code = 500, message = context.Exception.Message }); context.ExceptionHandled = true; } }
注入服务依赖:
services.AddMvc(options => { options.Filters.Add<CustomerExceptionFilter>(); });
Demo:
结果:
日志: