环境 :ASP.NET 6.0 项目:WebApi Nuget包:Serilog.AspNetCore、 Newtonsoft.Json

前期准备

Serilog

安装Nuget Serilog NuGet Gallery | Serilog.AspNetCore 6.1.1-dev-00295

官网 Serilog — simple .NET logging with fully-structured events

创建过滤器

操作拦截过滤器

public class ActionFilterLog : IActionFilter
{
    public void OnActionExecuting(ActionExecutingContext context)
    {
        if (!context.ModelState.IsValid)
        {
            Log.Error($"请求参数:{JsonConvert.SerializeObject(context.ActionArguments)}");
            Log.Error($"返回参数:{JsonConvert.SerializeObject(context.Result)}");
        }
        else
        {
            Log.Information($"请求参数:{JsonConvert.SerializeObject(context.ActionArguments)}");
        }
    }

    public void OnActionExecuted(ActionExecutedContext context)
    {
        Log.Information($"返回参数:{JsonConvert.SerializeObject(context.Result)}");
    }
}

异常拦截过滤器

public class ExceptionFilterLog:IExceptionFilter
{
    public void OnException(ExceptionContext context)
    {
        Log.Error($"返回参数:{JsonConvert.SerializeObject(context.Result)}");
    }
}

服务注入

using Serilog;
Log.Logger = new LoggerConfiguration()
    .WriteTo.Console() // 输出到控制台
    .WriteTo.File("Logs/log-.log", rollingInterval: RollingInterval.Day) //输出到文件
    .CreateLogger();
var builder = WebApplication.CreateBuilder(args).Inject();
builder.Services.AddControllers()
    .AddMvcFilter<LogActionFilter.ActionFilterLog>()
    .AddMvcFilter<LogActionFilter.ExceptionFilterLog>()
    .AddJsonOptions(option =>
    {
        option.JsonSerializerOptions.Converters.AddDateFormatString("yyyy-MM-dd HH:mm:ss");
        option.JsonSerializerOptions.Encoder = JavaScriptEncoder.Create(UnicodeRanges.All);
    });
...
builder.Host.UseSerilog();
...
var app = builder.Build();
...
app.UseSerilogRequestLogging();
...
app.Run();

启动

console

效果

log

good

最后修改:2023 年 02 月 28 日
如果觉得我的文章对你有用,请随意赞赏