看了log4net的简单使用之一_log4net介绍 大家对log4net组件应该有了大概的了解
,
下面再近一步介绍其在项目中如何应用。
1.Logger
所有的记录器都必须实现 ILog 接口,该接口提供日志记录所需的大量方法。
public interface ILog : ILoggerWrapper
{
void Debug(...);
void Error(...);
void Fatal(...);
void Info(...);
void Warn(...);
bool IsDebugEnabled { get; }
bool IsErrorEnabled { get; }
bool IsFatalEnabled { get; }
bool IsInfoEnabled { get; }
bool IsWarnEnabled { get; }
}
通常情况下,我们通过 LogManager.GetLogger() 来获取一个记录器。LogManager 内部维护一个 hashtable,保存新创建 Logger 引用,下次需要时直接从 hashtable 获取其实例。
ILog log = LogManager.GetLogger(this.GetType());
log.Debug("aaaaaaaaaaaaaaa");
所有
Logger
的参数设置都直接或间接继承自
root
,其继承关系类似
namespace
。比如,名为
"MyLogger.X.Y"
参数设置继承自
"MyLogger.X"
。当我们创建
"MyLooger.X.Y"
记录器时,会在配置文件找该名称的记录器设置,如果没找到,则按继承关系向上查找,直到
root
。因此,在创建
Logger
时,我们通常使用类型名称做为记录器的名字,缺省情况下,它会使用
root
或某一个父配置,但在需要的时候,我们随时可以为具体的类型添加一个更加
"
详细
"
的配置。
1
<?
xml version
=
"
1.0
"
encoding
=
"
utf-8
"
?>
2
<
log4net
>
3
<
appender name
=
"
Console
"
type
=
"
log4net.Appender.ConsoleAppender
"
>
4
<
layout type
=
"
log4net.Layout.PatternLayout
"
>
5
<
conversionPattern value
=
"
%5level [%thread] (%file:%line) - %message%newline
"
/>
6
</
layout
>
7
</
appender
>
8
9
<
logger name
=
"
Learn.Library.Log4netTest
"
>
10
<
level value
=
"
ALL
"
/>
11
</
logger
>
12
13
<
root
>
14
<
level value
=
"
OFF
"
/>
15
<
appender
-
ref
ref
=
"
Console
"
/>
16
</
root
>
17
</
log4net
>
18
"appender-ref" 参数用于绑定一个或多个具体的 Appender。
1
<?
xml version
=
"
1.0
"
encoding
=
"
utf-8
"
?>
2
<
log4net
>
3
<
appender name
=
"
Console
"
type
=
"
log4net.Appender.ConsoleAppender
"
>
4
</
appender
>
5
6
<
appender name
=
"
RollingFile
"
type
=
"
log4net.Appender.RollingFileAppender
"
>
7
</
appender
>
8
9
<
root
>
10
<
level value
=
"
DEBUG
"
/>
11
<
appender
-
ref
ref
=
"
Console
"
/>
12
<
appender
-
ref
ref
=
"
RollingFile
"
/>
13
</
root
>
14
</
log4net
>
15
2 Appender / Layout Log4net 提供了大量的 Appender,最常用的包括 AdoNetAppender、AspNetTraceAppender、ConsoleAppender、FileAppender、OutputDebugStringAppender。每种 Appender 都有特定一些参数,使用时直接从《Log4net 手册》的示例中拷贝过去,就OK了。(代码摘自 Log4net 手册)
(1) AspNetTraceAppender
1
<
appender name
=
"
AspNetTraceAppender
"
type
=
"
log4net.Appender.AspNetTraceAppender
"
>
2
<
layout type
=
"
log4net.Layout.PatternLayout
"
>
3
<
conversionPattern value
=
"
%date [%thread] %-5level %logger [%property{NDC}] - %message%newline
"
/>
4
</
layout
>
5
</
appender
>
6
(2) ConsoleAppender
1
<
appender name
=
"
ConsoleAppender
"
type
=
"
log4net.Appender.ConsoleAppender
"
>
2
<
layout type
=
"
log4net.Layout.PatternLayout
"
>
3
<
conversionPattern value
=
"
%date [%thread] %-5level %logger [%property{NDC}] - %message%newline
"
/>
4
</
layout
>
5
</
appender
>
6
(3) FileAppender
1
<
appender name
=
"
FileAppender
"
type
=
"
log4net.Appender.FileAppender
"
>
2
<
file value
=
"
log-file.txt
"
/>
3
<
appendToFile value
=
"
true
"
/>
4
<
layout type
=
"
log4net.Layout.PatternLayout
"
>
5
<
conversionPattern value
=
"
%date [%thread] %-5level %logger [%property{NDC}] - %message%newline
"
/>
6
</
layout
>
7
</
appender
>
8
有关 Layout 详细信息,请参考 Log4net 相关文档,本文不做详述。
3. Configuration
Log4net 的配置方式十分灵活,即可以写到应用程序配置文件中,也可以使用独立配置文件。同时它还提供了监测配置文件变化的功能,这样我们随时可以调整配置,而无须重启应用程序。
(1) 使用 app.config / web.config
配置app.config / web.config文件
1
<?
xml version
=
"
1.0
"
encoding
=
"
utf-8
"
?>
2
<!--
3
注意: 除了手动编辑此文件以外,您还可以使用
4
Web 管理工具来配置应用程序的设置。可以使用 Visual Studio 中的
5
“网站”
->
“Asp.Net 配置”选项。
6
设置和注释的完整列表在
7
machine.config.comments 中,该文件通常位于
8
\Windows\Microsoft.Net\Framework\v2.x\Config 中
9
-->
10
<
configuration
>
11
<
configSections
>
12
<
section name
=
"
log4net
"
type
=
"
log4net.Config.Log4NetConfigurationSectionHandler,log4net
"
/>
13
</
configSections
>
14
<
appSettings
/>
15
<
connectionStrings
/>
16
<
log4net
>
17
<
root
>
18
<
level value
=
"
ALL
"
/>
19
<
appender
-
ref
ref
=
"
LogFileAppender
"
/>
20
<
appender
-
ref
ref
=
"
RollingFileAppender
"
/>
21
<
appender
-
ref
ref
=
"
AdoNetAppender_SqlServer
"
/>
22
</
root
>
23
<!--
24
写入文件中
-->
25
<
appender name
=
"
LogFileAppender
"
type
=
"
log4net.Appender.FileAppender
"
>
26
<
file value
=
"
D:\log-file1.txt
"
/>
27
<!--
Example
using
environment variables
in
params
-->
28
<!--
<
file value
=
"
${TMP}\log-file.txt
"
/>
-->
29
<!--<
sppendToFile value
=
"
true
"
/>-->
30
<!--
An alternate output encoding can be specified
-->
31
<!--
<
encoding value
=
"
unicodeFFFE
"
/>
-->
32
<
layout type
=
"
log4net.Layout.PatternLayout
"
>
33
<!--<
footer value
=
"
[Footer] Test By Ring1981
"
/>-->
34
<
conversionPattern value
=
"
%date [%thread] %-5level %logger [%ndc] <%property{auth}> - %message%newline
"
/>
35
</
layout
>
36
<!--
Alternate layout
using
XML
37
<
layout type
=
"
log4net.Layout.XMLLayout
"
/>
-->
38
</
appender
>
39
40
<!--
将日志以回滚文件的形式写到文件中
41
为做测试,我把文件大小设置为1K,大于它,就重新生成文档
42
-->
43
<
appender name
=
"
RollingFileAppender
"
type
=
"
log4net.Appender.RollingFileAppender
"
Threshold
=
"
Error
"
>
44
<
file value
=
"
log.txt
"
/>
45
<
appendToFile value
=
"
true
"
/>
46
<
rollingStyle value
=
"
Size
"
/>
47
<
maxSizeRollBackups value
=
"
10
"
/>
48
<
maximumFileSize value
=
"
1KB
"
/>
49
<
staticLogFileName value
=
"
true
"
/>
50
<
layout type
=
"
log4net.Layout.PatternLayout
"
>
51
<
conversionPattern value
=
"
%date [%thread] %-5level %logger [%property{NDC}] - %message%newline
"
/>
52
</
layout
>
53
</
appender
>
54
55
56
<!--
将日志记录到数据库中。采用存储过程两种方式
57
备注:也可采用SQL语句的方式,主要就是commandType, commandText属性设置不同,请
58
参见log4net官方文档
59
-->
60
<
appender name
=
"
AdoNetAppender_SqlServer
"
type
=
"
log4net.Appender.AdoNetAppender
"
Threshold
=
"
Fatal
"
>
61
<
bufferSize value
=
"
0
"
/>
62
<
connectionType value
=
"
System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
"
/>
63
<
connectionString value
=
"
data source=.;initial catalog=aigoshop;integrated security=false;persist security info=True;User ID=sa;Password=
"
/>
64
<
commandType value
=
"
StoredProcedure
"
/>
65
<
commandText value
=
"
WriteLog
"
/>
66
<
parameter
>
67
<
parameterName value
=
"
@log_date
"
/>
68
<
dbType value
=
"
DateTime
"
/>
69
<
layout type
=
"
log4net.Layout.PatternLayout
"
value
=
"
%date{yyyy'-'MM'-'dd HH':'mm':'ss'.'fff}
"
/>
70
</
parameter
>
71
<
parameter
>
72
<
parameterName value
=
"
@thread
"
/>
73
<
dbType value
=
"
String
"
/>
74
<
size value
=
"
255
"
/>
75
<
layout type
=
"
log4net.Layout.PatternLayout
"
value
=
"
%thread
"
/>
76
</
parameter
>
77
<
parameter
>
78
<
parameterName value
=
"
@log_level
"
/>
79
<
dbType value
=
"
String
"
/>
80
<
size value
=
"
20
"
/>
81
<
layout type
=
"
log4net.Layout.PatternLayout
"
value
=
"
%level
"
/>
82
</
parameter
>
83
<
parameter
>
84
<
parameterName value
=
"
@logger
"
/>
85
<
dbType value
=
"
String
"
/>
86
<
size value
=
"
255
"
/>
87
<
layout type
=
"
log4net.Layout.PatternLayout
"
value
=
"
%logger
"
/>
88
</
parameter
>
89
<
parameter
>
90
<
parameterName value
=
"
@message
"
/>
91
<
dbType value
=
"
String
"
/>
92
<
size value
=
"
4000
"
/>
93
<
layout type
=
"
log4net.Layout.PatternLayout
"
value
=
"
%message
"
/>
94
</
parameter
>
95
</
appender
>
96
97
98
</
log4net
>
99
<
system.web
>
100
101
<
compilation debug
=
"
false
"
/>
102
103
<
authentication mode
=
"
Windows
"
/>
104
105
</
system.web
>
106
</
configuration
>
107
使用代码初始化配置。
log4net.Config.XmlConfigurator.Configure();
(2) 使用自定义配置文件
test.log4net
1
<?
xml version
=
"
1.0
"
encoding
=
"
utf-8
"
?>
2
<
log4net
>
3
<
appender name
=
"
Console
"
type
=
"
log4net.Appender.ConsoleAppender
"
>
4
<
layout type
=
"
log4net.Layout.PatternLayout
"
>
5
<
conversionPattern value
=
"
%5level [%thread] (%file:%line) - %message%newline
"
/>
6
</
layout
>
7
</
appender
>
8
9
<
root
>
10
<
level value
=
"
DEBUG
"
/>
11
<
appender
-
ref
ref
=
"
Console
"
/>
12
</
root
>
13
</
log4net
>
14
使用代码初始化配置。
log4net.Config.XmlConfigurator.Configure(new FileInfo("test.log4net"));
使用 XmlConfigurator.ConfigureAndWatch() 方法除了初始化配置外,还会监测配置文件的变化,一旦发生修改,将自动刷新配置。
(3) XmlConfiguratorAttribute
我们还可以使用 XmlConfiguratorAttribute 代替 XmlConfigurator.Config()/ConfigureAndWatch(),ConfiguratorAttribute 用于定义与 Assembly 相关联的配置文件名。
方式1: 关联到 test.log4net,并监测变化。
[assembly:log4net.Config.XmlConfigurator(ConfigFile="test.log4net", Watch=true)]
方式2: 关联到 test.exe.log4net (或 test.dll.log4net,文件名前缀为当前程序集名称),并监测变化。
[assembly:log4net.Config.XmlConfigurator(ConfigFileExtension="log4net", Watch=true)]
4.应用log4netDemo下载
备注:
CREATE
TABLE
[
dbo
]
.
[
Log
]
(
[
ID
]
[
int
]
IDENTITY
(
1
,
1
)
NOT
NULL
,
[
Date
]
[
datetime
]
NOT
NULL
,
[
Thread
]
[
varchar
]
(
255
) COLLATE Chinese_PRC_CI_AS
NOT
NULL
,
[
Level
]
[
varchar
]
(
20
) COLLATE Chinese_PRC_CI_AS
NOT
NULL
,
[
Logger
]
[
varchar
]
(
255
) COLLATE Chinese_PRC_CI_AS
NOT
NULL
,
[
Message
]
[
varchar
]
(
4000
) COLLATE Chinese_PRC_CI_AS
NOT
NULL
)
ON
[
PRIMARY
]
GO
CREATE
PROCEDURE
WriteLog
@log_date
datetime
,
@thread
varchar
(
255
),
@log_level
varchar
(
20
),
@logger
varchar
(
255
),
@message
varchar
(
4000
)
AS
INSERT
INTO
Log
(
[
Date
]
,
[
Thread
]
,
[
Level
]
,
[
Logger
]
,
[
Message
]
)
VALUES
(
@log_date
,
@thread
,
@log_level
,
@logger
,
@message
)
GO
运行完程序后,看到文件和数据库日志表都写入了两条。想到能否在数据库正常打开时只写日志表,在数据库连接不上而写到日志文件中呢。哈。。请看第三篇:log4net的简单使用之三_ log4net高级应用
备注:
参考:Log4net 简明手册 - Q_yuhen.htm