WebApi2 添加Log4Net

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

2,添加Web.Config配置
在这里插入图片描述
在这里插入图片描述
相应代码如下:

<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
 <log4net>
    <!-- OFF, FATAL, ERROR, WARN, INFO, DEBUG, ALL -->
    <!-- Set root logger level to ERROR and its appenders -->
    <root>
      <level value="ALL" />
      <appender-ref ref="SysAppender" />
    </root>
    <!-- Print only messages of level DEBUG or above in the packages -->
    <logger name="WebLogger">
      <level value="DEBUG" />
    </logger>
    <appender name="SysAppender" type="log4net.Appender.RollingFileAppender,log4net">
      <param name="File" value="App_Data/" />
      <param name="AppendToFile" value="true" />
      <param name="RollingStyle" value="Date" />
      <param name="DatePattern" value="&quot;Logs_&quot;yyyyMMdd&quot;.txt&quot;" />
      <param name="StaticLogFileName" value="false" />
      <layout type="log4net.Layout.PatternLayout,log4net">
        <param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n" />
      </layout>
    </appender>
    <appender name="consoleApp" type="log4net.Appender.ConsoleAppender,log4net">
      <layout type="log4net.Layout.PatternLayout,log4net">
        <param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n" />
      </layout>
    </appender>
  </log4net>

3,添加相应类与方法
1,定义一个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()
        {
            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);
        }

        /// <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,定义一个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 文件夹
在这里插入图片描述

或者自定义使用亦可
在这里插入图片描述

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

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

参考资料:
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 (里面的第三步)

猜你喜欢

转载自blog.csdn.net/qq_43583854/article/details/83651253