ITeye博客

Log4j生成压缩形式日志

java_2007 · 2014-05-26 11:14 · Log4j · 开源软件 · Markdown

Log4j生成压缩形式日志

转:http://blog.csdn.net/zhaosen241/article/details/3248331

 

Log4j提供了强大的日志功能,但是只能生成文本形式的日志文件,对于输出日志很频繁的应用会产生一些资源的浪费,例如我们的一个项目平均每20分钟就会生成一个大约10M的日志文件。为了节约硬盘资源,最近几天修改了一下Log4j,做了一个自己的版本将日志文件做成压缩包。

 

记录下这几天的工作吧:

 

1.       下载Log4j 1.2.15源代码,链接是:http://logging.apache.org/log4j/1.2/download.html

下载apache-log4j-1.2.15.tar.gz是带有源代码的包

 

2.       Log4j是用Maven2打包的,在链接http://maven.apache.org/download.html中下载

apache-maven-2.1.0-M1-bin.zip,这里需要注意下,2.0.9中有bug,打包会失败。

下载Maven后需要配置一下环境变量,就不细说了。

 

3.       下载安装MinGW,用来构建NTEventLogAppender.dll。下载链接:

http://mmtele3.skycn.com/down/MinGWStudioFullSetup-2_05.exe

 

4.       用Maven打包Log4j工程没问题后就可以开始修改里面的源代码了。在前一篇blog中转载了关于log4j的详细信息,我们主要更改两种方式的log,一种是DailyRollingFileAppender,一种是RollingFileAppender。

DailyRollingFileAppender在往日志文件打log的时候会检测日志文件上次修改的时间,如

果系统当前时间与上次修改时间不是一天,则将日志文件重新命名,在生成一个新的日志文件,例如日志文件是log.log,检测上次修改时间早于当天,则将log.log重命名为log.log.2008-11-7,并将log.log清空来打新的日志,其中2008-11-7是有配置文件指定的。

         RollingFileAppender在往日志文件打log的时候会根据配置文件设置的最大文件大小来与当前日志文件做比较,如果比文件大时,则将log文件重命名,规则为:根据最大日志备份个数做备份,例如最大日志备份个数设置为3,则将log.log更名为log.log.1、log.log.2、log.log.3、每次会判断这三个文件是否存在,如果存在,则将后缀最大的那个删掉,往后顺移一个,将log.log放到log.log.1中。

 

5.       现在需要做的就是将这两种方式的操作做一下修改。

DailyRollingFileAppender在判断需要将log.log重命名为log.log.2008-11-7时,我们将重命名这个操作改成将log.log打到zip包里面即可;同理,RollingFileAppender也是将文件重命名的操作改成打zip包。

 

6.       实现中主要需要修改两个类中的两个方法,相关代码如下:

DailyRollingFileAppender.java

修改方法rollOver

  

  1. void rollOver() throws IOException {
  2. // Compute filename, but only if datePattern is specified
  3. if (datePattern == null) {
  4. errorHandler.error("Missing DatePattern option in rollOver().");
  5. return;
  6. }
  7. String datedFilename = fileName+sdf.format(now);
  8. // It is too early to roll over because we are still within the
  9. // bounds of the current interval. Rollover will occur once the
  10. // next interval is reached.
  11. if (scheduledFilename.equals(datedFilename)) {
  12. return;
  13. }
  14. // close current file, and rename it to datedFilename
  15. this.closeFile();
  16. File target  = new File(scheduledFilename + ".zip");
  17. if (target.exists()) {
  18. target.delete();
  19. }
  20. //log old file
  21. File file = new File(fileName);
  22. //creat zip output stream to build zip file
  23. ZipOutputStream out = null;
  24. FileInputStream fin = null;
  25. byte[] buf = new byte[1024];
  26. //file -> zip
  27. try{
  28. fin = new FileInputStream(file);
  29. out = new ZipOutputStream(new FileOutputStream(scheduledFilename + ".zip"));
  30. out.putNextEntry(new ZipEntry(file.getPath()));
  31. LogLog.debug(fileName + " -> " + scheduledFilename + ".zip");
  32. int len;
  33. while ((len = fin.read(buf)) > 0) {
  34. out.write(buf, 0, len);
  35. }
  36. out.closeEntry();
  37. fin.close();
  38. LogLog.debug(fileName + " -> " + scheduledFilename + ".zip successful!");
  39. }catch(IOException e) {
  40. errorHandler.error("add zip file("+scheduledFilename+") failed.");
  41. }
  42. finally{
  43. if (out != null) {
  44. out.closeEntry();
  45. out.close();
  46. }
  47. if (fin != null)
  48. fin.close();
  49. }
  50. //delete old file
  51. file.delete();
  52. try {
  53. // This will also close the file. This is OK since multiple
  54. // close operations are safe.
  55. this.setFile(fileName, true, this.bufferedIO, this.bufferSize);
  56. }
  57. catch(IOException e) {
  58. errorHandler.error("setFile("+fileName+", true) call failed.");
  59. }
  60. scheduledFilename = datedFilename;
  61. }

 

