Application configuration and introduction of Log4net in ASP.

Source: Internet
Author: User

Log4net in. NET in the status of a few words, this article focuses on configuration. Less introduction is used. Because online you can search hundreds of thousands of of articles on the Internet to tell you how to use it.
Installation of the words are not nonsense, very simple. Search for "log4net" installation in NuGet.

I. Configuration and configuration detailed

You can choose to configure it in Web. config or in a separate XML file or otherwise. I'm here to use a separate XML file configuration.

A. Configuring in Web. config

It is important to note that a section named log4net is added within the configsections node node under the Configuration node

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

This step is also required if you choose to save to an XML file. I created a log4net.xml file in the root directory. The content of this file is the content of the next B that is written directly from the <log4net> node.

B. Add andconfigsectionsSibling nodes<log4net>
<log4net> <appender name= "Rollinglogfileappender" type= "log4net.     Appender.rollingfileappender "> <!--log file name starts with forward slash/and backslash \ will create folder--<file value=" D:/logs/myexinfo.log "/>    <--<file value= "d:/logs/"/>--> <staticlogfilename value= "false"/> <!-using Unicode encoding-- <encoding value= "UTF-8"/> <!--append to file--<appendtofile value= "true"/> <!--mixed Use date and file size transform log FileName date [Date], file size [size], mix [Composite]-<rollingstyle value= "Composite"/> <!--date format--<date Pattern value= "YyyyMMdd". Log "/> <!--the maximum number of log files that are generated, and only the latest n is retained.    SetPoint value= "-1" for unlimited files--<maxsizerollbackups value= "a"/> <!--does not record the log exclusively because deployment to the server encounters file name accumulation ....--> <lockingmodel type= "log4net.         Appender.fileappender+minimallock "/> <!--maximum file size--<maximumfilesize value=" 5MB "/> <!--filter record level <filter type= "log4net. Filter.levelrangefilter "> <levelmin valUe= "ERROR"/> <levelmax value= "FATAL"/> </filter>-<!--This is the default log content format <layout type= "log4net. Layout.patternlayout "> <conversionpattern value="%d [%t]%-5p%m-[%f:%l]%n]/> </layout&gt    ; --<!-here inherits the Log4net. Layout.patternlayout a custom layout, Tglog.expandlayout2 is a namespace. %property{operator},%property{action} is custom output--<layout type= "Tglog.expandlayout2.reflectionlayout,tglog" > <param name= "Conversionpattern" value= "Record time:%date thread Id:[%thread] Log level:%-5level record class:%logger operator Id:%prope  Rty{operator} operation type:%property{action}%n current machine name:%property%n current machine name and login User:%username%n record Location:%location%n Message Description:%property{message}%n exception:%exception%n message:%message%newline%n%n "/> </layout> </appender> <root&    Gt  <level value= "All" ></level> <appender-ref ref= "Rollinglogfileappender" ></appender-ref> </root></log4net>

The top is some basic configuration. You can see the primary node configuration <appender> nodes and <root> node.

The <appender> node can have 0 or more of this node to define the output of the log, that is, what kind of media the log is written to. This class can be customized and needs to be from log4net. Appender.appenderskeleton class inheritance.
Its Name property is guaranteed to be unique. It has more type types. Want to know can expand to see.

Adonetappender logging to the database. SQL and stored procedures can be used in two ways. Ansicolorterminalappender highlight the log output to the ANSI terminal. Aspnettraceappender can view logged logs in the same way as trace in ASP. Bufferingforwardingappender Cache log events before outputting to child appenders. Consoleappender the log output to the application console. Eventlogappender writes the log to Windows Event log. Fileappender the log output to a file. Forwardingappender Send log events to child appenders. Localsyslogappender writes the log to the local syslog service (only for UNIX environments). Memoryappender the log to the memory buffer. Netsendappender the log output to the Windows Messenger Service. These log messages are displayed in the User Terminal's dialog box. Outputdebugstringappender output the log to Debuger, and if the program does not debuger, it outputs to the system Debuger. If the system Debuger is also unavailable, the message is ignored. Remotesyslogappender logs are written to the remote Syslog service via the UDP network protocol. Remotingappender writes logs to the remote receive end through. NET Remoting. Rollingfileappender writes the log to a file in the form of a rollback file. Smtpappender writes the log to the message. Smtppickupdirappender the messages into a directory as files, and SMTP proxies such as the IIS SMTP agent can read or send them. The Telnetappender client accepts log events via Telnet. Traceappender writes the log to the. NET trace System. Udpappender sends the log to a remote host in the form of a non-connected UDP datagram or broadcasts it in udpclient form. Source: http://www.cnblogs.com/lzrabbit/archive/2012/03/23/2413180.html

