[. Net MVC] Using the Log4net log framework

Source: Internet
Author: User
Tags syslog log4net

Project: Background Management Platform

Significance: In the project development, it is proposed to increase the log function, to record the key operation and error information in the program operation, which has great significance to the debugging after the program deployment.

Note: This article is not original, but the online collection of information to be integrated for future inquiries.

One, the fastest steps to get started

1. Add log4net with NuGet

2. Add a node to the Web. config in the project root directory. Add a reference to log4net under the <configsections> node,

< configsections >  <  name= "log4net"  type= "Log4net". Config.log4netconfigurationsectionhandler,log4net "/></configsections  >

Add <log4net> nodes, configure Log4net,

<log4net>  <Appendername= "Rollingfile"type= "log4net." Appender.rollingfileappender ">    <filevalue= "C:\Temp\log4net.log" />    <Appendtofilevalue= "true" />    <maximumFileSizevalue= "500KB" />    <maxsizerollbackupsvalue= "2" />    <Layouttype= "log4net." Layout.patternlayout ">      <Conversionpatternvalue= "%date%level%logger-%message%newline" />    </Layout>  </Appender>  <Root>    < Levelvalue= "All" />    <Appender-refref= "Rollingfile" />  </Root></log4net>

Log4net provides a very powerful control strategy, such as the ability to control output log output formats, header and footer, overlay policies, security controls, and more. The configuration in the example above is to add a appender and put all types of information in C:\Temp\log4net.log. In the actual project, you should use more detailed configuration information. For example, you might need to send an ERROR or FATAL level of information to your system administrator.

3. Edit and add the following to Global.asax.cs, let log4net to read this XML configuration.

protected void Application_Start () {    log4net. Config.XmlConfigurator.Configure ();}

4. In order to test this log4net log, add the following to the HomeController.cs file. Create a logging component instance first,

