您的位置:首页 > 其它

Log4net 日志使用介绍

2015-08-04 11:51 417 查看

概述

Log4net 有三个主要组件:loggers,appenders 和 layouts。这三个组件一起工作使得开发者能够根据信息类型和等级(Level)记录信息,以及在运行时控制信息的格式化和信息的写入位置(如控制台,文件,内存,数据库等)。过滤器(filter)帮助这些组件,控制追加器(appender)的行为和把对象转换成字符串的对象渲染。

如果对log4net的基本使用并不是很清楚,可以参考我的另一遍介绍:Log4net入门使用

日志(Loggers)

日志请求是通过调用一个日志实例的打印方法(log4net.ILog)完成。这些打印方法是 Debug、Info、Warn、Error 和 Fatal。

根据定义,打印方法决定日志请求的等级。例如,如果 log 是一个日志器的实例,那么,语句 log.Info("..") 是等级为 INFO 的日志请求。

如果它的等级大于等于它日志器的等级,那么日志请求就被认为已启用。否则,请求被认为禁用。没有分配等级的日志器将从层次上继承。规则如下:


Basic Selection Rule

A log request of level L in a logger with (either assigned or inherited, whichever is appropriate) level K, is enabled if L >= K.


该规则是 log4net 的核心。它假设等级是有序的。对于标准等级,具有 DEBUG < INFO < WARN < ERROR < FATAL。

用相同的参数调用 log4net.LogManager.GetLogger 方法总是返回引用一个完全相同 logger 对象。如下所示:

[code]
[code]ILog x = LogManager.GetLogger("wombat");

ILog y = LogManager.GetLogger("wombat");

[/code]
[/code]
x 和 y 完全引用一个相同的 logger 对象。

因此,有可能配置一个日志器,然后在代码中的任何地方都可以检索到相同的实例。在生物学上,父母总是先于它们的孩子,而 log4net 日志器可以以任何顺序创建和配置。具体地说,一个“父”日志器将发现和链接到它的后代,即使它在它的后代之后才实例化。

log4net 环境的配置通常是在应用程序初始化。优先的方法是读取一个配置文件。

追加器(Appenders)

已经实现的输出方式有:

AdoNetAppender 将日志记录到数据库中。可以采用SQL和存储过程两种方式。

AnsiColorTerminalAppender 将日志高亮输出到ANSI终端。

AspNetTraceAppender 能用asp.net中Trace的方式查看记录的日志。

BufferingForwardingAppender 在输出到子Appenders之前先缓存日志事件。

ConsoleAppender 将日志输出到应用程序控制台。

EventLogAppender 将日志写到Windows Event Log。

FileAppender 将日志输出到文件。

ForwardingAppender 发送日志事件到子Appenders。

LocalSyslogAppender 将日志写到local syslog service (仅用于UNIX环境下)。

MemoryAppender 将日志存到内存缓冲区。

NetSendAppender 将日志输出到Windows Messenger service.这些日志信息将在用户终端的对话框中显示。

OutputDebugStringAppender 将日志输出到Debuger,如果程序没有Debuger,就输出到系统Debuger。如果系统Debuger也不可用,将忽略消息。

RemoteSyslogAppender 通过UDP网络协议将日志写到Remote syslog service。

RemotingAppender 通过.NET Remoting将日志写到远程接收端。

RollingFileAppender 将日志以回滚文件的形式写到文件中。

SmtpAppender 将日志写到邮件中。

SmtpPickupDirAppender 将消息以文件的方式放入一个目录中,像IIS SMTP agent这样的SMTP代理就可以阅读或发送它们。

TelnetAppender 客户端通过Telnet来接受日志事件。

TraceAppender 将日志写到.NET trace 系统。

UdpAppender 将日志以无连接UDP数据报的形式送到远程宿主或用UdpClient的形式广播。

AdoNetAppender

将日志记录到数据库中。详情参考 log4net.Appender. AdoNetAppender SDK文档

MS SQL Server

建立数据表:

[code]176 [main] INFO  Com.Foo.Bar - Located nearest gas station.

[/code]
[/code]
第一个域是流逝毫秒时间;第二个域是日志请求的线程;第三个域日志语句等级,如 INFO、WARN、ERROR 等;第四个域是与日志请求相关的日志器的名称。“-”后面的文本是具体消息。

下表是 log4net 中定义的布局:

类型

描述

log4net.Layout.ExceptionLayout

Renders the exception text from the logging event.

log4net.Layout.PatternLayout

Formats the logging event according to a flexible set of formatting flags.

log4net.Layout.RawTimeStampLayout

Extracts the timestamp from the logging event.

log4net.Layout.RawUtcTimeStampLayout

