1.首先选择你的项目 打开net管理控制台 输入 install-package log4net 进行安装 也可以 在net包 搜索 log4net
2.安装完之后 在Models文件夹 创建一个Log4net文件夹
3.在 Log4net文件夹下创建 一个 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); } }
4.再创建一个 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; } }
5.创建 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); } } }
6.在Global.asax 中 添加 log4net.Config.XmlConfigurator.Configure(); 这一行.
7.创建一个名称为log4net.config配置文件
<?xml version="1.0" encoding="utf-8"?> <log4net> <logger name="WebLogger"> <level value="DEBUG" /> </logger> <appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender"> <bufferSize value="0" /> <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /> <!--此为连接字符串,该处以SqlServer为例--> <connectionString value="server=.;uid=sa;pwd=sa;database=log4net" /> <!--此为数据库指令,也就是SQL的Insert语句--> <commandText value="INSERT INTO LogDetails ([LogDate],[LogThread],[LogLevel],[LogLogger],[LogMessage],[LogActionClick],[UserName],[UserIP]) VALUES (@log_date, @thread, @log_level, @logger, @message)" /> <!--定义参数,数据库表字段、类型、长度-->
<!-- 日期 --> <parameter> <parameterName value="@log_date" /> <dbType value="DateTime" /> <layout type="log4net.Layout.RawTimeStampLayout" /> </parameter>
<!-- 线程号 --> <parameter> <parameterName value="@thread" /> <dbType value="String" /> <size value="255" /> <layout type="log4net.Layout.PatternLayout,log4net"> <conversionPattern value="%thread" /> </layout> </parameter>
<!-- 等级 --> <parameter> <parameterName value="@log_level" /> <dbType value="String" /> <size value="50" /> <layout type="log4net.Layout.PatternLayout,log4net"> <conversionPattern value="%level" /> </layout> </parameter>
<!-- 日志 --> <parameter> <parameterName value="@logger" /> <dbType value="String" /> <size value="255" /> <layout type="log4net.Layout.PatternLayout,log4net"> <conversionPattern value="%logger" /> </layout> </parameter>
<!-- 内容 --> <parameter> <parameterName value="@message" /> <dbType value="String" /> <size value="4000" /> <layout type="log4net.Layout.PatternLayout,log4net"> <conversionPattern value="%message" /> </layout> </parameter> </appender> <root> <!-- Set this to "ERROR" before release --> <!--Highest: OFF->FATAL->RROR->WARN->INFO->DEBUG->ALL :Lowest --> <level value="ALL" /> <appender-ref ref="AdoNetAppender" /> <!-- <appender-ref ref="SmtpAppender" /> --> <!--<appender-ref ref="FileAppender" /> --> </root> </log4net>
数据库 自行创建
<commandText value="INSERT INTO LogDetails ([LogDate],[LogThread],[LogLevel],[LogLogger],[LogMessage],[LogActionClick],[UserName],[UserIP]) VALUES (@log_date, @thread, @log_level, @logger, @message)" />
根据数据库列名 填写
在Web.config里面
<configSections>节点里加上以下代码
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
在<configuration>父节点
引用刚才写的配置文件 <log4net configSource="log4net.config"/>
在控制器中加上 过滤器 报错自动记录
存入数据库中
最后 补一下 记得在
AssemblyInfo.cs 加上以下代码 非常重要
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", ConfigFileExtension = "config", Watch = true)]
挺详细的
第一次发文 还在学习中 谢谢
有看不懂的可以评论 或者 私我
记录学习!