全局异常日志
- ExceptionMiddleware
public class ExceptionMiddleware
{
private readonly ILogger logger;
private readonly RequestDelegate next;
public ExceptionMiddleware(RequestDelegate next, ILogger<ExceptionMiddleware> logger)
{
this.logger = logger;
this.next = next;
}
public async Task Invoke(HttpContext context)
{
try
{
await next(context);
}
catch (Exception e)
{
await ExceptionHandlerAsync(context, e);
}
}
private async Task ExceptionHandlerAsync(HttpContext context, Exception e)
{
context.Response.ContentType = "application/json";
logger.LogError(e, context.Request.Path);
var result = new Response<string>()
{
status = 500,
msg = e.Message
};
await context.Response.WriteAsync(result.ToJson());
}
}
- Startup Configure
app.UseMiddleware<ExceptionMiddleware>();
Api 日志
- ApiLogFilter
public class ApiLogFilter : IAsyncActionFilter
{
private readonly ILogger logger;
public ApiLogFilter(ILogger<ApiLogFilter> logger)
{
this.logger = logger;
}
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
string actionArguments = context.ActionArguments.ToJson();
var resultContext = await next();
string url = resultContext.HttpContext.Request.Host + resultContext.HttpContext.Request.Path + resultContext.HttpContext.Request.QueryString;
string method = resultContext.HttpContext.Request.Method;
dynamic result = resultContext.Result.GetType().Name == "EmptyResult" ? new { Value = "EmptyResult" } : resultContext.Result as dynamic;
string response = JsonConvert.SerializeObject(result.Value);
logger.LogInformation($"URL:{url} \n " +
$"Method:{method} \n " +
$"ActionArguments:{actionArguments}\n " +
$"Response:{response}\n ");
}
}
- Startup ConfigureServices
services.AddMvc(options =>
{
options.Filters.Add(typeof(ApiLogFilter));
});
日志
- Error Log
- Api Log
相关资料
- demo