Private Static readonly log4net. ILog log = log4net. Logmanager.getlogger (typeof

Log debug information.

 Public ActionResult Index () {   log. Debug ("Homecontroller.index () was called");   return Index ();}

5. After starting the program, browsing home page,log4net will create the C:\Temp\log4net.log file and add the following log information for each request:

2015-07-20 09:53:14,682 DEBUG Mycompany.webui.controllers.homecontroller-homecontroller.index () was called

Ii. detailed description of the configuration

With the above example, you can quickly configure and use Log4net, and from the use process, it is found that the key to use is the configuration of log4net, which is the <log4net> node in the Web. config file. The following is an introduction to the important configuration under this node.

1.<appender>

Each <appender> child node represents a way of logging (only configured here does not represent enabled).

Specifically, the following appender are available:
Adonetappender: Log on to the database using ADO.
Ansicolorterminalappender: Write a high-brightness log event in the ANSI window terminal.
Aspnettraceappender: You can view the log of a record in the same way as trace in ASP.
Bufferingforwardingappender: Caches log events before outputting to child appenders.
Consoleappender: Output The log to the console.
Eventlogappender: Writes the log to Windows Event log.
Fileappender: Writes the log to the file.
Localsyslogappender: Writes the log to the local syslog service (only for UNIX environments).
Memoryappender: The log is stored in the memory buffer.
Netsendappender: Output The log to the Windows Messenger Service. These log messages are displayed in the User Terminal's dialog box.
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.
Traceappender: Writes the log to the. NET trace System.
Udpappender: Send the log connectionless UDP datagrams to the remote host or broadcast as UdpClient.

Consider using the Rollingfileappender method in your project: (Control log file size issues) for a system that is used for a long time and has a large number of business logs, it can cause poor performance if you use Fileappender to log all the way to a file. In this case, consider using the Rollingfileappender loop to log logs, specify the maximum length of the file, and regenerate a file if it is exceeded, such as the following configuration:

<Appendername= "Rollingfileappender"type= "log4net." Appender.rollingfileappender ">  <filevalue= "Rollingfileappender_log.txt" />  <Appendtofilevalue= "true" />  <Rollingstylevalue= "Size" />  <maxsizerollbackupsvalue= "Ten" />  <maximumFileSizevalue= "100KB" />  <Staticlogfilenamevalue= "true" />  <Layouttype= "log4net." Layout.patternlayout ">    <Conversionpatternvalue= "%date [%thread] (%file:%line)%-5level%logger [%PROPERTY{NDC}]-%message%newline" />  </Layout></Appender>

In the above configuration, each log file maximum 100KB, the maximum number of log files is 10, the generated log file name will be Rollingfileappender_log.txt.1, rollingfileappender_log.txt.2 ... rollingfileappender_log.txt.10, if more than 10 logs are logged, they will be overwritten from Rollingfileappender_log.txt.1.

Another way is to log the logs by date, which is configured as follows:

<Appendername= "Rollinglogfileappender_dateformat"type= "log4net." Appender.rollingfileappender ">  <filevalue= "Rollinglogfileappender_dateformat_log.txt" />  <Appendtofilevalue= "true" />  <Rollingstylevalue= "Date" />  <!--<datepattern value= "yyyymmdd-hhmm"/> -  <Datepatternvalue= "YyyyMMdd" />  <Layouttype= "log4net." Layout.patternlayout ">    <Conversionpatternvalue= "%date [%thread] (%file:%line)%-5level%logger [%PROPERTY{NDC}]-%message%newline" />  </Layout></Appender>

Every day the log is written to a file, the day's log file is named "Rollinglogfileappender_dateformat_log.txt", the day's log will be taken with the date of the day, such as "Rollinglogfileappender_ Dateformat_log.txt20101117 "represents the November 17, 2010 log, which is convenient to differentiate and find.

2.<root>

Turn off and enable logging, which can be configured in <root>, as an example:

<Root>  <!--record log as file Form -  <Appender-refref= "Logfileappender" />  <!--Console control display log -  <Appender-refref= "Consoleappender" />  <!--Windows Event Log -  <!--<appender-ref ref= "Eventlogappender"/> -  <!--SQLite Event Log -  <Appender-refref= "Adonetappender_sqlite" />  <!--Rollingfileappender Event Log -  <Appender-refref= "Rollingfileappender" />  <!--Rollingfileappender Event Log, one log per day -  <Appender-refref= "Rollinglogfileappender_dateformat" />  <!--If you do not enable the appropriate logging, you can comment out this way <appender-ref ref= "adonetappender_access"/> -</Root>

Increase the log output destination, you can increase the <appender-ref> node, note that the following ref is Appender name, if you want to cancel, delete or comment out the line can be.

<root> under < level value= ' All ' /> label settings allow logging levels to be logged. There are seven levels, of which 2 to 6 can be called in the Code,

  1. OFF
  2. FATAL
  3. ERROR
  4. WARN
  5. INFO
  6. DEBUG
  7. All

  < root >    < layout >   Label sets the log data record format.  < layout >   sub-label set specific format

    • %date-Output the date under the local time zone, you can use the format%date{mmmm dd, yyyy HH:mm:ss, FFF} output "January 01, 2011 14:15:43, 767"
    • %utcdate-Output World Time
    • %exception-When an exception is passed in, a new line is added after the exception, and no exception is present when it is passed in.
    • %level-Record the event level
    • %message-User-passed in information
    • %newline-Line break
    • %timestamp-Timestamp, the number of milliseconds since the program was run
    • %thread-The thread name or thread number of the calling interface

The following methods should be used with caution:

    • %identity-The name of the current user, calling the Principal.Identity.Name property
    • %location-Useful in debug mode to indicate where the logging method is called
    • %line-Displays the line number of the call record
    • %method-Shows how to call records
    • %username-Show Windows users,调用 System.Security.Principal.WindowsIdentity 属性

You can add a value between the% symbol and the name of the call so that each piece of information has a fixed width:

    • X-Sets the minimum number of characters. If the information width is less than the set number of characters, spaces are padded to the left of the character, for example, %10message显示 " hi "
    • -X-The function is the same as above, the space will be filled to the right, for example, %-10message显示 " hi "
    • .X-Set the maximum number of characters, and if the information exceeds the set value, chop off the beginning of the string, for example, " %.10message显示 rror entry " if the incoming is "" Error entry

Iii. use in the program

Currently just call the function in the place where the log records are needed, and the log4net logging function is simple,

void Info (object  message); void Info (object message, Exception Exception);

The name of the function is the log level, Error, Fatal, info, Debug, Warn, parameter has an incoming message string, and exception information.

The above content is organized from the Internet, the following links to facilitate future inquiries

Http://www.cnblogs.com/anderslly/archive/2007/03/09/log4netconfigsamples.html

Http://www.codeproject.com/Articles/140911/log4net-Tutorial

Http://logging.apache.org/log4net/index.html

[. Net MVC] Using the Log4net log framework

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.