LOG4J supports simultaneous splitting of logs by date and file size

Source: Internet
Author: User

Rewrite the source code, you can use the code as a tool class:

1.log4jdateandsizesplit.java

/** * Project Name:hao24-common * File Name:Log4JDateAndSizeSplit.java * Package Name:cn.hao24.util.spring * date:2016 year March 31st Morning 11:30:22 * Copyright (c), Lujie All rights Reserved. **/
Package test/** * CLASSNAME:LOG4JDATEANDSIZESPLIT:LOG4J Log supports cutting by date and size <br/> * date:2016 year March 31 morning 11:30:22 <b r/> * @author Lujie * @version * @see */import java.io.file;import java.io.ioexception;import java.io.writer;impo RT Java.text.simpledateformat;import Java.util.date;import Java.util.locale;import Java.util.TimeZone;import Org.apache.log4j.fileappender;import Org.apache.log4j.layout;import Org.apache.log4j.helpers.CountingQuietWriter ; Import Org.apache.log4j.helpers.loglog;import Org.apache.log4j.helpers.optionconverter;import org.apache.log4j.spi.loggingevent;/** * * Classname:log4jdateandsizesplit <br/> * function:log4j generate log class rewrite, The class can separate logs by date + specified size. <br/> * date:2016 March 31 pm 12:44:14 <br/> * @author Lujie * @version */public class Log4jdateandsizesplit Exte NDS fileappender{//The code assumes that the following constants is in a increasing//sequence.static final int top_of_t rouble = -1;static final int top_of_minute = 0;static final intTop_of_hour = 1;static final int half_day = 2;static final int top_of_day = 3;static final int top_of_week = 4;static Fina l INT top_of_month = 5;/** * The default maximum file size is 10MB. */protected Long maxfilesize = ten * 1024x768 * 1024;/** * There is one backup file by default. */protected int maxbackupindex = 1;/** * meaning daily rollover. */private String datepattern = "'. ' YYYY-MM-DD ";/** *" Scheduledfilename "at the beginning of the next hour. * */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 (), int checkperiod = top_of_trouble;//The Gmttimezone is used only in COMPUTECHEC Kperiod () method.static final TimeZone gmttimezone = Timezone.gettimezone ("GMT");/** * The default constructor does Nothi Ng. */public Log4jdateandsizesplit () {}/** * ouput destination for this appender. */public LoG4jdateandsizesplit (layout layout, string filename, String datepattern) throws Ioexception{super (layout, filename, True ); This.datepattern = Datepattern;activateoptions ();} /** * Being rolled to backup files. * * @since 1.1 */public Long Getmaximumfilesize () {return maxfilesize;} /** * Being rolled to backup files. * * <p> * JavaBeans {@link java.beans.Introspector introspector}. * * @see #setMaxFileSize (String) */public void setmaximumfilesize (Long maxfilesize) {this.maxfilesize = MaxFileSize;} /** * Being rolled to backup files. * * <p> * The value "10KB" would be interpreted as 10240. */public void Setmaxfilesize (String value) {maxfilesize = Optionconverter.tofilesize (value, MaxFileSize + 1);} /** * Returns The value of the <b>MaxBackupIndex</b> option. */public int Getmaxbackupindex () {return maxbackupindex;} /** * Set The maximum number of backup files to keep around. * * <p> */public void setmaxbackupindex (int maxbackups) {this.maxbackupindex = maxbackups;} /** */public void Setdatepattern (String pattern) {Datepattern = pattern;} /** Returns The value of the <b>DatePattern</b> option. */public String Getdatepattern () {return datepattern;} @Overridepublic void Activateoptions () {super.activateoptions (); if (Datepattern! = NULL && FileName! = null) { Now.settime (System.currenttimemillis ()); SDF = new SimpleDateFormat (datepattern); int type = Computecheckperiod (); Printperiodicity (type); Rc.settype (type); File File = new file (filename), scheduledfilename = FileName + sdf.format (new Date (File.lastmodified ()));} Else{loglog.error ("Either File or Datepattern options is not set to Appender [" + Name + "].");}} void printperiodicity (int type) {switch (type) {case TOP_OF_MINUTE:LogLog.debug ("Appender [" + name + "] to be rolled every minute. "); Break;case TOP_OF_HOUR:LogLog.debug ("Appender [+ name +"] to being rolled on TOP of every HOUR. "); Break;case HALF_DAY:LogLog.debug ("Appender [+ name +"] to be rolLed at midday and midnight. "); Break;case TOP_OF_DAY:LogLog.debug ("Appender [+ name +"] to being rolled at midnight. "); Break;case TOP_OF_WEEK:LogLog.debug ("Appender [+ name +"] to being rolled at start of WEEK. "); Break;case TOP_OF_MONTH:LogLog.debug ("Appender [" + name + "] to being rolled at start of every MONTH."); Break;default:loglog.warn ("Unknown Periodicity for Appender [" + Name + "].");}} This method is computes the roll over period by looping through the//periods, starting with the shortest, and stopping when The R0 is//different from from R1, where R0 are the epoch formatted according//the Datepattern (supplied by the user) and R1 is the//epoch+nextmillis (i) formatted according to Datepattern. All date//formatting are done with GMT and not local format because the test//logic are based on comparisons relative to 197 0-01-01 00:00:00//GMT (The epoch). int Computecheckperiod () {Rollingcalendar Rollingcalendar = new Rollingcalendar ( Gmttimezone, locale.english);//Set Sate to 1970-01-01 00: 00:00 gmtdate epoch = new Date (0), if (datepattern! = null) {for (int i = top_of_minute; I <= top_of_month; i++) {simpled Ateformat SimpleDateFormat = new SimpleDateFormat (Datepattern); Simpledateformat.settimezone (GmtTimeZone); Do all date//formatting in gmtstring r0 = Simpledateformat.format (epoch); Rollingcalendar.settype (i);D ate next = new Da Te (Rollingcalendar.getnextcheckmillis (epoch)); String r1 = Simpledateformat.format (next);//System.out.println ("Type =" +i+ ", R0 =" +r0+ ", r1 =" +r1 "); if (r0! = null &amp ;& R1! = null &&!r0.equals (r1)) {return i;}}} return top_of_trouble; Deliberately head for trouble ...} /** * Implements The usual roll over behaviour. * * <p> * If <code>MaxBackupIndex</code> is positive and then files {* * * <p> * if <code&gt ; Maxbackupindex</code> is equal to zero and then the * <code>File</code> was truncated with no backup files Created. */public//synchronization not necessary since Doappend is aLreasy synchedvoid Sizerollover () {File target; File file; Loglog.debug ("Rolling over count=" + ((countingquietwriter) QW). GetCount ()); Loglog.debug ("maxbackupindex=" + maxbackupindex); String datedfilename = FileName + Sdf.format (now); if (Maxbackupindex > 0) {//Delete the oldest file, to keep Windows ha Ppy.file = new File (Datedfilename + '. ' + Maxbackupindex), if (File.exists ()) file.delete ();//Map {(maxBackupIndex-1), ... ., 2, 1} to {Maxbackupindex, ..., 3,//2}for (int i = maxBackupIndex-1; I >= 1; i--) {file = new file (Datedfilename + "." + i); if (File.exists ()) {target = new file (Datedfilename + '. ' + (i + 1)); Loglog.debug ("Renaming file" + file + "to" + target); File.renameto (target);}} Rename fileName to Datedfilename.1target = new File (Datedfilename + "." + 1); This.closefile (); Keep Windows happy.file = new file (fileName); Loglog.debug ("Renaming file" + file + "to" + target); File.renameto (target);} else if (Maxbackupindex < 0) {//infinite number of files//find the Max backup indexfor (int i = 1; i < Integer.max_value; i++) {target = new File (Datedfilename + "." + i); if (!target.exi STS ()) {//Rename fileName to DatedFilename.ithis.closeFile (); file = new file (fileName); File.renameto (target); Loglog.debug ("Renaming file" + file + "to" + target); try{//This would also close the file. This was OK since multiple//close operations is Safe.this.setFile (FileName, False, Bufferedio, buffersize);} catch (IOException e) {loglog.error ("setfile (" + FileName + ", false) call failed.", e);} Scheduledfilename = Datedfilename;} @Overridepublic synchronized void Setfile (String fileName, Boolean append, Boolean bufferedio, int buffersize) throws Ioex Ception{super.setfile (filename, append, This.bufferedio, this.buffersize); if (append) {file F = new File (filename);(( Countingquietwriter) QW). SetCount (F.length ());}} @Overrideprotected void Setqwforfiles (writer writer) {this.qw = new Countingquietwriter (writer, errorhandler);} /** * Rollover The current file to a New file. */void Timerollover () throws ioexception{/* Compute filename, but only if Datepattern is specified */if (datepattern = = Nu ll) {Errorhandler.error ("Missing datepattern option in RollOver ()."); return;} String datedfilename = FileName + Sdf.format (now);//It is too early to roll over because we are still within the//bounds of the current interval. Rollover would occur once the//next interval is Reached.if (scheduledfilename.equals (datedfilename)) {return;} Close current file, and rename it to Datedfilenamethis.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 + "+" + sche Duledfilename);} Else{loglog.error ("Failed to rename [" + FileName + "] to [" + Scheduledfilename + "]."); try{//This would also close the file. This is OK since multiple//close operations be Safe.super.setFile (FileName, False, This.bufferedio, this.buffersize);} catch (IOException e) {errorhandler.error ("setfile (" + FileName + ", false) call failed."); Scheduledfilename = Datedfilename;} /** * * <p> * rollover. * */@Overrideprotected void Subappend (Loggingevent event) {Long n = system.currenttimemillis (); if (n >= nextcheck) {now . settime (n); Nextcheck = Rc.getnextcheckmillis (now); Try{timerollover ();} catch (IOException IoE) {loglog.error ("RollOver () failed.", IoE);}} else if ((fileName! = null) && ((Countingquietwriter) QW). GetCount () >= maxfilesize) {sizerollover ();} Super.subappend (event);}}

2.

Rollingcalendar
/** * Project Name:hao24-common * File Name:RollingCalendar.java * Package Name:cn.hao24.util.spring * date:2016 year March 31 AM 1 1:41:34 * Copyright (c), [email protected] All rights Reserved. **/import java.util.calendar;import java.util.date;import Java.util.gregoriancalendar;import Java.util.Locale; Import java.util.timezone;/** * Classname:rollingcalendar <br/> * date:2016 year March 31 morning 11:41:34 <br/> * @aut Hor Lujie * @version * @see */class Rollingcalendar extends gregoriancalendar{private static final long Serialversio nuID = -3560331770601814177l;int type = mydailyrollingfileappender.top_of_trouble; Rollingcalendar () {super ();} Rollingcalendar (TimeZone tz, locale locale) {super (TZ, locale);} void SetType (int type) {this.type = type;} Public long Getnextcheckmillis (Date now) {return getnextcheckdate (now). GetTime ();} Public date getnextcheckdate ("date Now") {This.settime (now), switch (type) {case Mydailyrollingfileappender.top_of_ MINUTE:this.set (Calendar.second, 0); This.set (CaLendar.millisecond, 0); This.add (Calendar.minute, 1); Break;case MyDailyRollingFileAppender.TOP_OF_HOUR:this.set ( Calendar.minute, 0); This.set (Calendar.second, 0); This.set (Calendar.millisecond, 0); This.add (Calendar.hour_of_day, 1); Break;case MyDailyRollingFileAppender.HALF_DAY:this.set (calendar.minute, 0); This.set (Calendar.second, 0); This.set (Calendar.millisecond, 0), int hour = Get (Calendar.hour_of_day), if (Hour <) {This.set (calendar.hour_of_ Day, 12);} Else{this.set (calendar.hour_of_day, 0); This.add (Calendar.day_of_month, 1);} Break;case MyDailyRollingFileAppender.TOP_OF_DAY:this.set (calendar.hour_of_day, 0); This.set (Calendar.minute, 0); This.set (Calendar.second, 0); This.set (Calendar.millisecond, 0); This.add (calendar.date, 1); break;case MyDailyRollingFileAppender.TOP_OF_WEEK:this.set (Calendar.day_of_week, Getfirstdayofweek ()); This.set ( Calendar.hour_of_day, 0); This.set (Calendar.minute, 0); This.set (Calendar.second, 0); This.set (Calendar.millisecond, 0); This.add (calendar.week_of_year, 1); BREak;case MyDailyRollingFileAppender.TOP_OF_MONTH:this.set (calendar.date, 1); This.set (calendar.hour_of_day, 0); This.set (calendar.minute, 0); This.set (Calendar.second, 0); This.set (Calendar.millisecond, 0); This.add ( Calendar.month, 1); Break;default:throw new IllegalStateException ("Unknown periodicity type."); return GetTime ();}}

Then configure the relevant information in the configuration file:

Log4j.appender.r=test. log4jdateandsizesplitlog4j.appender.r.threshold=infolog4j.appender.r.immediateflush=truelog4j.appender.r.file= /xxx.loglog4j.appender.r.datepattern= ' _ ' yyyy-mm-dd '. Log ' log4j.appender.r.append= Truelog4j.appender.r.maxfilesize=200mb#maxbackupindex=-1 (not limit about file number) log4j.appender.r.maxbackupindex=-1log4j.appender.r.layout= org.apache.log4j.patternlayoutlog4j.appender.r.layout.conversionpattern=%d{yyyy-mm-dd HH\:mm \:ss} [%5p]-%c-%F (%L )-%m%n  

  

LOG4J supports simultaneous splitting of logs by date and file size

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.