九.Net6 Serilog日志文件txt

一、Nuget下载包

Serilog

Serilog.AspNetCore

Serilog.Extensions.Logging

Serilog.Sinks.Async

Serilog.Sinks.Console

Serilog.Sinks.File

九.Net6 Serilog日志文件txt_第1张图片

 二、修改appsetting.json配置文件,控制输出环境,可自行选择输出到控制台还是文件

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  //serilog  begin
  "Serilog": {
    "MinimumLevel": {
      "Default": "Debug", //最小日志记录级别
      "Override": { //系统日志最小记录级别
        "Default": "Warning",
        "System": "Warning",
        "Microsoft": "Warning"
      }
    },
    "WriteTo": [
      { "Name": "Console" }, //输出到控制台
      {
        "Name": "Async", //Serilog.Sinks.Async
        "Args": {
          "configure": [
            {
              "Name": "File", //输出文件
              "Args": {
                "path": "log/log.txt",
                "outputTemplate": "{NewLine}Date:{Timestamp:yyyy-MM-dd HH:mm:ss.fff}{NewLine}LogLevel:{Level}{NewLine}Message:{Message}{NewLine}Exception:{Exception}{NewLine}---------------------------------------------------------------------------------------------------------",
                "rollingInterval": "3" //按天记录
              }
            }
          ]
        }
      }
    ]
    //serilog  end
  }
}

三、修改Program.cs入口文件

using Serilog;
using Serilog.Events;
using System.Reflection;

try
{
    var builder = WebApplication.CreateBuilder(args);
    #region 1.Serilog
    builder.Host.UseSerilog((context, logger) =>//注册Serilog
    {
        logger.ReadFrom.Configuration(context.Configuration);
        logger.Enrich.FromLogContext();
    });
    #endregion

    #region Swagger
    // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
    builder.Services.AddEndpointsApiExplorer();
    builder.Services.AddSwaggerGen(options =>
    {
        // using System.Reflection;
        //获取xml注释文件目录
        var xmlFilename = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
        //默认的第二个参数是false,这个是controller的注释,true时会显示注释,否则只显示方法注释
        options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename), true);
    });
    #endregion

    // Add services to the container.
    builder.Services.AddControllers();
    var app = builder.Build();
    // Configure the HTTP request pipeline.
    if (app.Environment.IsDevelopment())
    {
        app.UseSwagger();
        app.UseSwaggerUI();
    }

    app.UseAuthorization();

    app.MapControllers();

    app.Run();
}
catch (Exception ex)
{
    Log.Fatal(ex, "Host terminated unexpectedly");
}
finally
{
    Log.CloseAndFlush();
}

四、控制器写接口如下

private readonly ILogger _logger;
public LogController(ILogger logger)
{
    _logger = logger;
}

/// 
/// 测试日志
/// 
/// 
[HttpGet]
public IActionResult LogTest()
{
    _logger.LogInformation("Information 日志");
    _logger.LogDebug("debug 日志");
    _logger.LogError(new IOException(), "io 错误");
    return Ok();
}

五、F5运行,调用接口成功

 控制台九.Net6 Serilog日志文件txt_第2张图片

文本文件九.Net6 Serilog日志文件txt_第3张图片 六、将LogTest接口改为以下代码验证是否会主动补货异常,F5执行调用接口

/// 
/// 测试日志
/// 
/// 
[HttpGet]
public IActionResult LogTest()
{
    int i=Convert.ToInt32("a");
    return Ok();
}

异常补货并写入日志成功

九.Net6 Serilog日志文件txt_第4张图片

 关于怎么写入数据库,测试失败了,有待研究

你可能感兴趣的:(.NET,CORE,API,.netcore)