log4net 的使用

常规的配置如下

先在web.config中的<configuration>节点下添加如下配置:

<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
</configSections>

然后配置log4net节点

代码
<log4net debug="false">
<appender name="LogFileAppender" type="log4net.Appender.FileAppender">
<param name="File" value="c:\Applog.txt"/>
<param name="datePattern" value="yyyy-MM-dd HH:mm"/>
<param name="AppendToFile" value="true"/>
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%d [%t] %-5p %c [%x] - %m%n"/>
</layout>
</appender>
<appender name="HttpTraceAppender" type="log4net.Appender.ASPNetTraceAppender">
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%d [%t] %-5p %c [%x] - %m%n"/>
</layout>
</appender>
<appender name="EventLogAppender" type="log4net.Appender.EventLogAppender">
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%d [%t] %-5p %c [%x] - %m%n"/>
</layout>
</appender>
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<param name="File" value="C:\Log.txt"/>
<param name="AppendToFile" value="true"/>
<param name="MaxSizeRollBackups" value="10"/>
<param name="MaximumFileSize" value="5MB"/>
<param name="RollingStyle" value="Size"/>
<param name="StaticLogFileName" value="true"/>
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%d [%t] %-5p %c [%x] - %m%n"/>
</layout>
</appender>
<root>
<level value="DEBUG"/>
<appender-ref ref="LogFileAppender"/>
</root>
</log4net>

然后在代码中加入

   log4net.ILog log = LogManager.GetLogger("MyLogger");

        log.Debug("Here is some debug info。。。");

如果就这样,你运行程序会发现没哟日志文件生成,那是因为您还未为log4net绑定配置文件。

对于web application则要在global.asax 的 Application_Start()方法中加上

log4net.Config.XmlConfigurator.Configure();或者在global.asax中加上[assembly: log4net.Config.XmlConfigurator()]

对于windows application或者console application 则要在 AssemblyInfo.cs 中加上

[assembly: log4net.Config.XmlConfigurator()]

对于log4net的配置,还有另外一种配置方式--单独的配置文件。

global.asax(web app)中,或者assemblyinfo.cs(winform)中加上[assembly: log4net.Config.XmlConfigurator(ConfigFileExtension="log4net", Watch=true)]

其中ConfigFileExtension 表示 配置文件的扩展名(注意:文件名必须与项目名称一致比如 QuartzTest.dll.log4net)

配置文件内容如下:

代码
<?xml version="1.0" encoding="utf-8" ?>

<!-- This section contains the log4net configuration settings -->
<log4net>

<!-- Define some output appenders -->

<appender name="LogFileAppender" type="log4net.Appender.FileAppender">
<file value="simple-module-log.txt"/>
<appendToFile value="true"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%ndc] - %message%newline"/>
</layout>
</appender>

<!-- Setup the root category, add the appenders and set the default level -->

<root>
<level value="DEBUG"/>
<appender-ref ref="LogFileAppender"/>
</root>

</log4net>

 ado net appender config section

  <appender name="ADONetAppender" type="log4net.Appender.ADONetAppender">
       <bufferSize value="10"/>
       <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
       <connectionString value="server=.\sqlexpress;database=DbLog;user id=sa;password=yuanjinzhou"/>
       <commandText value="INSERT INTO Log ([Date],[Thread],[Level],[Logger],[Message],[Exception]) VALUES (@log_date, @thread, @log_level, @logger, @message, @exception)"/>
       <parameter>
         <parameterName value="@log_date"/>
         <dbType value="DateTime"/>
         <layout type="log4net.Layout.RawTimeStampLayout"/>
       </parameter>
       <parameter>
         <parameterName value="@thread"/>
         <dbType value="String"/>
         <size value="255"/>
         <layout type="log4net.Layout.PatternLayout">
           <conversionPattern value="%thread"/>
         </layout>
       </parameter>
       <parameter>
         <parameterName value="@log_level"/>
         <dbType value="String"/>
         <size value="50"/>
         <layout type="log4net.Layout.PatternLayout">
           <conversionPattern value="%level"/>
         </layout>
       </parameter>
       <parameter>
         <parameterName value="@logger"/>
         <dbType value="String"/>
         <size value="255"/>
         <layout type="log4net.Layout.PatternLayout">
           <conversionPattern value="%logger"/>
         </layout>
       </parameter>
       <parameter>
         <parameterName value="@message"/>
         <dbType value="String"/>
         <size value="4000"/>
         <layout type="log4net.Layout.PatternLayout">
           <conversionPattern value="%message"/>
         </layout>
       </parameter>
       <parameter>
         <parameterName value="@exception"/>
         <dbType value="String"/>
         <size value="2000"/>
         <layout type="log4net.Layout.ExceptionLayout"/>
       </parameter>
     </appender>

 Conversion Pattern

