log4net.Layout.PatternLayout

原文地址

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

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

注意:

The goal of this class is to Format a LoggingEvent as a string. The results depend on the conversion pattern.

The conversion pattern is closely related to the conversion pattern of the printf function in C. A conversion pattern is composed of literal text and format control expressions called conversion specifiers.

You are free to insert any literal text within the conversion pattern.

Each conversion specifier starts with a percent sign (%) and is followed by optional format modifiers and a conversion pattern name. The conversion pattern name specifies the type of data, e.g. logger, level, date, thread name. The format modifiers control such things as field width, padding, left and right justification. The following is a simple example.

转换模式为 "%-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; }

Note that there is no explicit separator between text and conversion specifiers. The pattern parser knows when it has reached the end of a conversion specifier when it reads a conversion character. In the example above the conversion specifier %-5level means the level of the logging event should be left justified to a width of five characters.

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


转换模式名称


效果


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 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 properties
The event has Properties that can be set. These properties are specific to this event only.
the thread properties
The Properties that are set on the current thread. These properties are shared by all events logged on this thread.
the global properties
The 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 a date 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


%


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

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 the left justification flag which is just the minus (-) character. Then comes the optional minimum field width modifier. 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 the maximum field width modifier 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 the beginning of 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


Left pad with spaces if the logger name is less than 20 characters long.


%-20logger

true


20



Right pad with spaces if the logger name is less than 20 characters long.


%.30logger


NA


30


Truncate from the beginning if the logger name is longer than 30 characters.


%20.30logger


false

20


30


Left pad with spaces if the logger name is shorter than 20 characters. However, if logger name is longer than 30 characters, then truncate from the beginning.


%-20.30logger


true

20

30


Right pad with spaces if the logger name is shorter than 20 characters. However, if logger name is longer than 30 characters, then truncate from the beginning.

Note about caller location information.

The following patterns %type %file %line %method %location %class %C %F %L %l %M all generate caller location information. Location information uses the System.Diagnostics.StackTrace class to generate a call stack. The caller‘s information is then extracted from this stack.

CAUTION

The System.Diagnostics.StackTrace class is not supported on the .NET Compact Framework 1.0 therefore caller location information is not available on that framework.

CAUTION

The System.Diagnostics.StackTrace class 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 specific PatternLayout instance using the AddConverter method.

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; }

时间: 2024-08-04 15:10:07

log4net.Layout.PatternLayout的相关文章

log4net 自定义Layout日志字段

最近在使用log4net的时候有一个简单的需求,就是自定义个格式化输出符.这个输出符是专门用来帮我记录下业务ID.业务类型的.比如,"businessID:328593,businessType: orderID".类似这样的输出日志.这些日志会被elk agent提取送到日志中心ES中,用来进行辅助排障. 简单的看了下log4net的PatternLayout和PatternConverter两个对象的作用,实现起来也是非常方便的.log4net有一组global的PatternLa

log4net VS2012 日志layout自定义,error日志和info日志分别记录到不同文件中

打开VS中“工具”=>“NuGet程序包管理器”=>“管理解决方案的NuGet程序包”菜单 在“管理NuGet程序包”窗口中,搜索log4net,并安装 有时候,我们在日志中需要记录一些业务数据,如operator等信息,我们新建一个类WebMethodLog,来存放log里面需要用到的信息 public class WebMethodLog { public string operatorNo{get;set;} public string operatorName { get; set;

log4net 使用总结- (2)在ASP.NET MVC 中使用

log4net在ASP.NET MVC中的配置,还有一种配置方式,即不在web.config中,而是单独新建一个log4net.config 在根目录下 第一.引用log4net.dll 第二.在站点根目录下增加log4net.config <?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="

(转)非常完善的Log4net详细说明

转自:http://www.cnblogs.com/zhangchenliang/p/4546352.htmlhttp://www.cnblogs.com/zhangchenliang/p/4546352.html (转)非常完善的Log4net详细说明 1.概述 log4net是.Net下一个非常优秀的开源日志记录组件.log4net记录日志的功能非常强大.它可以将日志分不同的等级,以不同的格式,输出到不同的媒介.本文主要是介绍如何在Visual Studio2008中使用log4net快速创

Log4Net 之初体验

今天试了一下关于日志的一个插件--Log4Net 关于这个插件就不过多描述了,有很多人用,也挺好用比较方便,所以在此记录下使用过程. 一.建一个mvc 空网站 名字叫 Log4NetTest 二.下载log4net.dll 并添加引用,也可以用NuGet在线安装 三.在Models  文件夹下建立MyErrorAttribute 大概就是把所有的错误丢进队列里面去,并且继承 HandleErrorAttribute 代码就如下: using System; using System.Collec

log4net 既要按日期分割日志文件,又要按文件大小分割。

<appender name="DebugAppender" type="log4net.Appender.RollingFileAppender"> <file value="log\debug\"/> <appendToFile value="true" /> <rollingStyle value="Composite" /> <datePatte

log4net使用简介

说明:本程序演示如何利用log4net记录程序日志信息.log4net是一个功能著名的开源日志记录组件.利用log4net可以方便地将日志信息记录到文件.控制台.Windows事件日志和数据库(包括MS SQL Server, Access, Oracle9i,Oracle8i,DB2,SQLite)中.并且我们还可以记载控制要记载的日志级别,可以记载的日志类别包括:FATAL(致命错误).ERROR(一般错误).WARN(警告).INFO(一般信息).DEBUG(调试信息).要想获取最新版本的

Log4Net使用详解

说明自从上次在2008年在博客上发表过有关log4net的用法介绍文章之后(网址:http://blog.csdn.net/zhoufoxcn/archive/2008/03/26/2220533.aspx),有不少朋友在博文下留言询问一些细节,现在就一些比较普遍的问题做一些稍微深入的解答,希望大家满意.首先说明一点的是,log4net解决的问题是提供一个记录日志的框架,它提供了向多种目标写入的实现,比如利用log4net可以方便地将日志信息记录到文件.控制台.Windows事件日志和数据库(包

Log4Net 在多层项目中的使用小记

原文地址:http://www.cnblogs.com/zdh8675/p/3645556.html 这几天刚好在调整一个项目,把一些自己不是很清楚的东西先试验一下,这篇文章主要是对我在项目中需要使用Log4Net的一些记录.网上有很多相关的教程,但是各有各的说法,我结合我自己这个项目的需要,首先,项目是分多层的,假如每一层都需要加入日志记录,那该怎么办呢,下面是我的一些操作步骤,记录出来和大家分享一下,不足之处希望大家多拍板砖多多指教. 这个截图是我的当前项目的层次结构,首先在Common层先