WebApi服务监控 log4net记录监控日志
生活随笔
收集整理的這篇文章主要介紹了
WebApi服务监控 log4net记录监控日志
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
在項目中引用log4net.dll
1、在Models文件夾內,定義一個WebApiMonitorLog ,監控日志對象
/// <summary>/// 監控日志對象/// </summary>public class WebApiMonitorLog{public string ControllerName { get; set; }public string ActionName { get; set; }public DateTime ExecuteStartTime { get; set; }public DateTime ExecuteEndTime { get; set; }/// <summary>/// 請求的Action 參數/// </summary>public Dictionary<string, object> ActionParams { get; set; }/// <summary>/// Http請求頭/// </summary>public string HttpRequestHeaders { get; set; }/// <summary>/// 請求方式/// </summary>public string HttpMethod { get; set; }/// <summary>/// 請求的IP地址/// </summary>public string IP { get; set; }/// <summary>/// 獲取監控指標日志/// </summary>/// <param name="mtype"></param>/// <returns></returns>public string GetLoginfo(){//ControllerName:{0}Controller//ActionName:{1} //開始時間:{2}//結束時間:{3}//總 時 間:{4}秒//Action參數:{5}//Http請求頭:{6}//客戶端IP:{7} //HttpMethod:{8}string Msg = "Action執行監控:\r\nControllerName:{0}Controller\r\nActionName:{1}\r\n開始時間:{2}\r\n結束時間:{3}\r\n總 時 間:{4}秒\r\nAction參數:{5}\r\nHttp請求頭:{6}\r\n客戶端IP:{7}\r\nHttpMethod:{8}";return string.Format(Msg,ControllerName,ActionName,ExecuteStartTime,ExecuteEndTime,(ExecuteEndTime - ExecuteStartTime).TotalSeconds,GetCollections(ActionParams),HttpRequestHeaders,GetIP(),HttpMethod);}/// <summary>/// 獲取Action 參數/// </summary>/// <param name="Collections"></param>/// <returns></returns>public string GetCollections(Dictionary<string, object> Collections){string Parameters = string.Empty;if (Collections == null || Collections.Count == 0){return Parameters;}foreach (string key in Collections.Keys){Parameters += string.Format("{0}={1}&", key, Collections[key]);}if (!string.IsNullOrWhiteSpace(Parameters) && Parameters.EndsWith("&")){Parameters = Parameters.Substring(0, Parameters.Length - 1);}return Parameters;}/// <summary>/// 獲取IP/// </summary>/// <returns></returns>public string GetIP(){string ip = string.Empty;if (!string.IsNullOrEmpty(System.Web.HttpContext.Current.Request.ServerVariables["HTTP_VIA"]))ip = Convert.ToString(System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]);if (string.IsNullOrEmpty(ip))ip = Convert.ToString(System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]);return ip;}}2、在Helper文件夾內,定義一個LoggerHelper,日志幫助類
public class LoggerHelper{private static readonly log4net.ILog loginfo = log4net.LogManager.GetLogger("loginfo");private static readonly log4net.ILog logerror = log4net.LogManager.GetLogger("logerror");private static readonly log4net.ILog logmonitor = log4net.LogManager.GetLogger("logmonitor");public static void Error(string ErrorMsg, Exception ex = null){if (ex != null){logerror.Error(ErrorMsg, ex);}else{logerror.Error(ErrorMsg);}}public static void Info(string Msg){loginfo.Info(Msg);}public static void Monitor(string Msg){logmonitor.Info(Msg);}}3、在App_Start文件夾內,定義一個WebApiTrackerAttribute特性類,繼承于ActionFilterAttribute,并在App_Start的WebApiConfig.cs進行注冊
/// <summary>/// WebAPI監控/// </summary>public class WebApiTrackerAttribute : ActionFilterAttribute{private readonly string Key = "_thisWebApiOnActionMonitorLog_";/// <summary>/// 調用前驗證/// </summary>/// <param name="actionContext">操作上下文</param>public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext){base.OnActionExecuting(actionContext);ZrTestItemsWebApi.Models.WebApiMonitorLog MonLog = new ZrTestItemsWebApi.Models.WebApiMonitorLog();MonLog.ExecuteStartTime = DateTime.Now;//獲取Action 參數MonLog.ActionParams = actionContext.ActionArguments;MonLog.HttpRequestHeaders = actionContext.Request.Headers.ToString();MonLog.HttpMethod = actionContext.Request.Method.Method;actionContext.Request.Properties[Key] = MonLog;var form = System.Web.HttpContext.Current.Request.Form;#region 如果參數是實體對象,獲取序列化后的數據Stream stream = actionContext.Request.Content.ReadAsStreamAsync().Result;Encoding encoding = Encoding.UTF8;stream.Position = 0;string responseData = "";using (StreamReader reader = new StreamReader(stream, encoding)){responseData = reader.ReadToEnd().ToString();}if (!string.IsNullOrWhiteSpace(responseData) && !MonLog.ActionParams.ContainsKey("__EntityParamsList__")){MonLog.ActionParams["__EntityParamsList__"] = responseData;}#endregion}/// <summary>/// 驗證之后/// </summary>/// <param name="actionExecutedContext">操作上下文</param>public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext){ZrTestItemsWebApi.Models.WebApiMonitorLog MonLog = actionExecutedContext.Request.Properties[Key] as ZrTestItemsWebApi.Models.WebApiMonitorLog;MonLog.ExecuteEndTime = DateTime.Now;MonLog.ActionName = actionExecutedContext.ActionContext.ActionDescriptor.ActionName;MonLog.ControllerName = actionExecutedContext.ActionContext.ActionDescriptor.ControllerDescriptor.ControllerName;log4net.LogManager.GetLogger("logmonitor").Info(MonLog.GetLoginfo());if (actionExecutedContext.Exception != null){string Msg = string.Format("請求【{0}Controller】的【{1}】產生異常:\r\n異常信息:{2}\r\nAction參數:{3}\r\nHttp請求頭:{4}\r\n客戶端IP:{5}\r\nHttpMethod:{6}", MonLog.ControllerName, MonLog.ActionName, actionExecutedContext.Exception.ToString(), MonLog.GetCollections(MonLog.ActionParams), MonLog.HttpRequestHeaders, MonLog.GetIP(), MonLog.HttpMethod);log4net.LogManager.GetLogger("logerror").Error(Msg);}base.OnActionExecuted(actionExecutedContext);}}4、在Configs文件夾內,新建一個log4net.config
<?xml version="1.0" encoding="utf-8"?> <configuration><configSections><section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/></configSections><log4net><!--(高) OFF > FATAL > ERROR > WARN > INFO > DEBUG > ALL (低) --><!--錯誤日志--><appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender"><!--日志路徑--><!--<param name="File" value="D:\ElevatorSystem\SafeElevator\SafeElevator\App_Log\servicelog\" />--><param name="File" value="log\\LogError\\" /><!--是否是向文件中追加日志--><param name="AppendToFile" value="true" /><!--文件最大容量--><param name="MaxFileSize" value="10240" /><!--log保留天數--><param name="MaxSizeRollBackups" value="100" /><!--日志文件名是否是固定不變的--><param name="StaticLogFileName" value="false" /><!--日志文件名格式為:2008-08-31.log--><param name="DatePattern" value="yyyy\\yyyyMM\\yyyy-MM-dd".txt"" /><!--日志根據日期滾動--><param name="RollingStyle" value="Date" /><layout type="log4net.Layout.PatternLayout"><!--<param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n %loggername" />--><!--<conversionPattern value="%d [%t] %-5p %c - %m%n %loggername" />--><conversionPattern value="%newline %n記錄時間:%date %n線程ID:[%thread] %n日志級別: %-5level %n日志描述:%message%newline %n"/></layout></appender><!--Info日志--><appender name="InfoAppender" type="log4net.Appender.RollingFileAppender"><!--日志路徑--><param name="File" value="Log\\LogInfo\\" /><!--是否是向文件中追加日志--><param name="AppendToFile" value="true" /><!--文件最大容量--><param name="MaxFileSize" value="10240" /><!--log保留天數--><param name="MaxSizeRollBackups" value="100" /><!--日志文件名是否是固定不變的--><param name="StaticLogFileName" value="false" /> <param name="DatePattern" value="yyyy\\yyyyMM\\yyyy-MM-dd".txt"" /><!--日志根據日期滾動--><param name="RollingStyle" value="Date" /><layout type="log4net.Layout.PatternLayout"><conversionPattern value="%newline %n記錄時間:%date %n線程ID:[%thread] %n日志級別: %-5level %n日志描述:%message%newline %n"/></layout></appender><!--監控日志--><appender name="MonitorAppender" type="log4net.Appender.RollingFileAppender"><!--日志路徑--><param name="File" value="Log\\LogMonitor\\" /><!--是否是向文件中追加日志--><param name="AppendToFile" value="true" /><!--文件最大容量--><param name="MaxFileSize" value="10240" /><!--log保留天數--><param name="MaxSizeRollBackups" value="100" /><!--日志文件名是否是固定不變的--><param name="StaticLogFileName" value="false" /><param name="DatePattern" value="yyyy\\yyyyMM\\yyyy-MM-dd".txt"" /><!--日志根據日期滾動--><param name="RollingStyle" value="Date" /><layout type="log4net.Layout.PatternLayout"><conversionPattern value="%newline %n記錄時間:%date %n線程ID:[%thread] %n日志級別: %-5level %n跟蹤描述:%message%newline %n"/></layout></appender><!--Error日志--><logger name="logerror"><level value="ERROR" /><appender-ref ref="RollingLogFileAppender" /></logger><!--Info日志--><logger name="loginfo"><level value="INFO" /><appender-ref ref="InfoAppender" /></logger><!--監控日志--><logger name="logmonitor"><level value="Monitor" /><appender-ref ref="MonitorAppender" /></logger><!--(高) OFF > FATAL > ERROR > WARN > INFO > DEBUG > ALL (低) --><!--root是一個父級的logger,所有Logger列表的形式寫在里面,相當于多個looger分開定義--><!-- <root><level value="ALL" /> <appender-ref ref="RollingLogFileAppender" /></root>--></log4net></configuration>5、啟用log4net配置,在Global.asax中注冊log4net
void Application_Start(object sender, EventArgs e){// 在應用程序啟動時運行的代碼 ZrTestItemsWebApi.App_Start.WebApiConfig.Register(System.Web.Http.GlobalConfiguration.Configuration);log4net.Config.XmlConfigurator.Configure(new System.IO.FileInfo(AppDomain.CurrentDomain.BaseDirectory + "\\Configs\\log4net.config"));//啟用log4net配置}?參考網址:https://www.cnblogs.com/huangenai/archive/2016/04/23/5424596.html
轉載于:https://www.cnblogs.com/douf/p/11056546.html
總結
以上是生活随笔為你收集整理的WebApi服务监控 log4net记录监控日志的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: MySQL 备份和恢复策略(二)
- 下一篇: jenkins部署java项目(五)