log4net简单用法
一、NuGet在Server,mvc中添加Common.Logging和common.Logging.Log4Net如下图
二、在Server层创建logger类
<?xml version="1.0" encoding="utf-8" ?> <log4net> <!--级别层级ALL<DEBUG<INFO<WARN<ERROR<FATAL<OFF --> <!--调试日志--> <appender name="debugLog" type="log4net.Appender.RollingFileAppender,log4net" > <param name="File" value="logs\debug\debug.log" /> <param name="AppendToFile" value="true" /> <param name="RollingStyle" value="Date" /> <param name="DatePattern" value="yyyyMMdd" /> <param name="StaticLogFileName" value="true" /> <layout type="log4net.Layout.PatternLayout,log4net"> <param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss}%newline%message%n" /> </layout> <filter type="log4net.Filter.LevelRangeFilter"> <param name="LevelMin" value="DEBUG" /> <param name="LevelMax" value="DEBUG" /> </filter> </appender> <!--信息日志--> <appender name="infoLog" type="log4net.Appender.RollingFileAppender,log4net" > <param name="File" value="logs\info\info.log" /> <param name="AppendToFile" value="true" /> <param name="RollingStyle" value="Date" /> <param name="DatePattern" value="yyyyMMdd" /> <param name="StaticLogFileName" value="true" /> <layout type="log4net.Layout.PatternLayout,log4net"> <param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n" /> </layout> <filter type="log4net.Filter.LevelRangeFilter"> <param name="LevelMin" value="INFO" /> <param name="LevelMax" value="INFO" /> </filter> </appender> <!--错误日志--> <appender name="errorLog" type="log4net.Appender.RollingFileAppender,log4net" > <param name="File" value="logs\error\error.log" /> <param name="AppendToFile" value="true" /> <param name="RollingStyle" value="Date" /> <param name="DatePattern" value="yyyyMMdd" /> <param name="StaticLogFileName" value="true" /> <layout type="log4net.Layout.PatternLayout,log4net"> <param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss}%newline%message%n" /> </layout> <filter type="log4net.Filter.LevelRangeFilter"> <param name="LevelMin" value="ERROR" /> <param name="LevelMax" value="ERROR" /> </filter> </appender> <!--警告日志--> <appender name="warnLog" type="log4net.Appender.RollingFileAppender,log4net" > <param name="File" value="logs\warn\warn.log" /> <param name="AppendToFile" value="true" /> <param name="RollingStyle" value="Date" /> <param name="DatePattern" value="yyyyMMdd" /> <param name="StaticLogFileName" value="true" /> <layout type="log4net.Layout.PatternLayout,log4net"> <param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss}%newline%message%n" /> </layout> <filter type="log4net.Filter.LevelRangeFilter"> <param name="LevelMin" value="WARN" /> <param name="LevelMax" value="WARN" /> </filter> </appender> <!--致命错误日志--> <appender name="fatalLog" type="log4net.Appender.RollingFileAppender,log4net" > <param name="File" value="logs\fatal\fatal.log" /> <param name="AppendToFile" value="true" /> <param name="RollingStyle" value="Date" /> <param name="DatePattern" value="yyyyMMdd" /> <param name="StaticLogFileName" value="true" /> <layout type="log4net.Layout.PatternLayout,log4net"> <param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss}%newline%message%n" /> </layout> <filter type="log4net.Filter.LevelRangeFilter"> <param name="LevelMin" value="FATAL" /> <param name="LevelMax" value="FATAL" /> </filter> </appender> <appender name="LogToDB" type="log4net.Appender.AdoNetAppender"> <bufferSize value="1" /> <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /> <connectionString value="Data Source=oa.ctitech.cn;Initial Catalog=logtest;Persist Security Info=True;User ID=sa;Password=zkx123" /> <commandText value="INSERT INTO Log ([Date],[Thread],[Level],[Logger],[Message],[Exception]) VALUES (@log_date, @thread, @log_level, @logger, @message, @exception)" /> <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"> <conversionPattern value="%thread" /> </layout> </parameter> <parameter> <parameterName value="@log_level" /> <dbType value="String" /> <size value="50" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%level" /> </layout> </parameter> <parameter> <parameterName value="@logger" /> <dbType value="String" /> <size value="255" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%logger" /> </layout> </parameter> <parameter> <parameterName value="@message" /> <dbType value="String" /> <size value="4000" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%message" /> </layout> </parameter> <parameter> <parameterName value="@exception" /> <dbType value="String" /> <size value="2000" /> <layout type="log4net.Layout.ExceptionLayout" /> </parameter> <!--<filter type="log4net.Filter.LevelRangeFilter"> <param name="LevelMin" value="DEBUG" /> <param name="LevelMax" value="FATAL" /> </filter>--> </appender> <root> <level value="ALL" /> <appender-ref ref="debugLog" /> <appender-ref ref="infoLog"/> <appender-ref ref="warnLog" /> <appender-ref ref="errorLog" /> <appender-ref ref="fatalLog" /> <!--<appender-ref ref="LogToDB" />--> </root> <!-- CREATE TABLE [dbo].[Log] ( [Id] [int] IDENTITY (1, 1) NOT NULL, [Date] [datetime] NOT NULL, [Thread] [varchar] (255) NOT NULL, [Level] [varchar] (50) NOT NULL, [Logger] [varchar] (255) NOT NULL, [Message] [varchar] (4000) NOT NULL, [Exception] [varchar] (2000) NULL ) --> </log4net>
三、在mvc项目中添加log4net.config
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using System.Text; namespace LogServer { public class Logger { #region Wrap common.logging static readonly Common.Logging.ILog log = Common.Logging.LogManager.GetCurrentClassLogger(); public static void Debug(IFormatProvider formatProvider, Action<Common.Logging.FormatMessageHandler> formatMessageCallback, Exception exception) { log.Debug(formatProvider, formatMessageCallback, exception); } public static void Debug(IFormatProvider formatProvider, Action<Common.Logging.FormatMessageHandler> formatMessageCallback) { log.Debug(formatProvider, formatMessageCallback); } public static void Debug(Action<Common.Logging.FormatMessageHandler> formatMessageCallback, Exception exception) { log.Debug(formatMessageCallback, exception); } public static void Debug(Action<Common.Logging.FormatMessageHandler> formatMessageCallback) { log.Debug(formatMessageCallback); } public static void Debug(object message, Exception exception) { log.Debug(message, exception); } public static void Debug(object message) { log.Debug(message); } public static void DebugFormat(IFormatProvider formatProvider, string format, Exception exception, params object[] args) { log.DebugFormat(formatProvider, format, exception, args); } public static void DebugFormat(IFormatProvider formatProvider, string format, params object[] args) { log.DebugFormat(formatProvider, format, args); } public static void DebugFormat(string format, Exception exception, params object[] args) { log.DebugFormat(format, exception, args); } public static void DebugFormat(string format, params object[] args) { log.DebugFormat(format, args); } public static void Error(IFormatProvider formatProvider, Action<Common.Logging.FormatMessageHandler> formatMessageCallback, Exception exception) { log.Error(formatProvider, formatMessageCallback, exception); } public static void Error(IFormatProvider formatProvider, Action<Common.Logging.FormatMessageHandler> formatMessageCallback) { log.Error(formatProvider, formatMessageCallback); } public static void Error(Action<Common.Logging.FormatMessageHandler> formatMessageCallback, Exception exception) { log.Error(formatMessageCallback, exception); } public static void Error(Action<Common.Logging.FormatMessageHandler> formatMessageCallback) { log.Error(formatMessageCallback); } public static void Error(object message, Exception exception) { log.Error(message, exception); } public static void Error(object message) { log.Error(message); } public static void ErrorFormat(IFormatProvider formatProvider, string format, Exception exception, params object[] args) { log.ErrorFormat(formatProvider, format, exception, args); } public static void ErrorFormat(IFormatProvider formatProvider, string format, params object[] args) { log.ErrorFormat(formatProvider, format, args); } public static void ErrorFormat(string format, Exception exception, params object[] args) { log.ErrorFormat(format, exception, args); } public static void ErrorFormat(string format, params object[] args) { log.ErrorFormat(format, args); } public static void Fatal(IFormatProvider formatProvider, Action<Common.Logging.FormatMessageHandler> formatMessageCallback, Exception exception) { log.Fatal(formatProvider, formatMessageCallback, exception); } public static void Fatal(IFormatProvider formatProvider, Action<Common.Logging.FormatMessageHandler> formatMessageCallback) { log.Fatal(formatProvider, formatMessageCallback); } public static void Fatal(Action<Common.Logging.FormatMessageHandler> formatMessageCallback, Exception exception) { log.Fatal(formatMessageCallback, exception); } public static void Fatal(Action<Common.Logging.FormatMessageHandler> formatMessageCallback) { log.Fatal(formatMessageCallback); } public static void Fatal(object message, Exception exception) { log.Fatal(message, exception); } public static void Fatal(object message) { log.Fatal(message); } public static void FatalFormat(IFormatProvider formatProvider, string format, Exception exception, params object[] args) { log.FatalFormat(formatProvider, format, exception, args); } public static void FatalFormat(IFormatProvider formatProvider, string format, params object[] args) { log.FatalFormat(formatProvider, format, args); } public static void FatalFormat(string format, Exception exception, params object[] args) { log.FatalFormat(format, exception, args); } public static void FatalFormat(string format, params object[] args) { log.FatalFormat(format, args); } public static void Info(IFormatProvider formatProvider, Action<Common.Logging.FormatMessageHandler> formatMessageCallback, Exception exception) { log.Info(formatProvider, formatMessageCallback, exception); } public static void Info(IFormatProvider formatProvider, Action<Common.Logging.FormatMessageHandler> formatMessageCallback) { log.Info(formatProvider, formatMessageCallback); } public static void Info(Action<Common.Logging.FormatMessageHandler> formatMessageCallback, Exception exception) { log.Info(formatMessageCallback, exception); } public static void Info(Action<Common.Logging.FormatMessageHandler> formatMessageCallback) { log.Info(formatMessageCallback); } public static void Info(object message, Exception exception) { log.Info(message, exception); } public static void Info(object message) { log.Info(message); } public static void InfoFormat(IFormatProvider formatProvider, string format, Exception exception, params object[] args) { log.InfoFormat(formatProvider, format, exception, args); } public static void InfoFormat(IFormatProvider formatProvider, string format, params object[] args) { log.InfoFormat(formatProvider, format, args); } public static void InfoFormat(string format, Exception exception, params object[] args) { log.InfoFormat(format, exception, args); } public static void InfoFormat(string format, params object[] args) { log.InfoFormat(format, args); } public bool IsDebugEnabled { get { return IsDebugEnabled; } } public bool IsErrorEnabled { get { return IsErrorEnabled; } } public bool IsFatalEnabled { get { return IsFatalEnabled; } } public bool IsInfoEnabled { get { return IsInfoEnabled; } } public bool IsTraceEnabled { get { return IsTraceEnabled; } } public bool IsWarnEnabled { get { return IsWarnEnabled; } } public static void Trace(IFormatProvider formatProvider, Action<Common.Logging.FormatMessageHandler> formatMessageCallback, Exception exception) { log.Trace(formatProvider, formatMessageCallback, exception); } public static void Trace(IFormatProvider formatProvider, Action<Common.Logging.FormatMessageHandler> formatMessageCallback) { log.Trace(formatProvider, formatMessageCallback); } public static void Trace(Action<Common.Logging.FormatMessageHandler> formatMessageCallback, Exception exception) { log.Trace(formatMessageCallback, exception); } public static void Trace(Action<Common.Logging.FormatMessageHandler> formatMessageCallback) { log.Info(formatMessageCallback); } public static void Trace(object message, Exception exception) { log.Info(message, exception); } public static void Trace(object message) { log.Info(message); } public static void TraceFormat(IFormatProvider formatProvider, string format, Exception exception, params object[] args) { log.InfoFormat(formatProvider, format, exception, args); } public static void TraceFormat(IFormatProvider formatProvider, string format, params object[] args) { log.InfoFormat(formatProvider, format, args); } public static void TraceFormat(string format, Exception exception, params object[] args) { log.InfoFormat(format, exception, args); } public static void TraceFormat(string format, params object[] args) { log.InfoFormat(format, args); } public static void Warn(IFormatProvider formatProvider, Action<Common.Logging.FormatMessageHandler> formatMessageCallback, Exception exception) { log.Warn(formatProvider, formatMessageCallback, exception); } public static void Warn(IFormatProvider formatProvider, Action<Common.Logging.FormatMessageHandler> formatMessageCallback) { log.Warn(formatProvider, formatMessageCallback); } public static void Warn(Action<Common.Logging.FormatMessageHandler> formatMessageCallback, Exception exception) { log.Warn(formatMessageCallback, exception); } public static void Warn(Action<Common.Logging.FormatMessageHandler> formatMessageCallback) { log.Warn(formatMessageCallback); } public static void Warn(object message, Exception exception) { log.Warn(message, exception); } public static void Warn(object message) { log.Warn(message); } public static void WarnFormat(IFormatProvider formatProvider, string format, Exception exception, params object[] args) { log.WarnFormat(formatProvider, format, exception, args); } public static void WarnFormat(IFormatProvider formatProvider, string format, params object[] args) { log.WarnFormat(formatProvider, format, args); } public static void WarnFormat(string format, Exception exception, params object[] args) { log.WarnFormat(format, exception, args); } public static void WarnFormat(string format, params object[] args) { log.WarnFormat(format, args); } #endregion #region logger with Diagnostics public static void TraceReflect(params string[] args) { try { StackFrame frame = new StackFrame(1); MethodBase method = frame.GetMethod(); StackFrame frame2 = new StackFrame(2); MethodBase method2 = frame2.GetMethod(); List<string> list = new List<string>(); if (method.DeclaringType != null) { string format = GetReflectLogFormat(args, method.DeclaringType.ToString(), method2.Name + "/" + method.Name, ref list); Logger.TraceFormat(format, list.ToArray()); } } catch { } } /// <summary> /// 记录出错日志 /// </summary> /// <param name="args">第一个参数默认为错误描述</param> public static void ErrorReflect(params string[] args) { try { StackFrame frame = new StackFrame(1); MethodBase method = frame.GetMethod(); List<string> list = new List<string>(); if (method.DeclaringType != null) { string format = GetReflectErrorFormat(args, method.DeclaringType.ToString(), method.Name, ref list); Logger.ErrorFormat(format, list.ToArray()); } } catch { } } public static void DebugReflect(params string[] args) { try { StackFrame frame = new StackFrame(1); MethodBase method = frame.GetMethod(); StackFrame frame2 = new StackFrame(2); MethodBase method2 = frame2.GetMethod(); List<string> list = new List<string>(); if (method.DeclaringType != null) { string format = GetReflectLogFormat(args, method.DeclaringType.ToString(), method2.Name + "/" + method.Name, ref list); Logger.DebugFormat(format, list.ToArray()); } } catch { } } public static void FatalReflect(params string[] args) { try { StackFrame frame = new StackFrame(1); MethodBase method = frame.GetMethod(); List<string> list = new List<string>(); if (method.DeclaringType != null) { string format = GetReflectLogFormat(args, method.DeclaringType.ToString(), method.Name, ref list); Logger.FatalFormat(format, list.ToArray()); } } catch { } } public static void InfoReflect(params string[] args) { try { StackFrame frame = new StackFrame(1); MethodBase method = frame.GetMethod(); StackFrame frame2 = new StackFrame(2); MethodBase method2 = frame2.GetMethod(); List<string> list = new List<string>(); if (method.DeclaringType != null) { string format = GetReflectLogFormat(args, method.DeclaringType.ToString(), method2.Name + "/" + method.Name, ref list); Logger.InfoFormat(format, list.ToArray()); } } catch { } } /// <summary> /// 获取错误日志的模板 /// </summary> /// <param name="parms"></param> /// <param name="classname"></param> /// <param name="methodname"></param> /// <param name="argelist"></param> /// <returns></returns> /// <summary> private static string GetReflectErrorFormat(string[] parms, string classname, string methodname, ref List<string> argelist) { argelist.Add(classname); argelist.Add(methodname); StringBuilder sb = new StringBuilder("方法:{0}.{1}\r\n"); int l = parms.Length; if (l > 0) { sb.Append("错误:{2}\r\n"); argelist.Add(parms[0]); if (l > 1) { sb.Append("参数:"); for (int i = 1; i < l; i++) { sb.Append("[{" + (i + 2) + "}],"); argelist.Add(parms[i]); } } } return sb.ToString().TrimEnd(','); } /// <summary> /// 获取调试信息的模板 /// </summary> /// <param name="parms"></param> /// <param name="classname"></param> /// <param name="methodname"></param> /// <param name="argelist"></param> /// <returns></returns> private static string GetReflectLogFormat(string[] parms, string classname, string methodname, ref List<string> argelist) { argelist.Add(classname); argelist.Add(methodname); StringBuilder sb = new StringBuilder("方法:{0}.{1}\r\n"); int l = parms.Length; if (l > 0) { sb.AppendFormat("参数:"); for (int i = 0; i < l; i++) { sb.Append("[{" + (i + 2) + "}],"); argelist.Add(parms[i]); } } return sb.ToString().TrimEnd(','); } #endregion } public class Log4NetPathPattern : log4net.Util.PatternConverter { protected override void Convert(System.IO.TextWriter writer, object state) { try { var dirstr = System.Configuration.ConfigurationManager.AppSettings["log4net:root"]; if (string.IsNullOrWhiteSpace(dirstr)) dirstr = "logs"; dirstr = dirstr.TrimStart('/', '\\', '~'); if (!Path.IsPathRooted(dirstr)) dirstr = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, dirstr); writer.Write(dirstr); //如果在本项目中用,可以把文件夹加上程序集名:Assembly.GetExecutingAssembly() //否则只有在配置文件中加项目名了 } catch { //出错则默认当前目录logs文件夹 writer.Write(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "logs")); } } } }
四、在web.config的<configSections>内部添加
<sectionGroup name="common"> <section name="logging" type="Common.Logging.ConfigurationSectionHandler, Common.Logging" /> </sectionGroup>
五、在web.config的</configSections>的后面添加
<common> <logging> <factoryAdapter type="Common.Logging.Log4Net.Log4NetLoggerFactoryAdapter, Common.Logging.Log4net"> <arg key="configType" value="FILE-WATCH" /> <!-- FILE,FILE-WATCH,INLINE,EXTERNAL--> <arg key="configFile" value="~/log4net.config" /> <arg key="level" value="ALL" /> </factoryAdapter> </logging> </common>
六、创建测试类Class1进行调用所有类结构如下图