一个月前因为某些事情被困宁波三天,在酒店里闲着无事,然后开始看log4j的源码。原本之后的一个星期就应该开始写了,无奈又遇到一些事情,迟迟没有动笔。感觉工作后要做好一件额外的事情总是很难,每天下班后才能看代码、写文章,而如果中途遇到一些没有预料到的事情就很容易不了了之了,所以现在如果出现能静下心来看代码、写文章的时间,我都是特别珍惜。我一直不知道如何开场一篇文章,所以先用一些废话做引子….:(
在软件开发过程中,出现bug总是在所难免;事实上,以我个人经验,即使在实际开发阶段,fix bug时间要远超过写代码的时间。在开发阶段,比较有效的fix bug的方法当然是调试,然而如果代码比较复杂,而且开始对代码不是很熟悉,那么我们很容易在方法调用之间迷失方向;如果bug出现在多线程环境中,那么很多时候调试就无能为力了;另外当代码部署到服务器上运行时,不管是在uat测试环境还是production环境,此时要调试很多时候是不可能。为了解决这些问题,我们可以在开发过程中事先在一些关键点上打印出一些日志信息(log),以利于在出问题后能知道当时运行的环境信息,特别是在production上,我们可以分析log以确定问题所在,当然前提log信息足够多。不过加入日志信息后,不难想象,它会对程序的运行性能产生一定的影响,而且如果log过多会导致有用的信息不容易找到,如果过少又不具备很大的参考价值,这样的日志除了降低程序的性能,貌似对其他方面没有帮助。关于性能,log4j号称在这面做了很多优化,但是据说logback做的更好(logback的源码还没来得及看,而且也没用过,所以还不是很了解);而关于如何写log、在哪里写log、要把那些信息写入log中,个人感觉这是一门很大的学问,而且也是根据不同项目而不同,而本人也还没有达到那种可以列出一些比较详细的指导点,因而本文将不会涉及到这方面,本文主要从源码角度关注log4j是如何实现的。
以下将用循序渐进的方式来讲解简单的日志类实现,并最后引出log4j日志系统的核心实现。
最简单的logging功能实现,我想应该就是直接使用system.out.println()将需要的信息打印到控制台中了:
1 @test
2 public void testbasic() {
3 system.out.println("begin to execute testbasic() method
");
4
5 system.out.println("executing
6 try {
7 throw new exception("deliberately throw an exception
8 } catch(exception e) {
9 system.out.println("catching an exception: " + e.getmessage());
10 e.printstacktrace(system.out);
11 }
12
13 system.out.println("execute testbasic() method finished.");
14 }
这种方法最大的好处就是简单方便,而且不用引入第三方的依赖包。而它的功能自然也是最弱的:
1. 首先它只能将日志信息打印到控制台;
2. 它不支持分类日志信息,有些日志只是用于调试信息,在上production后不可以打印出来;而另一些日志信息则是包含一些重要信息,需要再production现实出来;有些时候为了进一步提升程序运行性能或者部署者认为系统已经很稳定了,日志信息并不是很重要,因而只需要打印错误信息、甚至关闭日志功能,在这种情况下,用这种方法就会非常麻烦。
3. 每一句日志记录中可能包含一些相似的信息,如日志级别、日志记录打印时间、日志记录对应的类等信息,如果要实现这种功能,则会出现很多重复代码。
4. 很多时候,我们希望保留日志,以备日后分析、审查用,随着日志信息的不断积累,我们并不希望所有的日志文件都在同一个文件中,而是希望日志文件能够根据一定的规则自动的切换使用新的文件。
封装是面向对象的三大特性之一,它把对象的数据和行为聚合在一起,只提供给外界需要的接口,以提高代码的可重用性、降低代码之间的耦合、进而也增加代码的内聚性。因而对上述直接打印日志到控制台的一个简单的重构即是将打印日志的代码都提取到一个简单的日志类中:simplelog1。
simplelog1也是将日志直接打印到控制台,但是它引入了日志级别(level,或类别)的支持:trace、debug、info、warn、error、fatal、all、off;另外,它也会自动的在每一条日志记录之前加入日志级别、日志名称、日志消息、异常堆栈等信息。
1 public class simplelog1 {
2 public static final int log_level_trace = 1;
3 public static final int log_level_debug = 2;
4 public static final int log_level_info = 3;
5 public static final int log_level_warn = 4;
6 public static final int log_level_error = 5;
7 public static final int log_level_fatal = 6;
8 public static final int log_level_all = (log_level_trace - 1);
9 public static final int log_level_off = (log_level_fatal + 1);
10
11 private final string name;
12 private final int level;
13 public simplelog1(string name, int level) {
14 this.name = name;
15 this.level = level;
16 }
17 public simplelog1(class<?> cls, int level) {
18 this(cls.getname(), level);
19 }
20 public void trace(string message) {
21 trace(message, null);
22 }
23 public void trace(string message, throwable cause) {
24 log(log_level_trace, message, cause);
25 }
26 public boolean istraceenabled() {
27 return islevelenabled(log_level_trace);
28 }
29
30 private void log(int type, string message, throwable cause) {
31 if(!islevelenabled(type)) {
32 return;
33 }
34 stringbuilder builder = new stringbuilder(32);
35
36 putlevelstring(builder, type);
37 putlogname(builder, name);
38 builder.append(message);
39 if(cause != null) {
40 putcauseinfo(builder, cause);
41 }
42
43 writelog(builder);
44 }
45 private void putlevelstring(stringbuilder builder, int type) {
46 switch(type) {
47 case simplelog1.log_level_trace:
48 builder.append("[trace] "); break;
49 case simplelog1.log_level_debug:
50 builder.append("[debug] "); break;
51 case simplelog1.log_level_info:
52 builder.append("[info] "); break;
53 case simplelog1.log_level_warn:
54 builder.append("[warn] "); break;
55 case simplelog1.log_level_error:
56 builder.append("[error] "); break;
57 case simplelog1.log_level_fatal:
58 builder.append("[fatal] "); break;
59 }
60 }
61 private void putlogname(stringbuilder builder, string name) {
62 builder.append(name);
63 builder.append("-");
64 }
65 private void putcauseinfo(stringbuilder builder, throwable cause) {
66 builder.append("<");
67 builder.append(cause.getmessage());
68 builder.append(">");
69 builder.append(system.getproperty("line.separator"));
70
71 stringwriter writer = new stringwriter();
72 printwriter printer = new printwriter(writer);
73 cause.printstacktrace(printer);
74 printer.close();
75 builder.append(writer.tostring());
76 }
77 private void writelog(stringbuilder builder) {
78 system.out.println(builder.tostring());
79 }
80 private boolean islevelenabled(int level) {
81 if(level >= this.level) {
82 return true;
83 }
84 return false;
85 }
86 }
将打印日志封装成一个类并支持不同级别的日志打印信息后,打印日志的代码看起来更合理一些了,而且也可以为每一条日志记录加入一些共同的信息了,如日志级别、日志名称等:
2 public void testsimplelog1() {
3 simplelog1 log = new simplelog1("levin.commons.logging.test.testbasic",
4 simplelog1.log_level_debug);
5 log.info("begin to execute testbasic() method
6
7 log.info("executing
8
9 try {
10 throw new exception("deliberately throw an exception
11 } catch(exception e) {
12 log.error("catching an exception", e);
13 }
14
15 log.info("execute testbasic() method finished.");
然而上述的日志类simplelog1还是太简单了,它需要为每个日志打印实例指定日志级别、不支持打印日志到文件、不能方便的配置每条日志记录的共同信息。因而我们还需要支持可配置的日志类。
虽然日志功能在应用程序开发中是一个非常重要的部件,有些时候日志信息的好坏可以直接影响程序开发的进度。然而日志本身不涉及到任何业务逻辑,因而需要尽量减少它的侵入性,也就说它提供的接口应该尽量的简单。为了实现接口的简单性,其中一种方法就是使用配置文件记录simplelog2的配置信息,simplelog2则根据配置信息初始化每一个simplelog2实例。这些配置信息包括是否显示日志名称、时间信息;如果显示日志打印时间,其格式如何;默认的日志级别是什么;支持单独配置一些日志名称的日志级别;如果将日志打印到日志文件,则日志文件的名称和目录在哪里等信息。
1 public class simplelog2 {
2
3 private static final string prop_prefix = "levin.commons.logging.simplelog.";
4 private static final string prop_log_prefix = prop_prefix + "log.";
5 private static final string default_data_format = "yyyy-mm-dd hh:mm:ss,sss zzz";
6 private static final string default_level = "debug";
7
8 private static simpledateformat dateformat = null;
9 private static boolean showlogname = true;
10 private static boolean showshortname = false;
11 private static boolean showdateinfo = false;
12 private static boolean flush = true;
13 private static int rootlevel;
14 private static map<string, integer> configlevels;
15 private static printstream out;
16
17 static {
18 inputstream in = getconfiginputstream("simplelog.properties");
19 properties props = new properties();
20 if(in != null) {
21 try {
22 props.load(in);
23 in.close();
24 } catch(ioexception e) {
25 // ignored
26 }
27 }
28 // put all system properties
29 props.putall(system.getproperties());
30
31 showlogname = getbooleanproperty(props, prop_prefix + "showlogname", "true");
32 showshortname = getbooleanproperty(props, prop_prefix + "showshortname", "false");
33 showdateinfo = getbooleanproperty(props, prop_prefix + "showdateinfo", "false");
34 string dateformatstr = getproperty(props, prop_prefix + "dateformat", default_data_format);
35 dateformat = new simpledateformat(dateformatstr);
36 rootlevel = tointegerlevel(getproperty(props, prop_prefix + "root.level", default_level));
37 configlevels = parseconfiglevels(props);
38 string logfile = getproperty(props, prop_prefix + "logfile", "");
39 boolean append = getbooleanproperty(props, prop_prefix + "logfile.append", "true");
40 out = getprintstream(logfile, append);
41 flush = getbooleanproperty(props, prop_prefix + "logfile.flush", "true");
42
43 // add shutdown hook
44 runtime runtime = runtime.getruntime();
45 runtime.addshutdownhook(new thread() {
46 @override
47 public void run() {
48 try {
49 shutdown();
50 } catch(exception e) {
51 system.err.println("shutdown simplelog2 application failed.");
52 e.printstacktrace(system.err);
53 }
54 }
55 });
56 }
57 private static map<string, integer> parseconfiglevels(properties props) {
58 map<string, integer> map = new treemap<string, integer>();
59 for(string key : props.stringpropertynames()) {
60 if(key != null && key.startswith(prop_log_prefix)) {
61 string loglevelvalue = props.getproperty(key);
62 string logname = parselogname(key);
63 map.put(logname, tointegerlevel(loglevelvalue));
64 }
65 }
66 return map;
67 }
68 private static string parselogname(string lognamekey) {
69 return lognamekey.substring(prop_log_prefix.length());
70 }
71 private static printstream getprintstream(string logfile, boolean append) {
72 if(logfile == null || logfile.isempty()) {
73 return system.out;
74 }
75
76 printstream out = null;
77 try {
78 out = new printstream(new fileoutputstream(logfile, append));
79 } catch(ioexception e) {
80 system.err.println("error while create logfile[" +
81 logfile + " printstream: " + e.getmessage());
82 system.err.println("output log info to console by default");
83 return system.out;
84 }
85
86 return out;
87 }
88 private static synchronized void writelog(stringbuilder builder) {
89 out.println(builder.tostring());
90 if(flush) {
91 out.flush();
92 }
93 }
94 private static inputstream getconfiginputstream(string configname) {
95 classloader classloader = getcontextclassloader();
96 inputstream in = classloader.getresourceasstream(configname);
97 if(in == null) {
98 in = simplelog2.class.getclassloader().getresourceasstream(configname);
99 }
100 if(in == null) {
101 in = simplelog2.class.getresourceasstream(configname);
102 }
103 return in;
104 }
105 private static classloader getcontextclassloader() {
106 return thread.currentthread().getcontextclassloader();
107 }
108 private string name;
109 private int level;
110 private string shortname;
111
112 public simplelog2(string name) {
113 this.name = name;
114 this.level = getloglevel(name);
115 }
116 public simplelog2(class<?> cls) {
117 this(cls.getname());
118 }
119 public void setlevel(int level) {
120 this.level = level;
121 }
122 public void trace(string message) {
123 trace(message, null);
124 }
125 public void trace(string message, throwable cause) {
126 log(log_level_trace, message, cause);
127 }
128 public boolean istraceenabled() {
129 return islevelenabled(log_level_trace);
130 }
131
132 private int getloglevel(string logname) {
133 if(configlevels == null || configlevels.isempty()) {
134 return rootlevel;
135 }
136 int loglevel = -1;
137 for(string name : configlevels.keyset()) {
138 if(logname.startswith(name)) {
139 loglevel = configlevels.get(name);
140 }
141 }
142 if(loglevel == -1) {
143 loglevel = rootlevel;
144 }
145 return loglevel;
146 }
147 private void log(int type, string message, throwable cause) {
148 if(!islevelenabled(type)) {
149 return;
150 }
151
152 stringbuilder builder = new stringbuilder(32);
153
154 putdateinfo(builder);
155 putlevelstring(builder, type);
156 putlogname(builder, name);
157 builder.append(message);
158 putcauseinfo(builder, cause);
159
160 writelog(builder);
161 }
162 private void putdateinfo(stringbuilder builder) {
163 if(showdateinfo) {
164 date date = new date();
165 string datestr = null;
166 synchronized(dateformat) {
167 datestr = dateformat.format(date);
168 }
169 builder.append(datestr);
170 }
171 }
172 private void putlevelstring(stringbuilder builder, int type) {
173 switch(type) {
174 case simplelog1.log_level_trace:
175 builder.append("[trace] "); break;
176 case simplelog1.log_level_debug:
177 builder.append("[debug] "); break;
178 case simplelog1.log_level_info:
179 builder.append("[info] "); break;
180 case simplelog1.log_level_warn:
181 builder.append("[warn] "); break;
182 case simplelog1.log_level_error:
183 builder.append("[error] "); break;
184 case simplelog1.log_level_fatal:
185 builder.append("[fatal] "); break;
186 }
187 }
188 private void putlogname(stringbuilder builder, string name) {
189 if(showshortname) {
190 builder.append(getshortname(name));
191 } else if(showlogname) {
192 builder.append(name);
193 }
194 builder.append(" - ");
195 }
196 private void putcauseinfo(stringbuilder builder, throwable cause) {
197 if(cause == null) {
198 return;
199 }
200 builder.append("<");
201 builder.append(cause.getmessage());
202 builder.append(">");
203 builder.append(system.getproperty("line.separator"));
204
205 stringwriter writer = new stringwriter();
206 printwriter printer = new printwriter(writer);
207 cause.printstacktrace(printer);
208 printer.close();
209 builder.append(writer.tostring());
210 }
211 private boolean islevelenabled(int level) {
212 if(level >= this.level) {
213 return true;
214 }
215 return false;
216 }
217 private string getshortname(string name) {
218 if(shortname == null) {
219 if(name == null) {
220 shortname = "null";
221 return shortname;
222 }
223 int idx = name.lastindexof(".");
224 if(idx < 0) {
225 shortname = name;
226 } else {
227 shortname = name.substring(idx + 1);
228 }
229 }
230 return shortname;
231 }
232 }
在使用配置文件后,在没有增加simplelog2接口复杂性的基础上,使其功能更加强大,并且每个simplelog2的实例的日志级别都是不需要在代码中配置,并且它还支持了不同日志实例级别的继承性:
2 public void testsimplelog2() {
3 simplelog2 log = new simplelog2("levin.commons.logging.test.testbasic");
4 log.info("begin to execute testbasic() method
5
6 log.info("executing
7
8 try {
9 throw new exception("deliberately throw an exception
10 } catch(exception e) {
11 log.error("catching an exception", e);
12 }
13
14 log.info("execute testbasic() method finished.");
15 }
其中典型的配置文件如下(simplelog.properties):
levin.commons.logging.simplelog.showshortname=true
levin.commons.logging.simplelog.showdateinfo=true
levin.commons.logging.simplelog.dateformat=yyyy-mm-dd hh:mm:ss,sss zzz
levin.commons.logging.simplelog.root.level=debug
levin.commons.logging.simplelog.logfile=log/levin.log
levin.commons.logging.simplelog.logfile.append=true
levin.commons.logging.simplelog.logfile.flush=true
levin.commons.logging.simplelog.log.level=fatal
levin.commons.logging.simplelog.log.level.commons=info
到目前为止,我们已经简单的实现了一个可用的日志系统了,它只有一个类,而且还支持配置文件。事实上,这里的实现参考了commons-logging中的simplelog类,而且也部分借鉴了log4j的实现,只是log4j将日志打印的各个模块用不同的类进行了封装:logger类封装了一个命名日志类,它是log4j和使用它的应用程序的主要接口,提供打印不同级别日志的接口;logger类包含了level字段和appender集合,其中level表达当前logger类可打印日志信息的级别;appender接口用于对日志输出目的地的抽象,它可以是控制台、文件、网络等;appender中包含了layout字段,layout类是对一条日志记录的格式的抽象,它定义了每条日志记录打印的信息内容、格式、不同类型信息的排列顺序等;而loggingevent类则是对每一条日志记录的抽象和封装,从而每一条日志记录所具有的信息都可以从loggingevent实例中查询,loggingevent的设计思想有点类似很多系统中的context概念或者servlet中的httprequest、httpsession等类的设计,它将每一次日志打印的请求信息封装在一个类中,保证了数据的内聚性,所有需要获取请求信息的类只要拿到这个实例即可,而且如果需要改变请求中的部分数据,只要修改该实例即可保证该修改对所有的模块可见,从而简化了编程模型,也不会因为将很多信息分散到不同地方而到后期出现数据同步问题或是数据太分散而无法管理的问题。
通过以上分析,我们可以知道log4j的日志打印功能的最核心类即:logger、appender、level、layout、loggingevent。它们的类结构图如下:
一次日志打印的序列图如下: