log4j自动日志删除(转)

本文介绍了如何使用 log4j 和 logback 实现日志自动删除功能,探讨了 DailyRollingFileAppender 的局限性,并提供了一个自定义的 AdvancedDailyRollingFileAppender 示例,支持更灵活的日志保留策略,包括最大日志数量、压缩备份和滚动压缩备份。文章还提到了其他可能的解决方案,如 logback 中的时间基于滚动策略。
摘要由CSDN通过智能技术生成

最近要实现定期删除N天前的日志。 以前都是利用运维的一个cron脚本来定期删除的, 总觉得可移植性不是很好, 比如要指定具体的日志文件路径, 有时候想想为什么log4j自己不实现这个功能呢? 后来发现在logback中已经实现了这个功能. 其配置如下: 

Xml代码   收藏代码
  1. <appender name="vstore"  
  2.      class="ch.qos.logback.core.rolling.RollingFileAppender">  
  3.      <file>default.log</file>  
  4.      <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">  
  5.           <fileNamePattern>./logs/%d/default.log.%d  
  6.           </fileNamePattern>  
  7.           <maxHistory>7</maxHistory>  
  8.      </rollingPolicy>  
  9.   
  10.      <encoder>  
  11.           <pattern>%d{HH:mm:ss.SSS} %level [%thread] %c{0}[%line] %msg%n  
  12.           </pattern>  
  13.      </encoder>  
  14. </appender>  



但是我的应用因为依赖的log相关的jar包的问题, 没法使用logback的jar包, 因为必须使用新的方式来处理. 于是google了一下, 发现老外也遇到了类似的问题. 比如这里是一个解决办法: 
http://stackoverflow.com/questions/1050256/how-can-i-get-log4j-to-delete-old-rotating-log-files 
这个方式是采用的RollingFileAppender, 然后通过设置maxBackupIndex属性来指定要保留的日志的最大值(这里采用一天一个日志).但是我们一直采用的是DailyRollingFileAppender. 可是该appender没有maxBackupIndex这个属性, 于是又google了一把, 发现老外也想到的解决办法, 而且这里有两个解决方法, 即在RollingFileAppender的基础上, 加入了maxBackupIndex属性. 

一种实现方案: 
http://www.zybonics.com/zybocodes/code/CodeViewForm.php?codeID=428 

