log4net是一个功能著名的开源日志记录组件。利用log4net可以方便地将日志信息记录到文件、控制台、Windows事件日志和数据库(包括MS SQL Server, Access, Oracle9i,Oracle8i,DB2,SQLite)中。并且我们还可以记载控制要记载的日志级别,可以记载的日志类别包括:FATAL(致命错误)、ERROR(一般错误)、WARN(警告)、INFO(一般信息)、DEBUG(调试信息)。要想获取最新版本的log4net组件库,可以到官方网站http://logging.apache.org/log4net/下载。现在的最新版本是1.2.10。
下面的例子展示了如何利用log4net记录日志 。
首先从官方网站下载最近版本的log4net组件,现在的最新版本是1.2.10。在程序中我们只需要log4net.dll文件就行了,添加对log4net.dll的引用,就可以在程序中使用了。
接着我们配置相关的配置文件(WinForm对应的是*.exe.config,WebForm对应的是*.config),本实例中是控制台应用程序,配置如下(附各配置的说明):
代码
1 <?xml version="1.0" encoding="utf-8" ?>
2 <configuration>
3 <configSections>
4 <section name="log4net" type="System.Configuration.IgnoreSectionHandler"/>
5 </configSections>
6 <appSettings>
7 </appSettings>
8 <log4net>
9 <!--RollingFileAppender自动截断-->
10 <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
11 <file value="log\\log.txt"/>
12 <appendToFile value="true"/>
13 <maxSizeRollBackups value="10"/>
14 <maximumFileSize value="2048KB"/>
15 <rollingStyle value="Size"/>
16 <staticLogFileName value="true"/>
17 <lockingModel type="log4net.Appender.FileAppender+MinimalLock"/>
18 <layout type="log4net.Layout.PatternLayout">
19 <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline"/>
20 </layout>
21 </appender>
22 <!--定义输出到文件中-->
23 <appender name="LogFileAppender" type="log4net.Appender.FileAppender">
24 <!--定义文件存放位置-->
25 <file value="logs.txt" />
26 <appendToFile value="true" />
27 <rollingStyle value="Date" />
28 <datePattern value="yyyyMMdd-HH:mm:ss" />
29 <layout type="log4net.Layout.PatternLayout">
30 <!--每条日志末尾的文字说明-->
31 <footer value="by author" />
32 <!--输出格式-->
33 <!--样例:2010-01-06 13:42:32,111 [10] INFO Log4NetDemo.MainClass [(null)] - info-->
34 <conversionPattern value="记录时间:%date 线程ID:[%thread] 日志级别:%-5level 出错类:%logger property:[%property{NDC}] - 错误描述:%message%newline" />
35 </layout>
36 </appender>
37 <!--定义输出到控制台命令行中-->
38 <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
39 <layout type="log4net.Layout.PatternLayout">
40 <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
41 </layout>
42 </appender>
43 <!--定义输出到windows事件中-->
44 <appender name="EventLogAppender" type="log4net.Appender.EventLogAppender">
45 <layout type="log4net.Layout.PatternLayout">
46 <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
47 </layout>
48 </appender>
49 <!--定义输出到数据库中,这里举例输出到Access数据库中,数据库为C盘的log4net.mdb-->
50 <appender name="AdoNetAppender_Access" type="log4net.Appender.AdoNetAppender">
51 <connectionString value="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=log4net.mdb" />
52 <commandText value="INSERT INTO LogDetails ([LogDate],[Thread],[Level],[Logger],[Message]) VALUES (@logDate, @thread, @logLevel, @logger,@message)" />
53 <!--定义各个参数-->
54 <parameter>
55 <parameterName value="@logDate" />
56 <dbType value="String" />
57 <size value="240" />
58 <layout type="log4net.Layout.PatternLayout">
59 <conversionPattern value="%date" />
60 </layout>
61 </parameter>
62 <parameter>
63 <parameterName value="@thread" />
64 <dbType value="String" />
65 <size value="240" />
66 <layout type="log4net.Layout.PatternLayout">
67 <conversionPattern value="%thread" />
68 </layout>
69 </parameter>
70 <parameter>
71 <parameterName value="@logLevel" />
72 <dbType value="String" />
73 <size value="240" />
74 <layout type="log4net.Layout.PatternLayout">
75 <conversionPattern value="%level" />
76 </layout>
77 </parameter>
78 <parameter>
79 <parameterName value="@logger" />
80 <dbType value="String" />
81 <size value="240" />
82 <layout type="log4net.Layout.PatternLayout">
83 <conversionPattern value="%logger" />
84 </layout>
85 </parameter>
86 <parameter>
87 <parameterName value="@message" />
88 <dbType value="String" />
89 <size value="240" />
90 <layout type="log4net.Layout.PatternLayout">
91 <conversionPattern value="%message" />
92 </layout>
93 </parameter>
94 </appender>
95 <!--定义日志的输出媒介,下面定义日志以四种方式输出。也可以下面的按照一种类型或其他类型输出。-->
96 <root>
97 <!--文件形式记录日志-->
98 <appender-ref ref="RollingFileAppender" />
99 <!--<appender-ref ref="LogFileAppender" />-->
100 <!--控制台控制显示日志-->
101 <appender-ref ref="ConsoleAppender" />
102 <!--Windows事件日志-->
103 <appender-ref ref="EventLogAppender" />
104 <!--
105 <appender-ref ref="AdoNetAppender_Access" />
106 -->
107 </root>
108 </log4net>
109 </configuration>
110
2 <configuration>
3 <configSections>
4 <section name="log4net" type="System.Configuration.IgnoreSectionHandler"/>
5 </configSections>
6 <appSettings>
7 </appSettings>
8 <log4net>
9 <!--RollingFileAppender自动截断-->
10 <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
11 <file value="log\\log.txt"/>
12 <appendToFile value="true"/>
13 <maxSizeRollBackups value="10"/>
14 <maximumFileSize value="2048KB"/>
15 <rollingStyle value="Size"/>
16 <staticLogFileName value="true"/>
17 <lockingModel type="log4net.Appender.FileAppender+MinimalLock"/>
18 <layout type="log4net.Layout.PatternLayout">
19 <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline"/>
20 </layout>
21 </appender>
22 <!--定义输出到文件中-->
23 <appender name="LogFileAppender" type="log4net.Appender.FileAppender">
24 <!--定义文件存放位置-->
25 <file value="logs.txt" />
26 <appendToFile value="true" />
27 <rollingStyle value="Date" />
28 <datePattern value="yyyyMMdd-HH:mm:ss" />
29 <layout type="log4net.Layout.PatternLayout">
30 <!--每条日志末尾的文字说明-->
31 <footer value="by author" />
32 <!--输出格式-->
33 <!--样例:2010-01-06 13:42:32,111 [10] INFO Log4NetDemo.MainClass [(null)] - info-->
34 <conversionPattern value="记录时间:%date 线程ID:[%thread] 日志级别:%-5level 出错类:%logger property:[%property{NDC}] - 错误描述:%message%newline" />
35 </layout>
36 </appender>
37 <!--定义输出到控制台命令行中-->
38 <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
39 <layout type="log4net.Layout.PatternLayout">
40 <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
41 </layout>
42 </appender>
43 <!--定义输出到windows事件中-->
44 <appender name="EventLogAppender" type="log4net.Appender.EventLogAppender">
45 <layout type="log4net.Layout.PatternLayout">
46 <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
47 </layout>
48 </appender>
49 <!--定义输出到数据库中,这里举例输出到Access数据库中,数据库为C盘的log4net.mdb-->
50 <appender name="AdoNetAppender_Access" type="log4net.Appender.AdoNetAppender">
51 <connectionString value="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=log4net.mdb" />
52 <commandText value="INSERT INTO LogDetails ([LogDate],[Thread],[Level],[Logger],[Message]) VALUES (@logDate, @thread, @logLevel, @logger,@message)" />
53 <!--定义各个参数-->
54 <parameter>
55 <parameterName value="@logDate" />
56 <dbType value="String" />
57 <size value="240" />
58 <layout type="log4net.Layout.PatternLayout">
59 <conversionPattern value="%date" />
60 </layout>
61 </parameter>
62 <parameter>
63 <parameterName value="@thread" />
64 <dbType value="String" />
65 <size value="240" />
66 <layout type="log4net.Layout.PatternLayout">
67 <conversionPattern value="%thread" />
68 </layout>
69 </parameter>
70 <parameter>
71 <parameterName value="@logLevel" />
72 <dbType value="String" />
73 <size value="240" />
74 <layout type="log4net.Layout.PatternLayout">
75 <conversionPattern value="%level" />
76 </layout>
77 </parameter>
78 <parameter>
79 <parameterName value="@logger" />
80 <dbType value="String" />
81 <size value="240" />
82 <layout type="log4net.Layout.PatternLayout">
83 <conversionPattern value="%logger" />
84 </layout>
85 </parameter>
86 <parameter>
87 <parameterName value="@message" />
88 <dbType value="String" />
89 <size value="240" />
90 <layout type="log4net.Layout.PatternLayout">
91 <conversionPattern value="%message" />
92 </layout>
93 </parameter>
94 </appender>
95 <!--定义日志的输出媒介,下面定义日志以四种方式输出。也可以下面的按照一种类型或其他类型输出。-->
96 <root>
97 <!--文件形式记录日志-->
98 <appender-ref ref="RollingFileAppender" />
99 <!--<appender-ref ref="LogFileAppender" />-->
100 <!--控制台控制显示日志-->
101 <appender-ref ref="ConsoleAppender" />
102 <!--Windows事件日志-->
103 <appender-ref ref="EventLogAppender" />
104 <!--
105 <appender-ref ref="AdoNetAppender_Access" />
106 -->
107 </root>
108 </log4net>
109 </configuration>
110
测试代码
代码
1 using System;
2 using System.Collections.Generic;
3 using System.Text;
4 using System.Windows.Forms;
5 using System.Reflection;
6 using log4net;
7 //注意下面的语句一定要加上,指定log4net使用.config文件来读取配置信息
8 //如果是WinForm(假定程序为MyDemo.exe,则需要一个MyDemo.exe.config文件)
9 //如果是WebForm,则从web.config中读取相关信息
10 [assembly: log4net.Config.XmlConfigurator(Watch = true)]
11 namespace Log4NetDemo
12 {
13 /// <summary>
14 /// 说明:本程序演示如何利用log4net记录程序日志信息。log4net是一个功能著名的开源日志记录组件。
15 /// 利用log4net可以方便地将日志信息记录到文件、控制台、Windows事件日志和数据库中(包括MS SQL Server, Access, Oracle9i,Oracle8i,DB2,SQLite)。
16 /// </summary>
17 public class MainClass
18 {
19 public static void Main(string[] args)
20 {
21 //Application.Run(new MainForm());
22 //创建日志记录组件实例
23 ILog log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
24 //记录错误日志
25 log.Error("error",new Exception("发生了一个异常"));
26 //记录严重错误
27 log.Fatal("fatal",new Exception("发生了一个致命错误"));
28 //记录一般信息
29 log.Info("info");
30 //记录调试信息
31 log.Debug("debug");
32 //记录警告信息
33 log.Warn("warn");
34 Console.WriteLine("日志记录完毕。");
35 Console.Read();
36 }
37 }
38 }
2 using System.Collections.Generic;
3 using System.Text;
4 using System.Windows.Forms;
5 using System.Reflection;
6 using log4net;
7 //注意下面的语句一定要加上,指定log4net使用.config文件来读取配置信息
8 //如果是WinForm(假定程序为MyDemo.exe,则需要一个MyDemo.exe.config文件)
9 //如果是WebForm,则从web.config中读取相关信息
10 [assembly: log4net.Config.XmlConfigurator(Watch = true)]
11 namespace Log4NetDemo
12 {
13 /// <summary>
14 /// 说明:本程序演示如何利用log4net记录程序日志信息。log4net是一个功能著名的开源日志记录组件。
15 /// 利用log4net可以方便地将日志信息记录到文件、控制台、Windows事件日志和数据库中(包括MS SQL Server, Access, Oracle9i,Oracle8i,DB2,SQLite)。
16 /// </summary>
17 public class MainClass
18 {
19 public static void Main(string[] args)
20 {
21 //Application.Run(new MainForm());
22 //创建日志记录组件实例
23 ILog log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
24 //记录错误日志
25 log.Error("error",new Exception("发生了一个异常"));
26 //记录严重错误
27 log.Fatal("fatal",new Exception("发生了一个致命错误"));
28 //记录一般信息
29 log.Info("info");
30 //记录调试信息
31 log.Debug("debug");
32 //记录警告信息
33 log.Warn("warn");
34 Console.WriteLine("日志记录完毕。");
35 Console.Read();
36 }
37 }
38 }
下面是便是强大的LogHelper类,如果用于web,注意记得在global.asax里面调用LogHelper里的init初始化方法。
代码
1 using System;
2 using System.Collections.Generic;
3 using System.Text;
4 using log4net;
5 [assembly: log4net.Config.XmlConfigurator(Watch = true)]
6 namespace The9web.Common
7 {
8 public class LogHelper
9 {
10 /// <summary>
11 /// 静态类
12 /// </summary>
13 private LogHelper() { }
14 private const string LOG_REPOSITORY = "Default"; // this should likely be set in the web config.
15 private static ILog m_log;
16 /// <summary>
17 /// 初始化日志系统
18 /// 在系统运行开始初始化
19 /// Global.asax Application_Start内
20 /// </summary>
21 public static void Init()
22 {
23 log4net.Config.XmlConfigurator.Configure();
24 }
25 /// <summary>
26 /// 写入日志
27 /// </summary>
28 /// <param name="message">日志信息</param>
29 /// <param name="messageType">日志类型</param>
30 public static void Write(string message, LogMessageType messageType)
31 {
32 DoLog(message, messageType, null, Type.GetType("System.Object"));
33 }
34 /// <summary>
35 /// 写入日志
36 /// </summary>
37 /// <param name="message">日志信息</param>
38 /// <param name="messageType">日志类型</param>
39 /// <param name="type"></param>
40 public static void Write(string message, LogMessageType messageType, Type type)
41 {
42 DoLog(message, messageType, null, type);
43 }
44 /// <summary>
45 /// 写入日志
46 /// </summary>
47 /// <param name="message">日志信息</param>
48 /// <param name="messageType">日志类型</param>
49 /// <param name="ex">异常</param>
50 public static void Write(string message, LogMessageType messageType, Exception ex)
51 {
52 DoLog(message, messageType, ex, Type.GetType("System.Object"));
53 }
54 /// <summary>
55 /// 写入日志
56 /// </summary>
57 /// <param name="message">日志信息</param>
58 /// <param name="messageType">日志类型</param>
59 /// <param name="ex">异常</param>
60 /// <param name="type"></param>
61 public static void Write(string message, LogMessageType messageType, Exception ex, Type type)
62 {
63 DoLog(message, messageType, ex, type);
64 }
65 /// <summary>
66 /// 断言
67 /// </summary>
68 /// <param name="condition">条件</param>
69 /// <param name="message">日志信息</param>
70 public static void Assert(bool condition, string message)
71 {
72 Assert(condition, message, Type.GetType("System.Object"));
73 }
74 /// <summary>
75 /// 断言
76 /// </summary>
77 /// <param name="condition">条件</param>
78 /// <param name="message">日志信息</param>
79 /// <param name="type">日志类型</param>
80 public static void Assert(bool condition, string message, Type type)
81 {
82 if (condition == false)
83 Write(message, LogMessageType.Info);
84 }
85 /// <summary>
86 /// 保存日志
87 /// </summary>
88 /// <param name="message">日志信息</param>
89 /// <param name="messageType">日志类型</param>
90 /// <param name="ex">异常</param>
91 /// <param name="type">日志类型</param>
92 private static void DoLog(string message, LogMessageType messageType, Exception ex,
93 Type type)
94 {
95 m_log = LogManager.GetLogger(type);
96 switch (messageType)
97 {
98 case LogMessageType.Debug:
99 LogHelper.m_log.Debug(message, ex);
100 break;
101 case LogMessageType.Info:
102 LogHelper.m_log.Info(message, ex);
103 break;
104 case LogMessageType.Warn:
105 LogHelper.m_log.Warn(message, ex);
106 break;
107 case LogMessageType.Error:
108 LogHelper.m_log.Error(message, ex);
109 break;
110 case LogMessageType.Fatal:
111 LogHelper.m_log.Fatal(message, ex);
112 break;
113 }
114 }
115 /// <summary>
116 /// 日志类型
117 /// </summary>
118 public enum LogMessageType
119 {
120 /// <summary>
121 /// 调试
122 /// </summary>
123 Debug,
124 /// <summary>
125 /// 信息
126 /// </summary>
127 Info,
128 /// <summary>
129 /// 警告
130 /// </summary>
131 Warn,
132 /// <summary>
133 /// 错误
134 /// </summary>
135 Error,
136 /// <summary>
137 /// 致命错误
138 /// </summary>
139 Fatal
140 }
141 }
142 }
143
2 using System.Collections.Generic;
3 using System.Text;
4 using log4net;
5 [assembly: log4net.Config.XmlConfigurator(Watch = true)]
6 namespace The9web.Common
7 {
8 public class LogHelper
9 {
10 /// <summary>
11 /// 静态类
12 /// </summary>
13 private LogHelper() { }
14 private const string LOG_REPOSITORY = "Default"; // this should likely be set in the web config.
15 private static ILog m_log;
16 /// <summary>
17 /// 初始化日志系统
18 /// 在系统运行开始初始化
19 /// Global.asax Application_Start内
20 /// </summary>
21 public static void Init()
22 {
23 log4net.Config.XmlConfigurator.Configure();
24 }
25 /// <summary>
26 /// 写入日志
27 /// </summary>
28 /// <param name="message">日志信息</param>
29 /// <param name="messageType">日志类型</param>
30 public static void Write(string message, LogMessageType messageType)
31 {
32 DoLog(message, messageType, null, Type.GetType("System.Object"));
33 }
34 /// <summary>
35 /// 写入日志
36 /// </summary>
37 /// <param name="message">日志信息</param>
38 /// <param name="messageType">日志类型</param>
39 /// <param name="type"></param>
40 public static void Write(string message, LogMessageType messageType, Type type)
41 {
42 DoLog(message, messageType, null, type);
43 }
44 /// <summary>
45 /// 写入日志
46 /// </summary>
47 /// <param name="message">日志信息</param>
48 /// <param name="messageType">日志类型</param>
49 /// <param name="ex">异常</param>
50 public static void Write(string message, LogMessageType messageType, Exception ex)
51 {
52 DoLog(message, messageType, ex, Type.GetType("System.Object"));
53 }
54 /// <summary>
55 /// 写入日志
56 /// </summary>
57 /// <param name="message">日志信息</param>
58 /// <param name="messageType">日志类型</param>
59 /// <param name="ex">异常</param>
60 /// <param name="type"></param>
61 public static void Write(string message, LogMessageType messageType, Exception ex, Type type)
62 {
63 DoLog(message, messageType, ex, type);
64 }
65 /// <summary>
66 /// 断言
67 /// </summary>
68 /// <param name="condition">条件</param>
69 /// <param name="message">日志信息</param>
70 public static void Assert(bool condition, string message)
71 {
72 Assert(condition, message, Type.GetType("System.Object"));
73 }
74 /// <summary>
75 /// 断言
76 /// </summary>
77 /// <param name="condition">条件</param>
78 /// <param name="message">日志信息</param>
79 /// <param name="type">日志类型</param>
80 public static void Assert(bool condition, string message, Type type)
81 {
82 if (condition == false)
83 Write(message, LogMessageType.Info);
84 }
85 /// <summary>
86 /// 保存日志
87 /// </summary>
88 /// <param name="message">日志信息</param>
89 /// <param name="messageType">日志类型</param>
90 /// <param name="ex">异常</param>
91 /// <param name="type">日志类型</param>
92 private static void DoLog(string message, LogMessageType messageType, Exception ex,
93 Type type)
94 {
95 m_log = LogManager.GetLogger(type);
96 switch (messageType)
97 {
98 case LogMessageType.Debug:
99 LogHelper.m_log.Debug(message, ex);
100 break;
101 case LogMessageType.Info:
102 LogHelper.m_log.Info(message, ex);
103 break;
104 case LogMessageType.Warn:
105 LogHelper.m_log.Warn(message, ex);
106 break;
107 case LogMessageType.Error:
108 LogHelper.m_log.Error(message, ex);
109 break;
110 case LogMessageType.Fatal:
111 LogHelper.m_log.Fatal(message, ex);
112 break;
113 }
114 }
115 /// <summary>
116 /// 日志类型
117 /// </summary>
118 public enum LogMessageType
119 {
120 /// <summary>
121 /// 调试
122 /// </summary>
123 Debug,
124 /// <summary>
125 /// 信息
126 /// </summary>
127 Info,
128 /// <summary>
129 /// 警告
130 /// </summary>
131 Warn,
132 /// <summary>
133 /// 错误
134 /// </summary>
135 Error,
136 /// <summary>
137 /// 致命错误
138 /// </summary>
139 Fatal
140 }
141 }
142 }
143
对的就做,做的就对