(1) Use log4net to generate log files and log4net log files

Source: Internet
Author: User
Tags log4net

(1) Use log4net to generate log files and log4net log files
1. Introduce log4net. dll

1.1 Nuget installation or plugin.

2. Configure log4net. config

2.1 Add configSections nodes to the Web. config file.

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

2.2 add log4net. config (set to always copy to output directory)

<? Xml version = "1.0" encoding = "UTF-8"?> <Configuration> <log4net> <! -- Information log class --> <logger name = "loginfo"> <level value = "ALL"/> <appender-ref = "InfoAppender"/> </logger> <! -- Additional information log media --> <appender name = "InfoAppender" type = "log4net. Appender. RollingFileAppender"> <! -- Output directory --> <param name = "File" value = "Log \ LogInfo \"/> <! -- Whether to overwrite the file --> <param name = "AppendToFile" value = "true"/> <! -- Number of backup files --> <param name = "MaxSizeRollBackups" value = "50"/> <! -- Maximum size of a single log file --> <param name = "MaxFileSize" value = "10240"/> <! -- Whether to use static file name --> <param name = "StaticLogFileName" value = "false"/> <! -- Log file name --> <param name = "DatePattern" value = "yyyyMMdd&quot;.htm & quot;"/> <param name = "RollingStyle" value = "Date"/> <! -- Layout. For more parameters, refer to the instructions on the official website --> <layout type = "log4net. layout. patternLayout "> <param name =" ConversionPattern "value =" & lt; hr color = red & gt; % n Level: %-5 p & lt; BR & gt; % n time: % d [% t] & lt; BR & gt; % n Description: % m & lt; BR & gt; "/> </layout> </appender> </log4net> </configuration>

2.3 specify log4net. config in the AssemblyInfo. cs File

[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", ConfigFileExtension = "config", Watch = true)]
3. Sample Code

3.1 encapsulation tool LogHelper

namespace July.Demo.Win{    public class LogHelper    {        static readonly log4net.ILog loginfo = log4net.LogManager.GetLogger("loginfo");        public static void WriteLog(string info)        {            if (loginfo.IsInfoEnabled)            {                loginfo.Info(info);            }        }    }}

3.2 Example

Private void Form1_Load (object sender, EventArgs e) {LogHelper. WriteLog ("form generation ");}
4. Running result

4.1 as follows

 


How to Use Log4net to create logs

First, let's analyze the working principle of Log4net: Log4net is a very famous open-source component for recording logs developed based on. NET. It uses a set of log engines configured in XML to classify logs into different levels: FATAL, ERROR, WARN, INFO, DEBUG, and ALL (allow ALL log requests) and OFF (reject all log requests). The default value is DEBUG. The first five items are similar to the errors we encounter when debugging applications, in the compiler, prompts such as errors and warnings are also left, and their error levels are constantly decreasing. Let's look at the core components of Log4net. Log4net consists of five parts: Logger, Appenders, Filters, Layouts, and Object Renders. 1) Logger: mainly responsible for logging. It can be recorded in multiple ways, such as files, databases, consoles, and emails. 2) Appenders: it is mainly responsible for recording the log media. Its output methods mainly include AdoNetAppender, which records logs to the database. You can use SQL or stored procedures. AspNetTraceAppender: You can trace logs in ASP. NET. BufferingForwardingAppender: cache log events before outputting them to sub-Appenders. ColoredConsoleAppender: Write high-brightness log events in the terminal window. ConsoleAppender: outputs logs to the console. EventLogAppender: writes logs to Windows operating system logs. FileAppender: Write logs to files. ForwardingAppender: used to specify a group of constraints for an Appender. MemoryAppender: stores logs in the memory buffer. NetSendAppender: outputs logs to the Windows Messenger service. The logs are displayed in the user terminal dialog box. OutputDebugStringAppender: configure this Appender to write logs to the OutputDebugString API. RemotingAppender: writes logs to the remote acceptor through. NET Remoting. RollingFileAppender: writes logs to a file in the form of a rollback file. SmtpAppender: Write logs to emails. SmtpPickupDirAppender: the configuration is similar to that of SmtpAppender, but replace SmtpHost with PickupDir. TraceAppender: Write logs to the. NET trace system. UdpAppender: Send Logs in the form of connectionless UDP multicast Rams to a remote host or broadcast logs in the form of UdpClient. Some of the above output methods may be used frequently, and some may not be used frequently. The specific examples are as follows. 3) Layouts: it is mainly responsible for formatting and outputting record logs. The display formats are as follows: % timestamp [% thread] %-5 level % logger {2} % ndc-% message % newline timestamp: indicates the time when the program has started running. Unit: [millisecond]. Thread: the Thread that executes the current code. Level: the log Level. Logger: the name of the log-related request.

How does log4net view the log file name currently being written?

A new log file is generated as long as it is larger than 10 MB.
This is to instruct you to rename the old log file. The log file currently being written, or the file name specified in the configuration, OK?
You only need to open the file specified in the configuration, which is the latest

Related Article

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.