.Net Core NLog 配置
通过日志,记录每个接口请求的耗时情况
结合 <logger name="*" level="Trace" writeTo="tracefile"/> 配置使用,NLog 热生效不需要重启服务
WebApi
Global.asax.cs
protected void Application_Start() { //增加Filter FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); FilterConfig.RegisterApiFilters(GlobalConfiguration.Configuration.Filters); }
Filter
public class FilterConfig { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErrorAttribute()); } public static void RegisterApiFilters(HttpFilterCollection filters) { filters.Add(new ApiAciontFilter()); } } public class ApiAciontFilter : System.Web.Http.Filters.ActionFilterAttribute { private const string Key = "__action_duration__"; public override void OnActionExecuting(HttpActionContext actionContext) { var stopWatch = new Stopwatch(); actionContext.Request.Properties[Key] = stopWatch; stopWatch.Start(); } public override void OnActionExecuted(HttpActionExecutedContext filterContext) { try { if (!filterContext.Request.Properties.ContainsKey(Key)) { return; } var stopWatch = filterContext.Request.Properties[Key] as Stopwatch; if (stopWatch != null) { stopWatch.Stop(); var clientIp = GetIPAddress(filterContext.Request); string msg = string.Format("{0}, {1}, {2}, {3} MS", clientIp, filterContext.Response.StatusCode, filterContext.Request.RequestUri.AbsolutePath, stopWatch.ElapsedMilliseconds); NLog.LogManager.GetCurrentClassLogger().Trace(msg); //正常日志输出 } } catch (Exception e) { NLog.LogManager.GetCurrentClassLogger().Error(e, e.Message); } } public static string GetIPAddress(HttpRequestMessage request) { string ip = ""; try { if (request.Properties.ContainsKey("MS_HttpContext")) { ip = ((HttpContextWrapper)request.Properties["MS_HttpContext"]).Request.UserHostAddress; } } catch (Exception ex) { } if (ip == "::1") ip = "127.0.0.1"; return ip; } }