[Java] [log4j] log4j log files every day, hourly, and minute

Source: Internet
Author: User
Tags date now time interval log4j
Received a demand, through the log4j time print log, requirements described as follows: the need to be able to print the log regularly, the interval can be matched. When it comes to timing, first think of the Dailyrollingfileappender class, various timing, according to Datepattern, this can refer to class SimpleDateFormat class, common some of the regular settings are as follows: [HTML]View Plain copy print? '.' YYYY-MM: Monthly '. ' YYYY-WW: Weekly '. ' YYYY-MM-DD: Every day '. ' Yyyy-mm-dd-a: Two times a day '. ' YYYY-MM-DD-HH: Every hour '. ' YYYY-MM-DD-HH-MM: Per minute
'.' YYYY-MM: Monthly
'. ' YYYY-WW: Weekly 
'. ' YYYY-MM-DD: Every day
'. ' Yyyy-mm-dd-a: Two times a day
'. ' YYYY-MM-DD-HH: Every hour
'. ' YYYY-MM-DD-HH-MM: Per minute

By observing that there are no n-minute similar date formats, a custom class is written based on the Dailyrollingfileappender class. The process is as follows:

1 copy dailyrollingfileappender type source code and renamed Minuterollingappender, in order to configure in Log4j.xml, add configuration Items intervaltime adding set, get method; Java] view plain copy print? private int intervaltime = 10;

private int intervaltime = 10;

2) because the Dailyrollingfileappender class uses the Rollingcalendar class to compute the next interval, it needs to pass the parameter intervaltime, so modify the Rollingcalendar class as an inner class Because the method is to calculate the time of the next rollover action based on Datepattern, no other time pattern is required, and the following is the modified method: [Java] view plain copy print?       Public date getnextcheckdate (date now) {this.settime (now);       This.set (Calendar.second, 0);       This.set (Calendar.millisecond, 0);       This.add (Calendar.minute, intervaltime);   return GetTime (); }

		Public date getnextcheckdate (date now)
		{
			this.settime (now);
			This.set (Calendar.second, 0);
			This.set (Calendar.millisecond, 0);
			This.add (Calendar.minute, intervaltime);
			return GetTime ();
		}

3 According to the Minutes, the time pattern needs to be disabled, change it to static final, the response to remove its get, set method and Minuterollingappender constructor datepattern parameters [Java] View Plain copy print? private static String Datepattern = "'. ' yyyy-mm-dd-hh-mm '. log ' ";

private static String Datepattern = "'. ' yyyy-mm-dd-hh-mm '. log ' ";

Similarly, the method of serving a variety of datepattern computecheckperiod () can also be deleted; So the transformation is done and the categories are as follows:[Java] View Plain copy print? package net.csdn.blog;      import java.io.file;   import  java.io.ioexception;   import java.io.interruptedioexception;   import  java.text.simpledateformat;   import java.util.calendar;   import java.util.Date;    import java.util.gregoriancalendar;      import  org.apache.log4j.fileappender;   import org.apache.log4j.layout;   import  org.apache.log4j.helpers.loglog;   import org.apache.log4j.spi.loggingevent;      /**   *  per minute configurable timing appender   *    *  @author  coder_xia   *    */   public class minuterollingappender extends  fileappender   {       /**       * the  date pattern. by default, the pattern is set to  "'. ' Yyyy-mm-dd "       * meaning daily rollover.        */       private static String DATEPATTERN  =  "'. ' yyyy-mm-dd-hh-mm '. Log ';       /**       *  time interval , units: minutes        */       private int  intervaltime = 10;          /**        * The log file will be renamed to the value of  the scheduledfilename       * variable when the next  interval is entered. For example, if the rollover        * period is one hour, the log file will be renamed to the value  of       *  "Scheduledfilename"  at the beginning of  the next hour.       *        *  the precise time when a rollover occurs depends on logging  activity.       */       private string  scheduledFilename;          /**        * The next time we estimate a rollover should occur.       */       private long nextcheck =  system.currenttimemillis ()  - 1;          date now  = neW date ();          SimpleDateFormat sdf;           rollingcalendar rc = new rollingcalendar ();          /**       * The default  constructor does nothing.       */        Public minuterollingappender ()        {       }           /**       * instantiate  a <code>MinuteRollingAppender</code> and open the file        * designated by <code>filename</code>. the opened  filename will become the       * ouput destination  for this appender.       */       public  Minuterollingappender (layout layout, string filename)                 throws IOException       {            super (layout, filename, true);           activateoptions ();       }           /**       *  @return  the  intervaltime       */       public int  Getintervaltime ()        {            return intervalTime;       }           /**&nbSp      *  @param  intervalTime       *             the intervalTime to set        */       public void setintervaltime (int  IntervalTime)        {            this.intervaltime = intervaltime;       }            @Override        public void activateoptions ()         {            Super.activateoptions ();           if  (filename !=  null)            {                 now.settime (System.currenttimemillis ());                sdf = new simpledateformat (DATEPATTERN);                file file = new  file (fileName);                scheduledfilename = filename                        + sdf.format (New Date (file.lastModified) ( ));              }            else           {               LogLog          &Nbsp;             .error ("Either File  or datepattern options are not set for appender ["                                + name +  "].");            }       }          /**       * Rollover the  current file to a new file.       */        void rollover ()  throws IOException       {            string datedfilename = filename +  sdf.format (now);   &Nbsp;       // it is too early to roll  over because we are still within the            // bounds of the current interval. Rollover will  occur once the           // next interval  is reached.           if  ( Scheduledfilename.equals (datedfilename))            {                return;            }              / / close current file, and rename it to datedfilename          &Nbsp; this.closefile ();              File  Target = new file (scheduledfilename);            if  (Target.exists ())            {                target.delete ();            }               File file = new file (fileName);            boolean result = file.renameto (target);            if  (Result)            {                loglog.debug (fileName +  " - >  " +&Nbsp;scheduledfilename);           }            else           {                loglog.error ("Failed to  rename [" + fileName + "] to ["                        +  scheduledfilename +  "].");            }               try           {                // this will also close  the file. This is OK since multiple     &Nbsp;         // close operations are safe.                this.setfile (FileName,  true, this.bufferedio, this.buffersize);            }           catch  (ioexception e)            {                errorhandler.error ("Setfile" (" + fileName + ",  true)  call  failed. ");            }            scheduledFilename = datedFilename;       }          /**       * t

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.