C# Log4Net 记录项目日志

 1 //1。 安装log4net 包
 2 
 3 //2。 新建 LoggerHelper 类
 4 
 5 [assembly: log4net.Config.XmlConfigurator()]
 6 namespace WebAPI.Common
 7 {
 8     public class LoggerHelper
 9     {
10         /// <summary>
11         /// 输出日志到Log4Net
12         /// </summary>
13         /// <param name="t"></param>
14         /// <param name="ex"></param>
15         #region static void WriteLog(Type t, Exception ex)
16 
17         public static void WriteLog(Type t, Exception ex)
18         {
19             log4net.ILog log = log4net.LogManager.GetLogger(t);
20             log.Error("Error", ex);
21         }
22 
23         #endregion
24 
25         /// <summary>
26         /// 输出日志到Log4Net
27         /// </summary>
28         /// <param name="t"></param>
29         /// <param name="msg"></param>
30         #region static void WriteLog(Type t, string msg)
31 
32         public static void WriteLog(Type t, string msg)
33         {
34             log4net.ILog log = log4net.LogManager.GetLogger(t);
35             log.Error(msg);
36         }
37 
38         #endregion
39     }
40 }
41 
42 //3。 在web.cofig 中加入如下配置
43 <configuration>
44   <configSections> 
45     <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
46   </configSections>
47  <log4net>
48     <appender name="rollingFile" type="log4net.Appender.RollingFileAppender,log4net">
49       <param name="File" value="log/" />
50       <param name="AppendToFile" value="true" />
51       <param name="RollingStyle" value="Date" />
52       <param name="DatePattern" value="yyyy\\yyyyMM\\yyyyMMdd'.txt'" />
53       <param name="staticLogFileName" value="false" />
54       <param name="MaxSizeRollBackups" value="100" />
55       <layout type="log4net.Layout.PatternLayout">
56         <param name="ConversionPattern" value="%newline %nDate:%date %ThreadID:[%thread] %nLevel:  %-5level %nErrorClass:%logger property: [%property{NDC}] - %nError Description:%message%newline %n" />
57       </layout>
58     </appender>
59     <root>
60       <level value="ALL" />
61       <appender-ref ref="rollingFile" />
62     </root>
63   </log4net>
64 
65 </configuration>
66 
67 //4。在调用其它类(StudentController)中调用logger
68 
69 LoggerHelper.WriteLog(typeof(StudentController), "ErrorMessage");
70 
71 
72 //5. 执行log代码时,会在项目文件中新建Log文件夹,记录txt文件log

 

posted @ 2019-06-28 15:39  王小二不在家  阅读(236)  评论(0编辑  收藏  举报