<APPENDER-REF> indicates the reference to the Appender. There can be multiple in the root node, <appender> can also be used under the node but not all types are supported! As far as I'm concerned,  rollingfileappender and Fileappender do not support  
Other nodes are written with comments easy to understand   Note the above configuration I'm all listed here. Direct replication may not be able to write properly!
The more special nodes are filter and layout
<FILTER> kind:     

Filters can be used to filter out the contents of the Appender output. Filters typically have the following: Denyallfilter prevents all log events from being logged levelmatchfilter only log events of a specified level are logged Levelrangefilter The log level event in the specified range is recorded loggermatchfilter matches the logger name only if the PropertyFilter message matches the specified property value, the Stringmathfilter message matches the specified string before it is logged

<layout> to control the output format of the Appender, there can only be one node. There are several types of more commonly used types are patternlayout, as the name implies that you can use a pattern to define the display content. In the front of the configuration has been written in detail .
It is important to note that%property{operator} This thing is a custom, and it's not necessary to mention it later.
There is also a <logger> node that is not described, and this node is similar to the <root> node. Inherits from the <root> node. It is important to note that the level issue may overwrite the <root> configuration.
The Name property is guaranteed to be unique . It can be accessed directly through the name in the code.

XML:     <logger name= "Exceptioninfo" >      <level value= "ERROR"/>      <appender-ref ref= " Exceptioninfo "/>    </logger>c#:log4net. Logmanager.getlogger ("Exceptioninfos"). Error ("This is an exception");

The Logmanager class is used to manage log, where the specified Exceptioninfoslogger is obtained and an error log is logged.

Configuration it's almost there. The last and most important step is to enable the configuration.
Add code to the startup event of the Global.asax file. This sentence must be there otherwise you will find that your configuration is correct but you cannot log:

Xmlconfigurator.configure (); or xmlconfigurator.configureandwatch (); Configuration file stream with parameter FileInfo type

Configure has several overloaded methods:

  
It can be seen from the parameters that a remote load profile can be placed directly into an XML class document to pass a custom XML file stream;
The custom Log4net.xml file was mentioned at the outset. If we're going to load it then it can be loaded like this:

Xmlconfigurator.configureandwatch (New System.IO.FileInfo (Server.MapPath ("~/log4net.xml"));

The method with watch indicates that the file is monitored and reloaded if there are any changes.
There may be questions at this time. Do not want to write so much code, through the configuration implementation can be the answer is OK.
In the code, write this:

Xmlconfigurator.configure ();

Add the code (note the file path) to the AssemblyInfo.cs in the bottom of the project, and the personal preference is to use this method:

[Assembly:log4net. Config.xmlconfigurator (configfile = "Log4net.xml", Watch = True)]

If you don't know where this file is, look at the picture:
  

Two. Dynamic configuration of Storage folders and formatted file names

Dynamic display of filenames as a date, several types are different

A.appender type is Fileappender
<appender name= "Warninfo" type= "log4net. Appender.fileappender ">     <file type=" log4net. Util.patternstring "value="/logs/%date{yyyy}/%date{yyyy MM dd hh_mm_ss}-warninfos.txt "  />      <param Name = "Lockingmodel"  type= "log4net. Appender.fileappender+minimallock "/>      <layout type=" log4net. Layout.patternlayout ">        <conversionpattern value="%d [%t]%-5p%m-[%f:%l]%n]/>      </layout>< /appender>

The configuration to note here is that the file node uses log4net. Util.patternstring Type This allows you to use pattern matching directly in value.
It has been mentioned in front that both the forward slash and the backslash are considered to be the delimiter of the folder, please note this when using.
Date format also note that in C # is accustomed to the form of YYYY-MM-DD HH:mm:ss here is not the case because of Windows system : as a disk delimiter separator can not be used as a filename!
If your folder is created without log file generation you might want to check to see if you have characters that are not file names.
In addition HH for 24-hour system (such as one o'clock in the afternoon will show 13:00 ) hh for 12-hour system (such as: One o'clock in the afternoon will show 1:00 points )
All right, let's run it. Look at the result of the build:

XML:  <logger name= "Warninfos" >    <level value= "All" ></level>    <appender-ref ref= " Warninfo "></appender-ref>  </logger>c#:logmanager.getlogger (" Warninfos "). Warn ("This is a warning");

The results are as follows:

The logs folder was created automatically under the D drive we specified and a folder with the current year name was created. The file name is also generated in the format we want.

B. Appender of type Rollingfileappender

This type has two ways of modifying a modification method that uses the top Fileappender (rollingfileappender inherits from Fileappender
Another is the configuration datepattern node with the following code:

 <appender name=" Requestinfo "type=" log4net. Appender.rollingfileappender "> <file value=" d:/logs "/> <encoding value=" UTF-8 "/> <append ToFile value= "true"/> <rollingstyle value= "Date"/> <!--do not use static filenames--<staticlogfilename Val Ue= "false"/> <maxsizerollbackups value= "-1"/> <maximumfilesize value= "5MB"/> <param nam E= "Lockingmodel" type= "log4net. Appender.fileappender+minimallock "/> <layout type=" log4net. Layout.patternlayout "> <conversionpattern value="%newline%n record time:%date%n thread Id:[%thread]%n log level:%-5level%n out Wrong class:%logger property: [%property{ndc}]-%n error description:%message%newline%n "/> </layout> <datepattern value=" /yyyy/yyyymm/yyyymmdd/' request.txt ' "/> </appender> 

Here in fact the main configuration Datepattern,staticlogfilename,rollingstyle three nodes
Datepattern   the mode of the configuration file name. Note that there is no need to write%date this placeholder for direct write format line
                    back '-request.tex T ' is to indicate that this place does not enable pattern matching also can be used &quot; Distinguish
staticlogfilename   whether static file names are enabled True/false
Span style= "FONT-SIZE:16PX; Color: #0000ff; " >rollingstyle   scroll record type Date/size/composite
Write a log again to see the format we need d:logs\\2016\\201606\\20160625\\ Request.txt file.
The dynamic configuration file name here is almost there. But what if there is a need to change the file's storage path to dynamic? For example, read from other configuration files, read from the database, or otherwise. Do not rule out the existence of this requirement. The
solution is as follows:

C#://global.asax file        protected void Application_Start ()        {            //log4net            log4net. globalcontext.properties["Dynamicpath"] = @ "D:\MyLogs\";            Xmlconfigurator.configure ();        } Xml://appender  Rollingfileappender and Fileappender can use the Type<file type= "log4net of note file. Util.patternstring "value="%property{dynamicpath} "/>

This piece of code is simple. %property{dynamicpath} This is the display of the properties that we have customized. The top configuration file is described in.
Use a simple curly brace with our pre-defined variable name.
The Properties property that is set in the code. This is where you can figure out how to do it. Read from somewhere else and put it in.
There is also a way to get all appender nodes to achieve their goal by modifying their result values in code as follows:

        protected void Application_Start ()        {            //log4net            //log4net. globalcontext.properties["MyPath"] = @ "D:\MyLogs\";            Xmlconfigurator.configure ();            var repository = log4net. Logmanager.getrepository ();            var appenders = repository. Getappenders ();            var Targetapp = appenders. First (x = X.name = = "Exceptioninfo") as Rollingfileappender;            Change path            targetapp.file = @ "D:\MyLogs\";           Manual replacement of the result           targetApp.DatePattern.Replace ("'. txt '", "'-excinfo.txt '");           Activation has been set by the property            targetapp.activateoptions ();        }

This way you can control multiple properties. The properties that support the Set method can be modified as long as they are supported.
If you want more granular operations, you can customize the Appender implementation.

  

Reference article:
1:apache log4net Manual
2:log4net generates log files to different places according to the different logger names.
3:log4net Configuration Detailed
4:log4net generate multiple files, file name additive solution
5: (Turn) Very perfect log4net detailed description lazy fat Bunny

  

Application configuration and introduction of Log4net in ASP.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.