RollingFileAppender.java

同样是修改rollOver方法:

  1. public// synchronization not necessary since doAppend is alreasy synched
  2. void rollOver() {
  3. File target;
  4. File file;
  5. if (qw != null) {
  6. long size = ((CountingQuietWriter) qw).getCount();
  7. LogLog.debug("rolling over count=" + size);
  8. // if operation fails, do not roll again until
  9. // maxFileSize more bytes are written
  10. nextRollover = size + maxFileSize;
  11. }
  12. LogLog.debug("maxBackupIndex=" + maxBackupIndex);
  13. boolean renameSucceeded = true;
  14. // If maxBackups <= 0, then there is no file renaming to be done.
  15. if (maxBackupIndex > 0) {
  16. // Delete the oldest file, to keep Windows happy.
  17. file = new File(fileName + maxBackupIndex + ".zip");
  18. if (file.exists())
  19. renameSucceeded = file.delete();
  20. // Map {(maxBackupIndex - 1), ..., 2, 1} to {maxBackupIndex, ..., 3,
  21. // 2}
  22. for (int i = maxBackupIndex - 1; i >= 1 && renameSucceeded; i--) {
  23. file = new File(fileName + i + ".zip");
  24. if (file.exists()) {
  25. target = new File(fileName + (i + 1) + ".zip");
  26. LogLog.debug("Renaming file " + file + " to " + target);
  27. renameSucceeded = file.renameTo(target);
  28. }
  29. }
  30. if (renameSucceeded) {
  31. // zip fileName to fileName1.zip
  32. this.closeFile(); // keep windows happy.
  33. file = new File(fileName);
  34. // LogLog.debug("compress file " + file + " to " + target);
  35. ZipOutputStream out = null;
  36. FileInputStream fin = null;
  37. byte[] buf = new byte[8192];
  38. try {
  39. //create zip out put stream to build zip file
  40. fin = new FileInputStream(file);
  41. out = new ZipOutputStream(new FileOutputStream(fileName
  42. + 1 + ".zip"));
  43. out.putNextEntry(new ZipEntry(file.getPath()));
  44. LogLog.debug(fileName + " -> " + fileName + 1
  45. + ".zip");
  46. int len;
  47. while ((len = fin.read(buf)) > 0) {
  48. out.write(buf, 0, len);
  49. }
  50. out.closeEntry();
  51. fin.close();
  52. LogLog.debug(fileName + " -> " + fileName + 1
  53. + ".zip successful!");
  54. file.delete();
  55. } catch (IOException e) {
  56. errorHandler.error("add zip file(" + fileName + 1
  57. + ".zip) failed.");
  58. }finally{
  59. try {
  60. if (out != null) {
  61. out.closeEntry();
  62. out.close();
  63. }
  64. if (fin != null)
  65. fin.close();
  66. } catch (IOException e) {
  67. // TODO Auto-generated catch block
  68. errorHandler.error("close out and fin failed.");
  69. }
  70. }
  71. // if file compress failed, reopen file with append = true
  72. //
  73. if (!renameSucceeded) {
  74. try {
  75. this.setFile(fileName, true, bufferedIO, bufferSize);
  76. } catch (IOException e) {
  77. if (e instanceof InterruptedIOException) {
  78. Thread.currentThread().interrupt();
  79. }
  80. LogLog.error("setFile(" + fileName
  81. + ", true) call failed.", e);
  82. }
  83. }
  84. }
  85. }
  86. //
  87. // if all renames were successful, then
  88. //
  89. if (renameSucceeded) {
  90. try {
  91. // This will also close the file. This is OK since multiple
  92. // close operations are safe.
  93. this.setFile(fileName, false, bufferedIO, bufferSize);
  94. nextRollover = 0;
  95. } catch (IOException e) {
  96. if (e instanceof InterruptedIOException) {
  97. Thread.currentThread().interrupt();
  98. }
  99. LogLog
  100. .error("setFile(" + fileName + ", false) call failed.",
  101. e);
  102. }
  103. }
  104. }

 

7.       最后,由于打zip包的时候用到了Ant中的zip代码,下载带源代码的Ant包,链接是

http://archive.apache.org/dist/ant/source/apache-ant-1.6.5-src.zip 。将里面zip的类放入log4j工程中,并用refactor将包重命名到org.apache.log4j中。

 

 

PS:这样做肯定会影响Log4j对输出日志的性能的影响,需要做进一步的性能方面的测试。

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。