log4net封装类

封装说明:

  1.使用静态方法调用即可写入日志。

  2.在日志信息写入之前,定义委托处理日志信息,便于记录日志信息之前,显示给用户。

  3.添加代码配置Log4net,避免应用程序总是携带配置文件。如果需要使用配置文件,即可在AssemblyInfo.cs添加

    [assembly: log4net.Config.XmlConfigurator(ConfigFile = "log.xml", Watch = false)]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
展开代码
 
 
using System;
using System.Data;
using System.Text;
using log4net;
using log4net.Appender;
using log4net.Config;
using log4net.Layout;
using log4net.Repository.Hierarchy;
 
namespace Chen.Common
{
    public class Log4NetHelp
    {
        #region 变量定义
        //定义信息的二次处理
        public static event Action<string> OutputMessage;
        //ILog对象
        private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        //记录异常日志数据库连接字符串
        private const string _ConnectionString = @"data source=your server;initial catalog=your db;integrated security=false;persist security info=True;User ID=sa;Password=1111";
        //信息模板
        private const string _ConversionPattern = "%n【记录时间】%date%n【描述】%message%n";
        #endregion
 
        #region 定义信息二次处理方式
        private static void HandMessage(object Msg)
        {
            if (OutputMessage != null)
            {
                OutputMessage(Msg.ToString());
            }
        }
        private static void HandMessage(object Msg, Exception ex)
        {
            if (OutputMessage != null)
            {
                OutputMessage(string.Format("{0}:{1}", Msg.ToString(), ex.ToString()));
            }
        }
        private static void HandMessage(string format, params object[] args)
        {
            if (OutputMessage != null)
            {
                OutputMessage(string.Format(format, args));
            }
        }
        #endregion
 
        #region 封装Log4net
        public static void Debug(object message)
        {
            HandMessage(message);
            if (log.IsDebugEnabled)
            {
                log.Debug(message);
            }
        }
        public static void Debug(object message, Exception ex)
        {
            HandMessage(message, ex);
            if (log.IsDebugEnabled)
            {
                log.Debug(message, ex);
            }
        }
        public static void DebugFormat(string format, params object[] args)
        {
            HandMessage(format, args);
            if (log.IsDebugEnabled)
            {
                log.DebugFormat(format, args);
            }
        }
        public static void Error(object message)
        {
            HandMessage(message);
            if (log.IsErrorEnabled)
            {
                log.Error(message);
            }
        }
        public static void Error(object message, Exception ex)
        {
            HandMessage(message, ex);
            if (log.IsErrorEnabled)
            {
                log.Error(message, ex);
            }
        }
        public static void ErrorFormat(string format, params object[] args)
        {
            HandMessage(format, args);
            if (log.IsErrorEnabled)
            {
                log.ErrorFormat(format, args);
            }
        }
        public static void Fatal(object message)
        {
            HandMessage(message);
            if (log.IsFatalEnabled)
            {
                log.Fatal(message);
            }
        }
        public static void Fatal(object message, Exception ex)
        {
            HandMessage(message, ex);
            if (log.IsFatalEnabled)
            {
                log.Fatal(message, ex);
            }
        }
        public static void FatalFormat(string format, params object[] args)
        {
            HandMessage(format, args);
            if (log.IsFatalEnabled)
            {
                log.FatalFormat(format, args);
            }
        }
        public static void Info(object message)
        {
            HandMessage(message);
            if (log.IsInfoEnabled)
            {
                log.Info(message);
            }
        }
        public static void Info(object message, Exception ex)
        {
            HandMessage(message, ex);
            if (log.IsInfoEnabled)
            {
                log.Info(message, ex);
            }
        }
        public static void InfoFormat(string format, params object[] args)
        {
            HandMessage(format, args);
            if (log.IsInfoEnabled)
            {
                log.InfoFormat(format, args);
            }
        }
        public static void Warn(object message)
        {
            HandMessage(message);
            if (log.IsWarnEnabled)
            {
                log.Warn(message);
            }
        }
        public static void Warn(object message, Exception ex)
        {
            HandMessage(message, ex);
            if (log.IsWarnEnabled)
            {
                log.Warn(message, ex);
            }
        }
        public static void WarnFormat(string format, params object[] args)
        {
            HandMessage(format, args);
            if (log.IsWarnEnabled)
            {
                log.WarnFormat(format, args);
            }
        }
        #endregion
 
