Log4net tutorial log classification and automatic maintenance example

Source: Internet
Author: User
Tags log4net

If we need to configure different ilogs, the process is like this. First, we need to create an ILoggerRepository to configure the Log Level and various Appender, then, you can use LogManager to obtain an Ilog object in ILoggerRepository to write logs. The Code is as follows:

Copy codeThe Code is as follows:
Public static ILog GetLogger (string repositoryName = "")
{
If (string. IsNullOrEmpty (repositoryName) return LogManager. GetLogger ("Defalut ");

ILoggerRepository repository = null;
Try
{
Repository = LogManager. GetRepository (repositoryName );
}
Catch (Exception ){}

// Find and return ilog directly
If (repository! = Null)
Return LogManager. GetLogger (repositoryName, "Defalut ");

// If it is not found, it is created. It is very likely that it exists when it is created in multiple threads.
Try
{
Repository = LogManager. CreateRepository (repositoryName );
}
Catch (Exception)
{
Repository = LogManager. GetRepository (repositoryName );
}

// Configure the log level to read the Appsettings Default Configuration
Var appSet = ConfigurationManager. receivettings. AllKeys;

// Query the Log Level
Const string logLevel = "LogLevel ";
Var hasSettings = Array. IndexOf (appSet, logLevel );
If (hasSettings>-1)
{
Var level = ConfigurationManager. receivettings [logLevel]. ToLower ();
If (level = "all") repository. Threshold = Level. All;
Else if (level = "debug") repository. Threshold = Level. Debug;
Else if (level = "info") repository. Threshold = Level. Info;
Else if (level = "warn") repository. Threshold = Level. Warn;
Else if (level = "error") repository. Threshold = Level. Error;
Else if (level = "fatal") repository. Threshold = Level. Fatal;
Else if (level = "off") repository. Threshold = Level. Off;
}
Else repository. Threshold = Level. All;

// Find the output Appender
Const string logAppender = "LogAppender ";
HasSettings = Array. IndexOf (appSet, logAppender );
If (hasSettings>-1)
{
Var appenders = ConfigurationManager. receivettings [logAppender]. ToLower (). Split (',');
Foreach (var appender in appenders)
{
If (appender = "rollingfile") LoadRollingFileAppender (repository );
Else if (appender = "console") LoadConsoleAppender (repository );
Else if (appender = "trace") LoadTraceAppender (repository );
}
}
Else LoadRollingFileAppender (repository );

Return LogManager. GetLogger (repositoryName, "Default ");
}

Log4net automatically maintains ILog and ILoggerRepository, so you do not need to save it. You can obtain it through LogManger. However, I cannot find a way to check whether the specified ILoggerRepository exists. Therefore, I can use try catch in the above Code to determine whether the ILoggerRepository exists. Because we configure log4net through code, but still want to set the Log Level and output type through configuration, so I choose to configure it in the deleettings file once, it takes effect for all ILoggerRepository. The reason for not configuring each function is mainly because of configuration troubles. If you want to configure different logger directly in log4net, it may be better to reference it through loggername.

Log Maintenance

So the next question is, how do I delete logs?

Log4net can configure RollingFileAppender, which is translated as a rolling file. You can set the MaximumFileSize and MaxSizeRollBackups parameters to create a new file every time the log file reaches a certain size. The maximum number of files is MaxSizeRollBackups, the premise is that the file names are consistent.

For example, we use the following Configuration:

Copy codeThe Code is as follows:
<! -- RollingFileAppender: output to file -->
<Appender name = "SysAppender" type = "log4net. Appender. RollingFileAppender">
<! -- Log Path -->
<File value = "Logs/"/>
<! -- Whether to overwrite; default value: true -->
<AppendToFile value = "true"/>
<! -- Does not occupy the log file process -->
<LockingModel type = "log4net. Appender. FileAppender + MinimalLock"/>
<RollingStyle value = "Composite"/>
<! -- File name -->
<DatePattern value = "yyyy-MM-dd HH 'time. log'"> </DatePattern>
<! -- Set unlimited backup =-1 and the maximum number of backups is 1000 -->
<Param name = "MaxSizeRollBackups" value = "1000"/>
<! -- Size of each file -->
<Param name = "MaximumFileSize" value = "500KB"/>
<! -- Can the name be changed to false? -->
<Param name = "StaticLogFileName" value = "false"/>
<Layout type = "log4net. Layout. PatternLayout">
<! -- Output format -->
<ConversionPattern value = "% n [record time] % date % n [description] % message % n"/>
</Layout>
</Appender>

The result is that logs are backed up in hours, and the maximum number of backups per hour is 1000. A log file is generated every kb. As the number of days increases, the number of files increases and we need to clear the files ourselves. Therefore, the preceding configuration can be changed slightly:

Copy codeThe Code is as follows:
<! -- RollingFileAppender: output to file -->
<Appender name = "SysAppender" type = "log4net. Appender. RollingFileAppender">
<! -- Log Path -->
<File value = "Logs/log. log"/>
<! -- Whether to overwrite; default value: true -->
<AppendToFile value = "true"/>
<! -- Does not occupy the log file process -->
<LockingModel type = "log4net. Appender. FileAppender + MinimalLock"/>
<RollingStyle value = "Composite"/>
<! -- File name -->
<DatePattern value = "yyyy-MM-dd HH 'time. log'"> </DatePattern>
<! -- Set unlimited backup =-1 and the maximum number of backups is 1000 -->
<Param name = "MaxSizeRollBackups" value = "1000"/>
<! -- Size of each file -->
<Param name = "MaximumFileSize" value = "500KB"/>
<! -- Can the name be changed to false? -->
<Param name = "StaticLogFileName" value = "true"/>
<Layout type = "log4net. Layout. PatternLayout">
<! -- Output format -->
<ConversionPattern value = "% n [record time] % date % n [description] % message % n"/>
</Layout>
</Appender>

It mainly sets the log file name and static name, which cannot be changed. In this way, there are a maximum of 1000 log files, so you do not need to manually maintain them. You will see such log file names:

Log. log. log.1 log. log.2... by default, the last number of the file name increases and the time is the oldest. Therefore, you can view the new log mainly in the first file name.
Note: If the Appender uses a static file name, the history log will be overwritten, and the application that cares about the history log is extremely concerned. We recommend that you do not use this solution to clear the logs, write code honestly.

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.