分享
 
 
 

log4net.Layout.PatternLayout用conversion模式格式化日志事件【翻译】

王朝学院·作者佚名  2016-08-27
窄屏简体版  字體: |||超大  

原文地址

log4net.Layout.PatternLayout,是一个灵活的布局,配置模式字符串。

线程安全。该类型的 Public static 成员对多线程操作是安全的。实例成员不保证线程安全。

注意:

该类的目标是把 LoggingEvent 格式化成字符串。格式化的结果依赖于conversion模式。

conversion模式与 C 语言的PRintf 函数很像。conversion 模式是由文字文本和格式控制表达式(称为转换指定符)组成。

你可以自由地将任何文字文本插入到转换模式中。

每个转换指定符(conversion specifier)以百分号(%)开始,后面跟一个可选的格式修饰符(format modifiers)和转换模式(conversion pattern)名称。 转换模式名称指定数据的类型,例如,日志器(logger)、级别(level)、日期(date)、线程名(thread name)。格式修饰符控制诸如,字段宽度,填充,左边和右边对齐等事情。

下面是一个简单的例子:

转换模式为"%-5level [%thread]: %message%newline",并假设 log4net 环境设置为PatternLayout,那么,下面语句:

[C#]

ILog log = LogManager.GetLogger(typeof(TestApp));

log.Debug("Message 1");

log.Warn("Message 2");

.csharpcode, .csharpcode pre

{

font-size: small;

color: black;

font-family: consolas, "Courier New", courier, monospace;

background-color: #ffffff;

/*white-space: pre;*/

}

.csharpcode pre { margin: 0em; }

.csharpcode .rem { color: #008000; }

.csharpcode .kwrd { color: #0000ff; }

.csharpcode .str { color: #006080; }

.csharpcode .op { color: #0000c0; }

.csharpcode .preproc { color: #cc6633; }

.csharpcode .asp{ background-color: #ffff00; }

.csharpcode .html { color: #800000; }

.csharpcode .attr { color: #ff0000; }

.csharpcode .alt

{

background-color: #f4f4f4;

width: 100%;

margin: 0em;

}

.csharpcode .lnum { color: #606060; }将输出,

DEBUG [main]: Message 1

WARN [main]: Message 2

.csharpcode, .csharpcode pre

{

font-size: small;

color: black;

font-family: consolas, "Courier New", courier, monospace;

background-color: #ffffff;

/*white-space: pre;*/

}

.csharpcode pre { margin: 0em; }

.csharpcode .rem { color: #008000; }

.csharpcode .kwrd { color: #0000ff; }

.csharpcode .str { color: #006080; }

.csharpcode .op { color: #0000c0; }

.csharpcode .preproc { color: #cc6633; }

.csharpcode .asp { background-color: #ffff00; }

.csharpcode .html { color: #800000; }

.csharpcode .attr { color: #ff0000; }

.csharpcode .alt

{

background-color: #f4f4f4;

width: 100%;

margin: 0em;

}

.csharpcode .lnum { color: #606060; }需要注意的是,文字和转换指示器之间没有明确的分隔符。当模式解析器读取一个转换字符时,它知道何时已经达到了一个转换指示器的末尾。上面的例子,在转换指示符%-5level含义是,日志事件的级别占 5 个字符的宽度,并且左边对齐。

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

转换模式名称

效果

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, DateTimeDateFormatter 和 Iso8601DateFormatter。例如,%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 byprecision 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 toproperty.

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 thelog4net:HostNameproperty is set to the name of machine on which the event was originally logged.

If no key is specified, e.g.%propertythen 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 theapplicationuntil 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 byprecision 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 specifierenclosed 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 theToString.

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 specifyingAbsoluteTimeDateFormatter,DateTimeDateFormatterand respectivelyIso8601DateFormatter. For example,%utcdate{ISO8601}or%utcdate{ABSOLUTE}.

These dedicated date formatters perform significantly better thanToString.

w

等价于username

x

等价于ndc

X

等价于mdc

%

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

The single letter patterns are deprecated in favor of the longer more descriptive pattern names.

By default the relevant information is output as is. However, with the aid of format modifiers it is possible to change the minimum field width, the maximum field width and justification.

The optional format modifier is placed between the percent sign and the conversion pattern name.

The first optional format modifier is theleft justification flagwhich is just the minus (-) character. Then comes the optionalminimum field widthmodifier. This is a decimal constant that represents the minimum number of characters to output. If the data item requires fewer characters, it is padded on either the left or the right until the minimum width is reached. The default is to pad on the left (right justify) but you can specify right padding with the left justification flag. The padding character is space. If the data item is larger than the minimum field width, the field is expanded to accommodate the data. The value is never truncated.

This behavior can be changed using themaximum field widthmodifier which is designated by a period followed by a decimal constant. If the data item is longer than the maximum field, then the extra characters are removed from thebeginningof the data item and not from the end. For example, it the maximum field width is eight and the data item is ten characters long, then the first two characters of the data item are dropped. This behavior deviates from the printf function in C where truncation is done from the end.

Below are various format modifier examples for the logger conversion specifier.

格式修饰符

左边对齐

最小宽度

最大宽度

备注

%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 个字符,则截取。

关于调用者位置信息(caller location information)

模式%type、%file、%line、%method、%location、%class、%C、%F、%L、%l 和 %M都会产生调用者位置信息。位置信息使用System.Diagnostics.StackTrace类来产生调用堆栈。调用者信息是从这个堆栈提取的。

注意

.NET Compact Framework 1.0 不支持System.Diagnostics.StackTrace类,因此,调用者位置信息也是不可用的。

注意

TheSystem.Diagnostics.StackTraceclass has this to say about Release builds:

"StackTrace information will be most informative with Debug build configurations. By default, Debug builds include debug symbols, while Release builds do not. The debug symbols contain most of the file, method name, line number, and column information used in constructing StackFrame and StackTrace objects. StackTrace might not report as many method calls as expected, due to code transformations that occur during optimization."

This means that in a Release build the caller information may be incomplete or may not exist at all! Therefore caller location information cannot be relied upon in a Release build.

Additional pattern converters may be registered with a specificPatternLayoutinstance using theAddConvertermethod.

This is a more detailed pattern.

%timestamp [%thread] %level %logger %ndc - %message%newline

.csharpcode, .csharpcode pre

{

font-size: small;

color: black;

font-family: consolas, "Courier New", courier, monospace;

background-color: #ffffff;

/*white-space: pre;*/

}

.csharpcode pre { margin: 0em; }

.csharpcode .rem { color: #008000; }

.csharpcode .kwrd { color: #0000ff; }

.csharpcode .str { color: #006080; }

.csharpcode .op { color: #0000c0; }

.csharpcode .preproc { color: #cc6633; }

.csharpcode .asp { background-color: #ffff00; }

.csharpcode .html { color: #800000; }

.csharpcode .attr { color: #ff0000; }

.csharpcode .alt

{

background-color: #f4f4f4;

width: 100%;

margin: 0em;

}

.csharpcode .lnum { color: #606060; }A similar pattern except that the relative time is right padded if less than 6 digits, thread name is right padded if less than 15 characters and truncated if longer and the logger name is left padded if shorter than 30 characters and truncated if longer.

%-6timestamp [%15.15thread] %-5level %30.30logger %ndc - %message%newline

.csharpcode, .csharpcode pre

{

font-size: small;

color: black;

font-family: consolas, "Courier New", courier, monospace;

background-color: #ffffff;

/*white-space: pre;*/

}

.csharpcode pre { margin: 0em; }

.csharpcode .rem { color: #008000; }

.csharpcode .kwrd { color: #0000ff; }

.csharpcode .str { color: #006080; }

.csharpcode .op { color: #0000c0; }

.csharpcode .preproc { color: #cc6633; }

.csharpcode .asp { background-color: #ffff00; }

.csharpcode .html { color: #800000; }

.csharpcode .attr { color: #ff0000; }

.csharpcode .alt

{

background-color: #f4f4f4;

width: 100%;

margin: 0em;

}

.csharpcode .lnum { color: #606060; }

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
2023年上半年GDP全球前十五强
 百态   2023-10-24
美众议院议长启动对拜登的弹劾调查
 百态   2023-09-13
上海、济南、武汉等多地出现不明坠落物
 探索   2023-09-06
印度或要将国名改为“巴拉特”
 百态   2023-09-06
男子为女友送行,买票不登机被捕
 百态   2023-08-20
手机地震预警功能怎么开?
 干货   2023-08-06
女子4年卖2套房花700多万做美容:不但没变美脸,面部还出现变形
 百态   2023-08-04
住户一楼被水淹 还冲来8头猪
 百态   2023-07-31
女子体内爬出大量瓜子状活虫
 百态   2023-07-25
地球连续35年收到神秘规律性信号,网友:不要回答!
 探索   2023-07-21
全球镓价格本周大涨27%
 探索   2023-07-09
钱都流向了那些不缺钱的人,苦都留给了能吃苦的人
 探索   2023-07-02
倩女手游刀客魅者强控制(强混乱强眩晕强睡眠)和对应控制抗性的关系
 百态   2020-08-20
美国5月9日最新疫情:美国确诊人数突破131万
 百态   2020-05-09
荷兰政府宣布将集体辞职
 干货   2020-04-30
倩女幽魂手游师徒任务情义春秋猜成语答案逍遥观:鹏程万里
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案神机营:射石饮羽
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案昆仑山:拔刀相助
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案天工阁:鬼斧神工
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案丝路古道:单枪匹马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:与虎谋皮
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:李代桃僵
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:指鹿为马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:小鸟依人
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:千金买邻
 干货   2019-11-12
 
推荐阅读
 
 
 
>>返回首頁<<
 
靜靜地坐在廢墟上,四周的荒凉一望無際,忽然覺得,淒涼也很美
© 2005- 王朝網路 版權所有