        #region 手动加载配置
        public static void LoadADONetAppender()
        {
            Hierarchy hier = LogManager.GetLoggerRepository() as log4net.Repository.Hierarchy.Hierarchy;
            if (hier != null)
            {
                log4net.Appender.AdoNetAppender appender = new log4net.Appender.AdoNetAppender();
                appender.Name = "AdoNetAppender";
                appender.CommandType = CommandType.Text;
                appender.BufferSize = 1;
                appender.ConnectionType = "System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
                appender.ConnectionString = _ConnectionString;
                appender.CommandText = @"INSERT INTO Log ([Date],[Thread],[Level],[Logger],[Message],[Exception]) VALUES (@log_date, @thread, @log_level, @logger, @message, @exception)";
                appender.AddParameter(new AdoNetAppenderParameter { ParameterName = "@log_date", DbType = System.Data.DbType.DateTime, Layout = new log4net.Layout.RawTimeStampLayout() });
                appender.AddParameter(new AdoNetAppenderParameter { ParameterName = "@thread", DbType = System.Data.DbType.String, Size = 255, Layout = new Layout2RawLayoutAdapter(new PatternLayout("%thread")) });
                appender.AddParameter(new AdoNetAppenderParameter { ParameterName = "@log_level", DbType = System.Data.DbType.String, Size = 50, Layout = new Layout2RawLayoutAdapter(new PatternLayout("%level")) });
                appender.AddParameter(new AdoNetAppenderParameter { ParameterName = "@logger", DbType = System.Data.DbType.String, Size = 255, Layout = new Layout2RawLayoutAdapter(new PatternLayout("%logger")) });
                appender.AddParameter(new AdoNetAppenderParameter { ParameterName = "@message", DbType = System.Data.DbType.String, Size = 4000, Layout = new Layout2RawLayoutAdapter(new PatternLayout("%message")) });
                appender.AddParameter(new AdoNetAppenderParameter { ParameterName = "@exception", DbType = System.Data.DbType.String, Size = 4000, Layout = new Layout2RawLayoutAdapter(new ExceptionLayout()) });
                appender.ActivateOptions();
                BasicConfigurator.Configure(appender);
            }
        }
 
        public static void LoadFileAppender()
        {
            FileAppender appender = new FileAppender();
            appender.Name = "FileAppender";
            appender.File = "error.log";
            appender.AppendToFile = true;
 
            PatternLayout patternLayout = new PatternLayout();
            patternLayout.ConversionPattern = _ConversionPattern;
            patternLayout.ActivateOptions();
            appender.Layout = patternLayout;
 
            //选择UTF8编码,确保中文不乱码。
            appender.Encoding = Encoding.UTF8;
 
            appender.ActivateOptions();
            BasicConfigurator.Configure(appender);
 
        }
 
        public static void LoadRollingFileAppender()
        {
            RollingFileAppender appender = new RollingFileAppender();
            appender.AppendToFile = true;
            appender.Name = "RollingFileAppender";
            appender.DatePattern = "yyyy-MM-dd HH'时.log'";
            appender.File = "Logs/";
            appender.AppendToFile = true;
            appender.RollingStyle = RollingFileAppender.RollingMode.Composite;
            appender.MaximumFileSize = "500kb";
            appender.MaxSizeRollBackups = 10;
            appender.StaticLogFileName = false;
 
 
            PatternLayout patternLayout = new PatternLayout();
            patternLayout.ConversionPattern = _ConversionPattern;
            patternLayout.ActivateOptions();
            appender.Layout = patternLayout;
 
            //选择UTF8编码,确保中文不乱码。
            appender.Encoding = Encoding.UTF8;
 
            appender.ActivateOptions();
            BasicConfigurator.Configure(appender);
        }
 
        public static void LoadConsoleAppender()
        {
            ConsoleAppender appender = new ConsoleAppender();
            appender.Name = "ConsoleAppender";
 
            PatternLayout patternLayout = new PatternLayout();
            patternLayout.ConversionPattern = _ConversionPattern;
            patternLayout.ActivateOptions();
            appender.Layout = patternLayout;
 
            appender.ActivateOptions();
            BasicConfigurator.Configure(appender);
        }
 
        public static void LoadTraceAppender()
        {
            TraceAppender appender = new TraceAppender();
            appender.Name = "TraceAppender";
 
            PatternLayout patternLayout = new PatternLayout();
            patternLayout.ConversionPattern = _ConversionPattern;
            patternLayout.ActivateOptions();
            appender.Layout = patternLayout;
 
            appender.ActivateOptions();
            BasicConfigurator.Configure(appender);
        }
 
        public static void LoadEventLogAppender()
        {
            EventLogAppender appender = new EventLogAppender();
            appender.Name = "EventLogAppender";
 
            PatternLayout patternLayout = new PatternLayout();
            patternLayout.ConversionPattern = _ConversionPattern;
            patternLayout.ActivateOptions();
            appender.Layout = patternLayout;
 
            appender.ActivateOptions();
            BasicConfigurator.Configure(appender);
        }
        #endregion
 
        #region 定义常规应用程序中未处理的异常信息记录方式
        public static void LoadUnhandledException()
        {
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler
 ((sender, e) =>
 {
     log.Fatal("未处理的异常", e.ExceptionObject as Exception);
 });
        }
        #endregion
    }
}

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
log.xml
 
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="log4net" type="System.Configuration.IgnoreSectionHandler"/>
  </configSections>
  <log4net>
    <!--定义输出到文件中-->
    <appender name="SysAppender" type="log4net.Appender.RollingFileAppender">
      <!--日志的路径-->
      <file value="Logs/" />
      <!--是否覆盖,默认是追加true-->
      <appendToFile value="true"/>
      <rollingStyle value="Composite"/>
      <!--文件名称-->
      <DatePattern value="yyyy-MM-dd HH'时.log'"></DatePattern>
      <!--设置无限备份=-1 ,最大备份数为1000-->
      <param name="MaxSizeRollBackups" value="1000"/>
      <!--每个文件的大小-->
      <param name="MaximumFileSize" value="500KB"/>
      <!--名称是否可以更改 为false为可以更改-->
      <param name="StaticLogFileName" value="false"/>
      <layout type="log4net.Layout.PatternLayout">
        <!--输出格式-->
        <conversionPattern value="%n【记录时间】%date%n【描述】%message%n"/>
      </layout>
    </appender>
    <!--定义输出到控制台命令行中-->
    <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%n【记录时间】%date%n【描述】%message%n"/>
      </layout>
    </appender>
    <!--定义输出到windows事件中-->
    <appender name="EventLogAppender" type="log4net.Appender.EventLogAppender">
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%n==========
%n【日志级别】%-5level
%n【记录时间】%date
%n【线程编号】[%thread]
%n【执行时间】[%r]毫秒
%n【出错文件】%F
%n【出错行号】%L
%n【出错的类】%logger 属性[%property{NDC}]
%n【错误描述】%message
%n【错误详情】%newline"/>
      </layout>
    </appender>
    <!--定义输出到Trace中-->
    <appender name="TraceAppender" type="log4net.Appender.TraceAppender">
      <layout type="log4net.Layout.PatternLayout">
        <!--<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />-->
        <conversionPattern value="%n==========
%n【日志级别】%-5level
%n【记录时间】%date
%n【线程编号】[%thread]
%n【执行时间】[%r]毫秒
%n【出错文件】%F
%n【出错行号】%L
%n【出错的类】%logger 属性[%property{NDC}]
%n【错误描述】%message
%n【错误详情】%newline"/>
      </layout>
    </appender>
    <!--定义日志的输出媒介,下面定义日志以四种方式输出。也可以下面的按照一种类型或其他类型输出。-->
    <root>
      <!--日志的级别 OFF > FATAL > ERROR > WARN > INFO > DEBUG > ALL 只有日志输出级别大于或等于配置的级别才能输出日志信息-->
      <level value="ALL" />