一、安装包
第一个是主包,第二个是将日志输出到控制台,第三个是将日志输出到文件中;
二、在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}InfoInfo.txt", restrictedToMinimumLevel: LogEventLevel.Debug, rollingInterval: RollingInterval.Day) //2. for error file sink .WriteTo.File($@".Logs{DateTime.Now.Year}-{DateTime.Now.Month}{DateTime.Now.Day}ErrorError.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中;