Extracts the timestamp from the logging event in Universal Time.

log4net.Layout.SimpleLayout

Formats the logging event very simply: [level] - [message]

log4net.Layout.XmlLayout

Formats the logging event as an XML element.

log4net.Layout.XmlLayoutSchemaLog4j

Formats the logging event as an XML element that complies with the log4j event dtd.

由于PatternLayout布局非常重要,下面具体再介绍:

下表是可以识别的转换模式名称:

转换模式名称

效果

a

等价于 appdomain

appdomain

用于输出当产生日志事件时的 AppDomain 名称。

aspnet-cache

指定 %aspnet-cache 时输出所有 cache 项;指定 %aspnet-cache{key} 时只输出 key 指定的项。

该模式对 Compact Framework or Client Profile 不可用。

aspnet-context

指定 %aspnet-context 时输出所有 context 项;指定 %aspnet-context 时只输出 key 指定的项。

该模式对 Compact Framework or Client Profile 不可用。

aspnet-request

指定 %aspnet-request 时输出所有请求参数的项;指定 %aspnet-request{key} 时只输出 key 指定的项。

该模式对 Compact Framework or Client Profile 不可用。

aspnet-session

指定 %aspnet-session 时输出所有 session 项;指定 %aspnet-session{key} 时只输出 key 指定的项。

该模式对 Compact Framework or Client Profile 不可用。

c

等价于 logger

C

等价于 type

class

等价于 type

d

等价于 date

date

以 local time zone 输出日志事件的日期。若输出 universal time 日期要使用
%utcdate
模式。日期格式也可以在模式后用大括号指定,例如,%date{HH:mm:ss,fff}%date{dd MMM yyyy HH:mm:ss,fff}。若没有指定日期格式,则将采用 ISO8601(Iso8601DateFormatter)。日期格式指示器跟 ToString 方法个式化日期时采用时间模式具有相同的语法。

推荐使用 log4net 日期格式化器,能得到更好的输出。通过指定字符串“ABSOLUTE”,“DATE”和“ISO8601”中的一个,分别表示AbsoluteTimeDateFormatter, DateTimeDateFormatterIso8601DateFormatter。例如,%date{ISO8601}%date{ABSOLUTE}

这写专用的日期格式化要比 ToString 更好。

exception

Used to output the exception passed in with the log message.

If an exception object is stored in the logging event it will be rendered into the pattern output with a trailing newline. If there is no exception then nothing will be output and no trailing newline will be appended. It is typical to put a newline before the exception and to have the exception as the last data in the pattern.

F

等价于 file

file

输出发生日志请求的文件名。

警告:产生调用位置信息相当慢。除非执行速度不是问题,否则要避免使用它。

See the note below on the availability of caller location information.

identity

输出当前活跃用户的用户名(Principal.Identity.Name)。

警告:产生调用位置信息相当慢。除非执行速度不是问题,否则要避免使用它。

l

等价于 location

L

等价于 line

location

Used to output location information of the caller which generated the logging event.

位置信息(location information)依赖 CLI 的实现,但通常是由调用方法的完整限定名(fully qualified name)组成,后面跟调用者源文件名和行号。

位置信息很有用。然而,它的产生相当慢。除非执行速度不是问题,否则要避免使用。

See the note below on the availability of caller location information.

level

输出日志事件的级别。

line

输出发生日志请求时的行号。

警告:产生调用位置信息相当慢。除非执行速度不是问题,否则要避免使用它。

See the note below on the availability of caller location information.

logger

输出日志事件的日志器。The logger conversion specifier can be optionally followed by precision specifier, that is a decimal constant in brackets.

If a precision specifier is given, then only the corresponding number of right most components of the logger name will be printed. By default the logger name is printed in full.

例如,若日志器名为 "a.b.c",模式为 %logger{2},将输出 "b.c".

m

等价于 message

M

等价于 method

message

输出与日志事件相关联的应用程序提供的信息,也就是你敲入的信息。

mdc

The MDC (old name for the ThreadContext.Properties) is now part of the combined event properties. This pattern is supported for compatibility but is equivalent to property.

method

输出发生日志请求时的方法名。

警告:产生调用位置信息相当慢。除非执行速度不是问题,否则要避免使用它。

See the note below on the availability of caller location information.

n

等价于 newline

newline

输出换行。换行是平台依赖的,各个平台可能不同。

This conversion pattern offers the same performance as using non-portable line separator strings such as "\n", or "\r\n". Thus, it is the preferred way of specifying a line separator.

ndc

输出与生产日志事件线程有关的 NDC(nested diagnostic context)。

p

等价于 level

P

等价于 property

properties

等价于 property

property

