WebApi2 添加Log4Net

1,在项目中引用log4net.dll
在NuGet包管理器里面搜索log4net,并安装

2,添加Web.Config配置
WebApi2 添加Log4Net_第1张图片
WebApi2 添加Log4Net_第2张图片
相应代码如下:

 
    
    
    
      
      
    
    
    
      
    
    
      
      
      
      
      
      
        
      
    
    
      
        
      
    
  

3,添加相应类与方法
1,定义一个WebApiMonitorLog ,监控日志对象

/// 
    /// 监控日志对象
    /// 
    public class WebApiMonitorLog
    {
        public string ControllerName { get; set; }
        public string ActionName { get; set; }

        public DateTime ExecuteStartTime { get; set; }
        public DateTime ExecuteEndTime { get; set; }

        /// 
        /// 请求的Action 参数
        /// 
        public Dictionary ActionParams { get; set; }

        /// 
        /// Http请求头
        /// 
        public string HttpRequestHeaders { get; set; }

        /// 
        /// 请求方式
        /// 
        public string HttpMethod { get; set; }

        /// 
        /// 请求的IP地址
        /// 
        public string IP { get; set; }

        /// 
        /// 获取监控指标日志
        /// 
        /// 
        /// 
        public string GetLoginfo()
        {
            string Msg = @"
            Action执行时间监控:
            ControllerName:{0}Controller
            ActionName:{1}
            开始时间:{2}
            结束时间:{3}
            总 时 间:{4}秒
            Action参数:{5}
            Http请求头:{6}
            客户端IP:{7},
            HttpMethod:{8}
                    ";
            return string.Format(Msg,
                ControllerName,
                ActionName,
                ExecuteStartTime,
                ExecuteEndTime,
                (ExecuteEndTime - ExecuteStartTime).TotalSeconds,
                GetCollections(ActionParams),
                HttpRequestHeaders,
                IP,
                HttpMethod);
        }

        /// 
        /// 获取Action 参数
        /// 
        /// 
        /// 
        public string GetCollections(Dictionary 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;
        }

        /// 
        /// 获取IP
        /// 
        /// 
        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,定义一个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,定义一个WebApiTrackerAttribute类,继承于ActionFilterAttribute

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
    public class WebApiTrackerAttribute : ActionFilterAttribute
    {
        private readonly string Key = "_thisWebApiOnActionMonitorLog_";
        public override void OnActionExecuting(HttpActionContext actionContext) {
            base.OnActionExecuting(actionContext);
            WebApiMonitorLog MonLog = new 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
        }
        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext) {
            WebApiMonitorLog MonLog = actionExecutedContext.Request.Properties[Key] as WebApiMonitorLog;
            MonLog.ExecuteEndTime = DateTime.Now;
            MonLog.ActionName = actionExecutedContext.ActionContext.ActionDescriptor.ActionName;
            MonLog.ControllerName = actionExecutedContext.ActionContext.ActionDescriptor.ControllerDescriptor.ControllerName;
            LoggerHelper.Monitor(MonLog.GetLoginfo());
            if (actionExecutedContext.Exception != null) {
                string Msg = string.Format(@"
                请求【{0}Controller】的【{1}】产生异常:
                Action参数:{2}
               Http请求头:{3}
                客户端IP:{4},
                HttpMethod:{5}
                    ", MonLog.ControllerName, MonLog.ActionName, MonLog.GetCollections(MonLog.ActionParams), MonLog.HttpRequestHeaders, MonLog.GetIP(), MonLog.HttpMethod);
                LoggerHelper.Error(Msg, actionExecutedContext.Exception);
            }
        }
    }

4,在WebApiConfig.cs 中加上(也可以在global中加)

log4net.Config.XmlConfigurator.Configure();	

5,最后在需要监控的控制器上加上 WebApiTracker
在这里插入图片描述

4,查看记录结果
每次在调用这个监控下的Action 时,都会有日志记录,像这样滴

在项目下有个log 文件夹
WebApi2 添加Log4Net_第3张图片

或者自定义使用亦可
WebApi2 添加Log4Net_第4张图片

5,在桌面应用程序、控制台应用程序、Windows服务项目中log4net的配置

第一步:跟上面网站项目配置一样先把log4net程序包安装到项目中
第二步:也是一样只是由Web.config变成App.config文件代码还是一样
第三步:有点不一样了,我们要在项目中的AssemblyInfo.cs中加一行代码:
//[assembly: log4net.Config.XmlConfigurator(ConfigFileExtension = "config", Watch = true)]
//log4net从配置文件中读取配置 WebApi2 添加Log4Net_第5张图片
最后一步就是在项目中使用了,跟网站项目中的使用一样就可以了。

参考资料:
1,https://www.cnblogs.com/weixiaowei/p/8253228.html
2,https://www.cnblogs.com/huangenai/archive/2016/04/23/5424596.html
3,https://jingyan.baidu.com/album/636f38bb5e5eead6b84610e9.html?picindex=8 (里面的第三步)

你可能感兴趣的:(WebApi2 添加Log4Net)