配置文件
备注,需要放到根目录下面
<?xml version="1.0" encoding="utf-8"?> <configuration> <configSections> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/> </configSections> <log4net> <!--定义输出到文件中--> <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender"> <!--定义文件存放位置--> <file value="log\\"/> <appendToFile value="true"/> <rollingStyle value="Date"/> <datePattern value="yyyy\\yyyyMM\\yyyyMMdd‘.txt‘"/> <staticLogFileName value="false"/> <param name="MaxSizeRollBackups" value="100"/> <layout type="log4net.Layout.PatternLayout"> <!--每条日志末尾的文字说明--> <!--输出格式--> <!--样例:2008-03-26 13:42:32,111 [10] INFO Log4NetDemo.MainClass [(null)] - info--> <conversionPattern value="%newline %n记录时间:%date %n线程ID:[%thread] %n日志级别: %-5level %n出错类:%logger property: [%property{NDC}] - %n错误描述:%message%newline %n"/> </layout> </appender> <root> <level value="ERROR"/> <!--文件形式记录日志--> <appender-ref ref="RollingLogFileAppender"/> </root> </log4net> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/> </startup> </configuration>
日志类:
public class WriteLog { /// <summary> /// 输出日志到Log4Net /// </summary> /// <param name="t"></param> /// <param name="ex"></param> #region static void WriteErrorLog(Type t, Exception ex) public static void WriteErrorLog(Type t, Exception ex) { log4net.ILog log = log4net.LogManager.GetLogger(t); log.Error("Error", ex); } #endregion /// <summary> /// 输出日志到Log4Net /// </summary> /// <param name="t"></param> /// <param name="msg"></param> #region static void WriteErrorLog(Type t, string msg) public static void WriteErrorLog(Type t, string msg) { log4net.ILog log = log4net.LogManager.GetLogger(t); log.Error(msg); } #endregion }
测试调用:
static void Main(string[] args) { string a = "aa"; try { int i = int.Parse(a); } catch (Exception ex) { Console.WriteLine(ex.ToString()); WriteLog.WriteErrorLog(typeof(Program), ex); } }
备注:如果出现日志无法记录问题,则
//配置log4net
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
在程序的 assembly.cs 里加上 上面这句话
时间: 2024-10-18 08:03:09