1、添加自定义日志过滤器类
using Serilog;
using Microsoft.AspNetCore.Mvc.Filters;
namespace ADTO.CMS.Common.Filter
{
/// <summary>
/// 日志记录过滤器
/// </summary>
public class LogActionFilter : IActionFilter
{
/// <summary>
/// 在动作执行前记录日志
/// </summary>
/// <param name="context"></param>
public void OnActionExecuting(ActionExecutingContext context)
{
Log.Information("Starting action {ActionName} on controller {ControllerName}",
context.ActionDescriptor.RouteValues["action"],
context.ActionDescriptor.RouteValues["controller"]);
}
/// <summary>
/// 动作完成后
/// </summary>
/// <param name="context"></param>
public void OnActionExecuted(ActionExecutedContext context)
{
if (context.Exception != null)
{
// 如果发生异常,记录错误日志
Log.Error(context.Exception, "An error occurred in action {ActionName} on controller {ControllerName}",
context.ActionDescriptor.RouteValues["action"],
context.ActionDescriptor.RouteValues["controller"]);
}
else
{
// 在动作执行后记录日志
Log.Information("Completed action {ActionName} on controller {ControllerName} with status code {StatusCode}",
context.ActionDescriptor.RouteValues["action"],
context.ActionDescriptor.RouteValues["controller"],
context.HttpContext.Response.StatusCode);
}
}
}
}
2、在Program中注入日志过滤器
#region 日志过滤器
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.WriteTo.Console()
.WriteTo.File("logs/myapp.txt", rollingInterval: RollingInterval.Day) //写入文本文件
.CreateLogger();
builder.Services.AddControllers(options =>
{
options.Filters.Add(typeof(LogActionFilter));
});
#endregion