---
title: " Log4j生成压缩形式日志"
author: "java_2007"
date: "2014-05-26T11:14:54Z"
tags: []
categories: ["开源软件"]
slug: "log4j"
draft: false
lastmod: "2014-05-26T11:14:54Z"
id: 2071095
url: "https://java-2007.iteye.com/blog/2071095"
---

Log4j生成压缩形式日志

转：[http://blog.csdn.net/zhaosen241/article/details/3248331](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](http://logging.apache.org/log4j/1.2/download.html)

下载[apache-log4j-1.2.15.tar.gz](http://www.apache.org/dyn/closer.cgi/logging/log4j/1.2.15/apache-log4j-1.2.15.tar.gz)是带有源代码的包

 

2.       Log4j是用Maven2打包的，在链接[http://maven.apache.org/download.html](http://maven.apache.org/download.html)中下载

[apache-maven-2.1.0-M1-bin.zip](http://www.apache.org/dyn/closer.cgi/maven/binaries/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](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

  

01. void rollOver() throws IOException {
02. // Compute filename, but only if datePattern is specified
03. if (datePattern == null) {
04. errorHandler.error("Missing DatePattern option in rollOver().");
05. return;
06. }
07. String datedFilename = fileName+sdf.format(now);
08. // It is too early to roll over because we are still within the
09. // 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 -&gt; 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 + " -&gt; " + scheduledFilename + ".zip");
32. int len;
33. while ((len = fin.read(buf)) &gt; 0) {
34. out.write(buf, 0, len);
35. }
36. out.closeEntry();
37. fin.close();
38. LogLog.debug(fileName + " -&gt; " + 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方法：

001. public// synchronization not necessary since doAppend is alreasy synched
002. void rollOver() {
003. File target;
004. File file;
005. if (qw != null) {
006. long size = ((CountingQuietWriter) qw).getCount();
007. LogLog.debug("rolling over count=" + size);
008. // if operation fails, do not roll again until
009. // maxFileSize more bytes are written
010. nextRollover = size + maxFileSize;
011. }
012. LogLog.debug("maxBackupIndex=" + maxBackupIndex);
013. boolean renameSucceeded = true;
014. // If maxBackups &lt;= 0, then there is no file renaming to be done.
015. if (maxBackupIndex &gt; 0) {
016. // Delete the oldest file, to keep Windows happy.
017. file = new File(fileName + maxBackupIndex + ".zip");
018. if (file.exists())
019. renameSucceeded = file.delete();
020. // Map {(maxBackupIndex - 1), ..., 2, 1} to {maxBackupIndex, ..., 3,
021. // 2}
022. for (int i = maxBackupIndex - 1; i &gt;= 1 && renameSucceeded; i--) {
023. file = new File(fileName + i + ".zip");
024. if (file.exists()) {
025. target = new File(fileName + (i + 1) + ".zip");
026. LogLog.debug("Renaming file " + file + " to " + target);
027. renameSucceeded = file.renameTo(target);
028. }
029. }
030. if (renameSucceeded) {
031. // zip fileName to fileName1.zip
032. this.closeFile(); // keep windows happy.
033. file = new File(fileName);
034. // LogLog.debug("compress file " + file + " to " + target);
035. ZipOutputStream out = null;
036. FileInputStream fin = null;
037. byte\[] buf = new byte\[8192];
038. try {
039. //create zip out put stream to build zip file
040. fin = new FileInputStream(file);
041. out = new ZipOutputStream(new FileOutputStream(fileName
042. + 1 + ".zip"));
043. out.putNextEntry(new ZipEntry(file.getPath()));
044. LogLog.debug(fileName + " -&gt; " + fileName + 1
045. + ".zip");
046. int len;
047. while ((len = fin.read(buf)) &gt; 0) {
048. out.write(buf, 0, len);
049. }
050. out.closeEntry();
051. fin.close();
052. LogLog.debug(fileName + " -&gt; " + fileName + 1
053. + ".zip successful!");
054. file.delete();
055. } catch (IOException e) {
056. errorHandler.error("add zip file(" + fileName + 1
057. + ".zip) failed.");
058. }finally{
059. try {
060. if (out != null) {
061. out.closeEntry();
062. out.close();
063. }
064. if (fin != null)
065. fin.close();
066. } catch (IOException e) {
067. // TODO Auto-generated catch block
068. errorHandler.error("close out and fin failed.");
069. }
070. }
071. // if file compress failed, reopen file with append = true
072. //
073. if (!renameSucceeded) {
074. try {
075. this.setFile(fileName, true, bufferedIO, bufferSize);
076. } catch (IOException e) {
077. if (e instanceof InterruptedIOException) {
078. Thread.currentThread().interrupt();
079. }
080. LogLog.error("setFile(" + fileName
081. + ", true) call failed.", e);
082. }
083. }
084. }
085. }
086. //
087. // if all renames were successful, then
088. //
089. if (renameSucceeded) {
090. try {
091. // This will also close the file. This is OK since multiple
092. // close operations are safe.
093. this.setFile(fileName, false, bufferedIO, bufferSize);
094. nextRollover = 0;
095. } catch (IOException e) {
096. if (e instanceof InterruptedIOException) {
097. Thread.currentThread().interrupt();
098. }
099. 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](http://archive.apache.org/dist/ant/source/apache-ant-1.6.5-src.zip%20%E3%80%82%E5%B0%86%E9%87%8C%E9%9D%A2zip%E7%9A%84%E7%B1%BB%E6%94%BE%E5%85%A5log4j)工程中，并用refactor将包重命名到org.apache.log4j中。

 

 

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