Log4net Tutorial Log classification and automatic Maintenance sample

Source: Internet
Author: User

 log4net can be categorized by function? It can be done by configuring different logger, and then the function loads Ilog instances according to different loggername. However, because the log configuration of these features is very small, perhaps only the filename is different. So you want to configure it through code, and here's how to share the following

If we need to configure different ilog, the process is this, first of all, to create a iloggerrepository, through which log level configuration, and a variety of appender, Then by Logmanager in Iloggerrepository get a Ilog object, you can write the log. The code is as follows: The   code is as follows: public static ILog GetLogger (String repositoryname = "")         {    &N Bsp       if (string. IsNullOrEmpty (Repositoryname)) return Logmanager.getlogger ("Defalut");               iloggerrepository repository = null;             try             {        &NBS P       repository = logmanager.getrepository (repositoryname);                         catch (Exception) {}              //Find direct return ilog             if (repository!= null)   & nbsp             return Logmanager.getlogger (Repositoryname, "Defalut");             //not found then created, multithreading is very likely to create when there is the             try   & nbsp         {                repository = Logmanager.createreposi Tory (Repositoryname);                         catch (Exception)     &NBS P       {                repository = logmanager.getrepository (repos Itoryname);                          //configuration log level   Read appsettings Configuration               var appset = ConfigurationManager.AppSettings.AllKeys;              //lookup log level             const string LogLevel = "LogLevel";             var hassettings = Array.indexof (Appset, loglevel);   &NBSp         if (Hassettings >-1)             {      &NBS P         var level = Configurationmanager.appsettings[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 output Appender             const string Log Appender = "Logappender";             hassettings = Array.indexof (Appset, Logappender);             if (Hassettings >-1)             {  &NBS P             var appenders = Configurationmanager.appsettings[logappender]. ToLower (). Split (', ');                 foreach (var appender in appenders)         &N Bsp       {                    if (Appender = "Rollingfile") ) Loadrollingfileappender (repository);                 &nbsp   else if (Appender = "Console") Loadconsoleappender (repository);                     else if (Appender = "Trace") Loadtraceappender (repos Itory);                            }             Else Loadrollingfileappender (repository);               return Logmanager.getlogger (Repositoryname, "Default");        }       log4net will automatically maintain ilog and iloggerrepository, so do not save, through Logmanger access. But I didn't find a way to find out if the specified iloggerrepository existed, so I judged it through a try catch in the code above. Since we are configuring Log4net in code, but still want to set the log level and output type through configuration, I chose to configure it in the appsettings file, one at a time, for all iloggerrepository. The reason why it is not configured for each feature, mainly due to configuration problems, and if you really want to do so, directly in the log4net configuration of different logger, by loggername reference, may be better.   Log Maintenance   So the next question is, how do I delete a log?   Log4net can be configured Rollingfileappender, translated is scrolling file. You can do this by setting the maximumFileSize and maxsizerollbackups 2 parameters, which each achieves a certainThe size produces a new file with a maximum total of maxsizerollbackups, but only if the file name is consistent.   For example, we use the following configuration: The code is as follows: <!--rollingfileappender: output to file-->     <appender name= "Sysappender" type= " Log4net. Appender.rollingfileappender ">       <!--log path-->       <file value=" logs/"/& Gt       <!--overwrite, default is append true-->       <appendtofile value= "true"/>     &N Bsp <!--does not occupy the log file process-->       <lockingmodel type= "log4net. Appender.fileappender+minimallock "/>       <rollingstyle value=" composite "/>     & nbsp <!--file name-->       <datepattern value= "Yyyy-mm-dd HH" when. Log ' "></DatePattern>       <!--set Unlimited backup =-1, maximum number of backup 1000-->       <param name= "maxsizerollbackups" value= "1000"/ >       <!--size of each file-->       <param name= "maximumfilesize" value= "500KB"/> & nbsp     <! --name can be changed to false to be able to change-->       <param name= "Staticlogfilename" value= "false"/>     & nbsp <layout type= "log4net. Layout.patternlayout ">         <!--output format-->         < Conversionpattern value= "%n" Record Time "%date%n" description "%message%n"/>       </layout>     </ The appender>     effect is that the log is in hours, the maximum number of backups per hour is 1000, and the log file is formed every 500kb. As the number of days increases, so does the file, and we need to clean it ourselves. So the above configuration can be slightly changed:   code as follows: <!--rollingfileappender: output to file-->     <appender name= "Sysappender" type= "Log4net. Appender.rollingfileappender ">       <!--log path-->       <file value=" logs/ Log. Log "/>       <!--overwrite, default is append true-->       <appendtofile value=" true "/> &n Bsp     <!--does not occupy the log file process-->       <lockingmodel type= "log4net. Appender.fileappender+minimallock "/>       <rolLingstyle value= "composite"/>       <!--file name-->       <datepattern value= " Yyyy-mm-dd HH ' When. Log ' "></DatePattern>       <!--set Unlimited backup =-1, maximum number of backups for 1000-->     & nbsp <param name= "maxsizerollbackups" value= "1000"/>       <!--size of each file-->       <param name= "maximumFileSize" value= "500KB"/>       <!--name can be changed to false to be able to change-->       <param name= "Staticlogfilename" value= "true"/>       <layout type= "log4net. Layout.patternlayout ">         <!--output format-->         < Conversionpattern value= "%n" Record Time "%date%n" description "%message%n"/>       </layout>     </ Appender>     Mainly sets the log file name and is a static name and does not allow changes. Since then, there are only 1000 log files, no manual maintenance, you will see the log file name:   log   log. log.1   log. log.2   ... Default is file name the larger the last number, the oldest, so view the new log, mainly in the first file name. Other than thatReminder: If the settings appender use a static filename, then the history of the log will be covered, and extremely concerned about the application of the history log, it is recommended not to use this scheme, clean up the log, or honestly write code.  

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.