Used to output the an event specific property. The key to lookup must be specified within braces and directly following the pattern specifier, e.g. %property{user} would include the value from the property that is keyed by the string 'user'. Each property value that is to be included in the log must be specified separately. Properties are added to events by loggers or appenders. By default the
log4net:HostName
property is set to the name of machine on which the event was originally logged.

If no key is specified, e.g. %property then all the keys and their values are printed in a comma separated list.

The properties of an event are combined from a number of different contexts. These are listed below in the order in which they are searched.

the event propertiesThe event has Properties that can be set. These properties are specific to this event only.the thread propertiesThe Properties that are set on the current thread. These properties are shared by all events logged on this thread.the global propertiesThe Properties that are set globally. These properties are shared by all the threads in the AppDomain.
r

等价于 timestamp

stacktrace

Used to output the stack trace of the logging event The stack trace level specifier may be enclosed between braces. For example, %stacktrace{level}. If no stack trace level specifier is given then 1 is assumed

Output uses the format: type3.MethodCall3 > type2.MethodCall2 > type1.MethodCall1

This pattern is not available for Compact Framework assemblies.

stacktracedetail

Used to output the stack trace of the logging event The stack trace level specifier may be enclosed between braces. For example, %stacktracedetail{level}. If no stack trace level specifier is given then 1 is assumed

Output uses the format: type3.MethodCall3(type param,...) > type2.MethodCall2(type param,...) > type1.MethodCall1(type param,...)

This pattern is not available for Compact Framework assemblies.

t

等价于 thread

timestamp

Used to output the number of milliseconds elapsed since the start of the application until the creation of the logging event.

thread

输出产生日志事件的线程名称。如果没有可用的线程名称,则使用数字。

type

Used to output the fully qualified type name of the caller issuing the logging request. This conversion specifier can be optionally followed by precision specifier, that is a decimal constant in brackets.

If a precision specifier is given, then only the corresponding number of right most components of the class name will be printed. By default the class name is output in fully qualified form.

For example, for the class name "log4net.Layout.PatternLayout", the pattern %type{1} will output "PatternLayout".

警告:产生调用位置信息相当慢。除非执行速度不是问题,否则要避免使用它。

See the note below on the availability of caller location information.

u

等价于 identity

username

输出当前活跃用户的 WindowsIdentity。

警告:产生调用位置信息相当慢。除非执行速度不是问题,否则要避免使用它。

utcdate

Used to output the date of the logging event in universal time. The date conversion specifier may be followed by adate format specifier enclosed between braces. For example, %utcdate{HH:mm:ss,fff} or %utcdate{dd MMM yyyy HH:mm:ss,fff}. If no date format specifier is given then ISO8601 format is assumed (Iso8601DateFormatter).

The date format specifier admits the same syntax as the time pattern string of the ToString.

For better results it is recommended to use the log4net date formatters. These can be specified using one of the strings "ABSOLUTE", "DATE" and "ISO8601" for specifying AbsoluteTimeDateFormatter,DateTimeDateFormatter and respectively Iso8601DateFormatter. For example, %utcdate{ISO8601} or%utcdate{ABSOLUTE}.

These dedicated date formatters perform significantly better than ToString.

w

等价于 username

x

等价于 ndc

X

等价于 mdc

%

连续两个百分号 %% 会输出一个百分号。

格式修饰符

左边对齐

最小宽度

最大宽度

备注

%20logger

false

20



若日志器的名称小于 20 个字符,则左边补空格。

%-20logger

true

20



若日志器的名称小于 20 个字符,则右边补空格。

%.30logger

NA



30

若日志器的名称大于 30 个字符,则截取。

%20.30logger

false

20

30

若日志器的名称小于 20 个字符,则左边补空格。但是,若日志器名称的长度大于 30 个字符,则截取。

%-20.30logger

true

20

30

若日志器的名称小于 20 个字符,则右边补空格。但是,若日志器名称的长度大于 30 个字符,则截取。

相对应的XML格式如下:

<parameter>
<parameterName value="AppDomain"/>
<dbType value="String"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%appdomain"/>
</layout>
</parameter>
<parameter>
<parameterName value="AspnetCache"/>
<dbType value="String"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%aspnet-cache"/>
</layout>
</parameter>
<parameter>
<parameterName value="AspnetContext"/>
<dbType value="String"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%aspnet-context"/>
</layout>
</parameter>
<parameter>
<parameterName value="AspnetRequest"/>
<dbType value="String"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%aspnet-request"/>
</layout>
</parameter>
<parameter>
<parameterName value="AspnetSession"/>
<dbType value="String"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%aspnet-session"/>
</layout>
</parameter>
<parameter>
<parameterName value="Logger"/>
<dbType value="String"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%logger"/>
</layout>
</parameter>
<parameter>
<parameterName value="Date"/>
<dbType value="DateTime"/>
<layout type="log4net.Layout.RawTimeStampLayout"/>
</parameter>
<parameter>
<parameterName value="Identity"/>
<dbType value="String"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%identity"/>
</layout>
</parameter>
<parameter>
<parameterName value="Level"/>
<dbType value="String"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%level"/>
</layout>
</parameter>
<parameter>
<parameterName value="Location"/>
<dbType value="String"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%location"/>
</layout>
</parameter>
<parameter>
<parameterName value="Exception"/>
<dbType value="String"/>
<layout type="log4net.Layout.ExceptionLayout">
</layout>
</parameter>
<parameter>
<parameterName value="Message"/>
<dbType value="String"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%message"/>
</layout>
</parameter>
<parameter>
<parameterName value="Thread"/>
<dbType value="String"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%thread"/>
</layout>
</parameter>
<parameter>
<parameterName value="NDC"/>
<dbType value="String"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%ndc"/>
</layout>
</parameter>
<parameter>
<parameterName value="StackTraceDetail"/>
<dbType value="String"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%stacktracedetail{10}"/>
</layout>
</parameter>
<parameter>
<parameterName value="UserName"/>
<dbType value="String"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%username"/>
</layout>
</parameter>
<parameter>
<parameterName value="UTCDate"/>
<dbType value="DateTime"/>
<layout type="log4net.Layout.RawUtcTimeStampLayout"/>
</parameter>
</appender>


对象渲染(Object Renderers)

同样重要的是,log4net 会根据用户指定的标准呈现日志消息的内容。例如,如果你经常需要记录 Oranges,它是你项目中使用的一个对象类型,那么,你可以注册一个 OrangeRenderer,这样无论何时需要记录 Orange 就可以调用。

对象渲染按照类的层次结构。例如,假设橙子是水果,如果你注册一个 FruitRenderer,所有的水果,包括橙子,将按 FruitRenderer 渲染,除非你已经注册一个橙子的 OrangeRenderer。
对象渲染器必须实现 log4net.ObjectRenderer.IObjectRenderer 接口。
注意,DebugFormat、InfoFormat、WarnFormat、ErrorFormat 和 FatalFormat 方法不使用 ObjectRenderers。

使用部分心得

1、在输出到数据库里,一些数据库相关的DLL还是需要引用的。比如:输出到postgres 数据库,运行时当前目录下要有Npgsql.dll。

2、如果日志量非常的大,将数据直接输出到文本或者是数据库里,都会导致一个问题:减慢应用程序。如果太详细,它可能会导致滚动失败,插入数据库失败,导致整个运用程序挂掉。为了解决这个问题,我的解决方案是:



通过使用UdpAppender模式,将日志传输到指定的IP地址和端口下,日志监控中心进行监控操作,将接收到的日志进行分析,存入数据库里。

UdpAppender:

<?xml version="1.0"?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<log4net>
<appender name="UdpAppender" type="log4net.Appender.UdpAppender">
<remoteAddress value="192.168.100.107" />
<remotePort value="8080" />
<layout type="log4net.Layout.PatternLayout" value="%-5level$$%logger$$%message$$%username$$%date{yyyyMMdd HH:mm:ss fff}$$" />
</appender>
<root>
<level value="ALL" />
<appender-ref ref="ColoredConsoleAppender" />
<appender-ref ref="UdpAppender" />
</root>

<logger name="*">
<level value="ALL" />
<appender-ref ref="UdpAppender" />
</logger>
</log4net>
</configuration>


配置了"%-5level$$%logger$$%message$$%username$$%date{yyyyMMdd HH:mm:ss fff}$$",以$$分隔。

监控日志中心:

using System;
using System.Net;
using System.Net.Sockets;

namespace UdpAppender
{
class Program
{
static void Main(string[] args)
{
IPAddress address = IPAddress.Parse("192.168.100.107");
IPEndPoint remoteEndPoint = new IPEndPoint(address, 0);
UdpClient udpClient;
byte[] buffer;
string loggingEvent;

try
{
udpClient = new UdpClient(8080);

while (true)
{
buffer = udpClient.Receive(ref remoteEndPoint);
loggingEvent = System.Text.Encoding.Default.GetString(buffer);
Console.WriteLine(loggingEvent);
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
}


监控得到的数据效果:



这样,就成功的将应用程序的压力,转移到日志监控中心了。当然,我们还可以使用现成的第三方日志分析服务器,将日志监控中心里的日志,中转处理后,交给第三方日志分析服务器处理。

原文地址:http://logging.apache.org/log4net/release/config-examples.html

参考:

/article/4687203.html

/article/4964152.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: