博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
WebApi服务监控 log4net记录监控日志
阅读量:5991 次
发布时间:2019-06-20

本文共 8298 字,大约阅读时间需要 27 分钟。

在项目中引用log4net.dll

1、在Models文件夹内,定义一个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() { //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); } ///
/// 获取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、在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进行注册

///     /// WebAPI监控    ///     public class WebApiTrackerAttribute : ActionFilterAttribute    {        private readonly string Key = "_thisWebApiOnActionMonitorLog_";        ///         /// 调用前验证        ///         /// 操作上下文        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        }        ///         /// 验证之后        ///         /// 操作上下文        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

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/douf/p/11056546.html

你可能感兴趣的文章
flash_builder_设置默认启动的浏览器
查看>>
jquery-ui 小图标 IE6/7下 显示空白问题
查看>>
终极选择---老男孩教育
查看>>
开机挂载之/etc/fstab
查看>>
extjs的MVC图
查看>>
Microsoft Azure系列之七 Azure IaaS虚拟机大小
查看>>
Go 语言 bytes.FieldsFunc 函数的使用
查看>>
DHCP安装配置
查看>>
lync2013前端服务器和边缘服务器复制错误
查看>>
xdebug php 调试器的安装和使用
查看>>
网络设备之shh配置
查看>>
辞职吐槽及方向调整
查看>>
Docker 内存占用测试
查看>>
【JavaScript】关于包装类与类型转换
查看>>
fw: Oracle的dmp文件,不知道fromuser,怎么才能把dmp文件导入到我的数据库中呢?
查看>>
文件中有一组整数,要求排序后输出到另一个文件中
查看>>
git工具文章
查看>>
Ibatis xml 通配符
查看>>
我的友情链接
查看>>
Oracle PL/SQL之处理index不连续的table类型变量
查看>>