netcore 中间件记录日志
public class Logger { private static ILog logger; static Logger() { if (logger == null) { var repository = LogManager.CreateRepository("NETCoreRepository"); //log4net从log4net.config文件中读取配置信息 XmlConfigurator.Configure(repository, new FileInfo("log4net.config")); logger = LogManager.GetLogger(repository.Name, "Logger"); } } private RequestDelegate _nextDelegate; public Logger(RequestDelegate nextDelegate) { _nextDelegate = nextDelegate; } public async Task Invoke(HttpContext httpContext) { logger.Info("start:" + DateTime.Now.ToString()); await _nextDelegate.Invoke(httpContext); logger.Info("end:" + DateTime.Now.ToString()); } public static void Info(string message, Exception exception = null) { if (exception == null) logger.Info(message); else logger.Info(message, exception); } public static void Warn(string message, Exception exception = null) { if (exception == null) logger.Warn(message); else logger.Warn(message, exception); } public static void Error(string message, Exception exception = null) { if (exception == null) logger.Error(message); else logger.Error(message, exception); } }
然后,在startup.cs中增加
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseMiddleware<Logger>(); app.UseMvc(); }
所有中间件需要放在UseMvc前面
测试