Conversion Pattern NameEffect
a Equivalent to appdomain
appdomain Used to output the friendly name of the AppDomain where the logging event was generated.
aspnet-cache

Used to output all cache items in the case of %aspnet-cache or just one named item if used as %aspnet-cache{key}

This pattern is not available for Compact Framework or Client Profile assemblies.

aspnet-context

Used to output all context items in the case of %aspnet-context or just one named item if used as %aspnet-context{key}

This pattern is not available for Compact Framework or Client Profile assemblies.

aspnet-request

Used to output all request parameters in the case of %aspnet-request or just one named param if used as %aspnet-request{key}

This pattern is not available for Compact Framework or Client Profile assemblies.

aspnet-session

Used to output all session items in the case of %aspnet-session or just one named item if used as %aspnet-session{key}

This pattern is not available for Compact Framework or Client Profile assemblies.

c Equivalent to logger
C Equivalent to type
class Equivalent to type
d Equivalent to date
date

Used to output the date of the logging event in the local time zone. To output the date in universal time use the %utcdate pattern. The date conversion specifier may be followed by a date format specifier enclosed between braces. For example, %date{HH:mm:ss,fff} or %date{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, %date{ISO8601} or %date{ABSOLUTE}.

These dedicated date formatters perform significantly better than 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 Equivalent to file
file

Used to output the file name where the logging request was issued.

WARNING Generating caller location information is extremely slow. Its use should be avoided unless execution speed is not an issue.

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

identity

Used to output the user name for the currently active user (Principal.Identity.Name).

WARNING Generating caller information is extremely slow. Its use should be avoided unless execution speed is not an issue.

l Equivalent to location
L Equivalent to line
location

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

The location information depends on the CLI implementation but usually consists of the fully qualified name of the calling method followed by the callers source the file name and line number between parentheses.

The location information can be very useful. However, its generation is extremely slow. Its use should be avoided unless execution speed is not an issue.

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

level

Used to output the level of the logging event.

line

Used to output the line number from where the logging request was issued.

WARNING Generating caller location information is extremely slow. Its use should be avoided unless execution speed is not an issue.

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

logger

Used to output the logger of the logging event. 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.

For example, for the logger name "a.b.c" the pattern %logger{2} will output "b.c".

m Equivalent to message
M Equivalent to method
message

Used to output the application supplied message associated with the logging event.

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

Used to output the method name where the logging request was issued.

WARNING Generating caller location information is extremely slow. Its use should be avoided unless execution speed is not an issue.

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

n Equivalent to newline
newline

Outputs the platform dependent line separator character or characters.

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

Used to output the NDC (nested diagnostic context) associated with the thread that generated the logging event.

p Equivalent to level
P Equivalent to property
properties Equivalent to 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 Equivalent to 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 Equivalent to thread
timestamp

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

thread

Used to output the name of the thread that generated the logging event. Uses the thread number if no name is available.

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".

WARNING Generating the caller class information is slow. Thus, its use should be avoided unless execution speed is not an issue.

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

u Equivalent to identity
username

Used to output the WindowsIdentity for the currently active user.

WARNING Generating caller WindowsIdentity information is extremely slow. Its use should be avoided unless execution speed is not an issue.

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 Equivalent to username
x Equivalent to ndc
X Equivalent to mdc
%

The sequence %% outputs a single percent sign.

 文本格式配置

Format modifierleft justifyminimum widthmaximum widthcomment
%20logger false 20 none

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

%-20logger true 20 none

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

%.30logger NA none 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.

原文地址:https://www.cnblogs.com/philzhou/p/1923441.html