Java代码   收藏代码
  1. /************************** 
  2. * Zybocodes ******************************* 
  3. * Code For : 
  4. * log4j custom DailyRollingFileAppender - manage your 
  5. * logs:maxBackupIndex zip roll archive logging log management 
  6. * logs 
  7. * Contributor : Ed Sarrazin 
  8. * Ref link : http://jconvert.sourceforge.net 
  9. * For this and other codes/logic under any technology visit: 
  10. * http://www.zybonics.com/zybocodes/ 
  11. ********************************************************************/  
  12.   
  13. /* 
  14. * Licensed to the Apache Software Foundation (ASF) under one or more 
  15. * contributor license agreements. See the NOTICE file distributed with 
  16. * this work for additional information regarding copyright ownership. 
  17. * The ASF licenses this file to You under the Apache License, Version 2.0 
  18. * (the "License"); you may not use this file except in compliance with 
  19. * the License. You may obtain a copy of the License at 
  20. * http://www.apache.org/licenses/LICENSE-2.0 
  21. * Unless required by applicable law or agreed to in writing, software 
  22. * distributed under the License is distributed on an "AS IS" BASIS, 
  23. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
  24. * See the License for the specific language governing permissions and 
  25. * limitations under the License. 
  26. */  
  27. package logger;  
  28.   
  29. import java.io.File;  
  30. import java.io.FileFilter;  
  31. import java.io.FileInputStream;  
  32. import java.io.FileOutputStream;  
  33. import java.io.IOException;  
  34. import java.io.InputStream;  
  35. import java.io.InterruptedIOException;  
  36. import java.text.ParseException;  
  37. import java.text.SimpleDateFormat;  
  38. import java.util.Calendar;  
  39. import java.util.Date;  
  40. import java.util.GregorianCalendar;  
  41. import java.util.Locale;  
  42. import java.util.TimeZone;  
  43. import java.util.zip.ZipEntry;  
  44. import java.util.zip.ZipInputStream;  
  45. import java.util.zip.ZipOutputStream;  
  46.   
  47. import org.apache.log4j.FileAppender;  
  48. import org.apache.log4j.Layout;  
  49. import org.apache.log4j.helpers.LogLog;  
  50. import org.apache.log4j.spi.LoggingEvent;  
  51.   
  52. /** 
  53. * @author Ed Sarrazin 
  54. *  <pre> 
  55. *  AdvancedDailyRollingFileAppender is a copy of apaches DailyRollingFileAppender.  This copy was made because it could not be extended due to package level access.  This new version will allow two new properties to be set: 
  56. *  MaxNumberOfDays:            Max number of log files to keep, denoted in days.  If using compression, this days should be longer than 
  57. *  -                           CompressBackupsAfterDays and will become irrelevant as files will be moved to archive before this time. 
  58. *  CompressBackups:            Indicating if older log files should be backed up to a compressed format. 
  59. *  RollCompressedBackups:      TURE/FALSE indicating that compressed backups should be rolled out (deleted after certain age) 
  60. *  CompressBackupsAfterDays:   Number of days to wait until adding files to compressed backup. (Files that are compressed are deleted) 
  61. *  CompressBackupsDatePattern: example - "'.'yyyy-MM" - this will create compressed backups grouped by pattern.  In this example, every month 
  62. *  CompressMaxNumberDays:      Number of days to keep compressed backups.  RollCompressedBackups must be true. 
  63.  
  64. *  Here is a listing of the log4j.properties file you would use: 
  65.  
  66. *  log4j.appender.RootAppender=com.edsdev.log4j.AdvancedDailyRollingFileAppender 
  67. *  log4j.appender.RootAppender.DatePattern='.'yyyyMMdd 
  68. *  log4j.appender.RootAppender.MaxNumberOfDays=60 
  69. *  log4j.appender.RootAppender.CompressBackups=true 
  70. *  log4j.appender.RootAppender.CompressBackupsAfterDays=31 
  71. *  log4j.appender.RootAppender.CompressBackupsDatePattern='.'yyyyMM 
  72. *  log4j.appender.RootAppender.RollCompressedBackups=true 
  73. *  log4j.appender.RootAppender.CompressMaxNumberDays=365 
  74.  
  75. *  </pre> 
  76. * AdvancedDailyRollingFileAppender extends {@link FileAppender} so that the underlying file is rolled over at a user 
  77. * chosen frequency. AdvancedDailyRollingFileAppender has been observed to exhibit synchronization issues and data loss. 
  78. * The log4j extras companion includes alternatives which should be considered for new deployments and which are 
  79. * discussed in the documentation for org.apache.log4j.rolling.RollingFileAppender. 
  80. * <p> 
  81. * The rolling schedule is specified by the <b>DatePattern</b> option. This pattern should follow the 
  82. * {@link SimpleDateFormat} conventions. In particular, you <em>must</em> escape literal text within a pair of single 
  83. * quotes. A formatted version of the date pattern is used as the suffix for the rolled file name. 
  84. * <p> 
  85. * For example, if the <b>File</b> option is set to <code>/foo/bar.log</code> and the <b>DatePattern</b> set to 
  86. * <code>'.'yyyy-MM-dd</code>, on 2001-02-16 at midnight, the logging file <code>/foo/bar.log</code> will be copied 
  87. * to <code>/foo/bar.log.2001-02-16</code> and logging for 2001-02-17 will continue in <code>/foo/bar.log</code> 
  88. * until it rolls over the next day. 
  89. * <p> 
  90. * Is is possible to specify monthly, weekly, half-daily, daily, hourly, or minutely rollover schedules. 
  91. * <p> 
  92. * <table border="1" cellpadding="2"> 
  93. * <tr> 
  94. * <th>DatePattern</th> 
  95. * <th>Rollover schedule</th> 
  96. * <th>Example</th> 
  97. * <tr> 
  98. * <td><code>'.'yyyy-MM</code> 
  99. * <td>Rollover at the beginning of each month</td> 
  100. * <td>At midnight of May 31st, 2002 <code>/foo/bar.log</code> will be copied to <code>/foo/bar.log.2002-05</code>. 
  101. * Logging for the month of June will be output to <code>/foo/bar.log</code> until it is also rolled over the next 
  102. * month. 
  103. * <tr> 
  104. * <td><code>'.'yyyy-ww</code> 
  105. * <td>Rollover at the first day of each week. The first day of the week depends on the locale.</td> 
  106. * <td>Assuming the first day of the week is Sunday, on Saturday midnight, June 9th 2002, the file <i>/foo/bar.log</i> 
  107. * will be copied to <i>/foo/bar.log.2002-23</i>. Logging for the 24th week of 2002 will be output to 
  108. * <code>/foo/bar.log</code> until it is rolled over the next week. 
  109. * <tr> 
  110. * <td><code>'.'yyyy-MM-dd</code> 
  111. * <td>Rollover at midnight each day.</td> 
  112. * <td>At midnight, on March 8th, 2002, <code>/foo/bar.log</code> will be copied to 
  113. * <code>/foo/bar.log.2002-03-08</code>. Logging for the 9th day of March will be output to <code>/foo/bar.log</code> 
  114. * until it is rolled over the next day. 
  115. * <tr> 
  116. * <td><code>'.'yyyy-MM-dd-a</code> 
  117. * <td>Rollover at midnight and midday of each day.</td> 
  118. * <td>At noon, on March 9th, 2002, <code>/foo/bar.log</code> will be copied to 
  119. * <code>/foo/bar.log.2002-03-09-AM</code>. Logging for the afternoon of the 9th will be output to 
  120. * <code>/foo/bar.log</code> until it is rolled over at midnight. 
  121. * <tr> 
  122. * <td><code>'.'yyyy-MM-dd-HH</code> 
  123. * <td>Rollover at the top of every hour.</td> 
  124. * <td>At approximately 11:00.000 o'clock on March 9th, 2002, <code>/foo/bar.log</code> will be copied to 
  125. * <code>/foo/bar.log.2002-03-09-10</code>. Logging for the 11th hour of the 9th of March will be output to 
  126. * <code>/foo/bar.log</code> until it is rolled over at the beginning of the next hour. 
  127. * <tr> 
  128. * <td><code>'.'yyyy-MM-dd-HH-mm</code> 
  129. * <td>Rollover at the beginning of every minute.</td> 
  130. * <td>At approximately 11:23,000, on March 9th, 2001, <code>/foo/bar.log</code> will be copied to 
  131. * <code>/foo/bar.log.2001-03-09-10-22</code>. Logging for the minute of 11:23 (9th of March) will be output to 
  132. * <code>/foo/bar.log</code> until it is rolled over the next minute. </table> 
  133. * <p> 
  134. * Do not use the colon ":" character in anywhere in the <b>DatePattern</b> option. The text before the colon is 
  135. * interpeted as the protocol specificaion of a URL which is probably not what you want. 
  136. * @author Eirik Lygre 
  137. * @author Ceki Gülcü 
  138. */  
  139. public class AdvancedDailyRollingFileAppender extends FileAppender {  
  140.   
  141.     // The code assumes that the following constants are in a increasing  
  142.     // sequence.  
  143.     static final int TOP_OF_TROUBLE = -1;  
  144.     static final int TOP_OF_MINUTE = 0;  
  145.     static final int TOP_OF_HOUR = 1;  
  146.     static final int HALF_DAY = 2;  
  147.     static final int TOP_OF_DAY = 3;  
  148.     static final int TOP_OF_WEEK = 4;  
  149.     static final int TOP_OF_MONTH = 5;  
  150.   
  151.     /** Indicates if log files should be moved to archive file */  
  152.     private String compressBackups = "false";  
  153.     /** Indicates if archive file that may be created will be rolled off as it ages */  
  154.     private String rollCompressedBackups = "false";  
  155.     /** Maximum number of days to keep log files */  
  156.     private int maxNumberOfDays = 31;  
  157.     /** Number of days to wait before moving a log file to an archive */  
  158.     private int compressBackupsAfterDays = 31;  
  159.     /** Pattern used to name archive file (also controls what log files are grouped together */  
  160.     private String compressBackupsDatePattern = "'.'yyyy-MM";  
  161.     /** Maximum number of days to keep archive file before deleting */  
  162.     private int compressMaxNumberDays = 365;  
  163.   
  164.     /** 
  165.      * The date pattern. By default, the pattern is set to "'.'yyyy-MM-dd" meaning daily rollover. 
  166.      */  
  167.     private String datePattern = "'.'yyyy-MM-dd";  
  168.   
  169.     /** 
  170.      * The log file will be renamed to the value of the scheduledFilename variable when the next interval is entered. 
  171.      * For example, if the rollover period is one hour, the log file will be renamed to the value of "scheduledFilename" 
  172.      * at the beginning of the next hour. The precise time when a rollover occurs depends on logging activity. 
  173.      */  
  174.     private String scheduledFilename;  
  175.   
  176.     /** 
  177.      * The next time we estimate a rollover should occur. 
  178.      */  
  179.     private long nextCheck = System.currentTimeMillis() - 1;  
  180.   
  181.     Date now = new Date();  
  182.   
  183.     SimpleDateFormat sdf;  
  184.   
  185.     RollingCalendar rc = new RollingCalendar();  
  186.   
  187.     int checkPeriod = TOP_OF_TROUBLE;  
  188.   
  189.     // The gmtTimeZone is used only in computeCheckPeriod() method.  
  190.     static final TimeZone gmtTimeZone = TimeZone.getTimeZone("GMT");  
  191.   
  192.     /** 
  193.      * The default constructor does nothing. 
  194.      */  
  195.     public AdvancedDailyRollingFileAppender() {  
  196.     }  
  197.   
  198.     /** 
  199.      * Instantiate a <code>AdvancedDailyRollingFileAppender</code> and open the file designated by 
  200.      * <code>filename</code>. The opened filename will become the ouput destination for this appender. 
  201.      */  
  202.     public AdvancedDailyRollingFileAppender(Layout layout, String filename, String datePattern) throws IOException {  
  203.         super(layout, filename, true);  
  204.         this.datePattern = datePattern;  
  205.         activateOptions();  
  206.     }  
  207.   
  208.     /** 
  209.      * The <b>DatePattern</b> takes a string in the same format as expected by {@link SimpleDateFormat}. This options 
  210.      * determines the rollover schedule. 
  211.      */  
  212.     public void setDatePattern(String pattern) {  
  213.         datePattern = pattern;  
  214.     }  
  215.   
  216.     /** Returns the value of the <b>DatePattern</b> option. */  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值