本文转自上善若水的博客,原文出处:http://www.blogjava.net/DLevin/archive/2012/07/10/382676.html。感谢作者的无私的分享。
Appender负责定义日志输出的目的地,它可以是控制台(ConsoleAppender)、文件(FileAppender)、JMS服务器(JmsLogAppender)、以Email的形式发送出去(SMTPAppender)等。Appender是一个命名的实体,另外它还包含了对Layout、ErrorHandler、Filter等引用:
2 void addFilter(Filter newFilter);
3 public Filter getFilter();
4 public void clearFilters();
5 public void close();
6 public void doAppend(LoggingEvent event);
7 public String getName();
8 public void setErrorHandler(ErrorHandler errorHandler);
9 public ErrorHandler getErrorHandler();
public void setLayout(Layout layout);
public Layout getLayout();
public void setName(String name);
public boolean requiresLayout();
}
简单的,在配置文件中,Appender会注册到Logger中,Logger在写日志时,通过继承机制遍历所有注册到它本身和其父节点的Appender(在additivity为true的情况下),调用doAppend()方法,实现日志的写入。在doAppend方法中,若当前Appender注册了Filter,则doAppend还会判断当前日志时候通过了Filter的过滤,通过了Filter的过滤后,如果当前Appender继承自SkeletonAppender,还会检查当前日志级别时候要比当前Appender本身的日志级别阀门要打,所有这些都通过后,才会将LoggingEvent实例传递给Layout实例以格式化成一行日志信息,最后写入相应的目的地,在这些操作中,任何出现的错误都由ErrorHandler字段来处理。
Log4J中的Appender类图结构:
在Log4J Core一小节中已经简单的介绍过了AppenderSkeleton、WriterAppender、ConsoleAppender以及 Filter,因小节将直接介绍具体的几个常用的Appender。
FileAppender类
FileAppender继承自WriterAppender,它将日志写入文件。主要的日志写入逻辑已经在WriterAppender中处理,FileAppender主要处理的逻辑主要在于将设置日志输出文件名,并通过设置的文件构建WriterAppender中的QuiteWriter字段实例。如果Log文件的目录没有创建,在setFile()方法中会先创建目录,再设置日志文件。另外,所有FileAppender字段在调用activateOptions()方法中生效。
2 protected String fileName = null;
3 protected boolean bufferedIO = false;
;
5
6 public void activateOptions() {
7 if (fileName != null) {
8 try {
9 setFile(fileName, fileAppend, bufferedIO, bufferSize);
} catch (java.io.IOException e) {
errorHandler.error("setFile(" + fileName + "," + fileAppend
+ ") call failed.", e, ErrorCode.FILE_OPEN_FAILURE);
}
} else {
LogLog.warn("File option not set for appender [" + name + "].");
LogLog.warn("Are you using FileAppender instead of ConsoleAppender?");
}
}
public synchronized void setFile(String fileName, boolean append,
boolean bufferedIO, int bufferSize) throws IOException {
LogLog.debug("setFile called: " + fileName + ", " + append);
if (bufferedIO) {
setImmediateFlush(false);
}
reset();
FileOutputStream ostream = null;
try {
ostream = new FileOutputStream(fileName, append);
} catch (FileNotFoundException ex) {
String parentName = new File(fileName).getParent();
if (parentName != null) {
File parentDir = new File(parentName);
if (!parentDir.exists() && parentDir.mkdirs()) {
ostream = new FileOutputStream(fileName, append);
} else {
throw ex;
}
} else {
throw ex;
}
}
Writer fw = createWriter(ostream);
if (bufferedIO) {
fw = new BufferedWriter(fw, bufferSize);
}
this.setQWForFiles(fw);
this.fileName = fileName;
this.fileAppend = append;
this.bufferedIO = bufferedIO;
this.bufferSize = bufferSize;
writeHeader();
LogLog.debug("setFile ended");
}
DailyRollingFileAppender类
DailyRollingFileAppender继承自FileAppender,不过这个名字感觉有点不靠谱,事实上,DailyRollingFileAppender会在每隔一段时间可以生成一个新的日志文件,不过这个时间间隔是可以设置的,不仅仅只是每隔一天。时间间隔通过setDatePattern()方法设置,datePattern必须遵循SimpleDateFormat中的格式。支持的时间间隔有:
1. 每天:’.’YYYY-MM-dd(默认)
2. 每星期:’.’YYYY-ww
3. 每月:’.’YYYY-MM
4. 每隔半天:’.’YYYY-MM-dd-a
5. 每小时:’.’YYYY-MM-dd-HH
6. 每分钟:’.’YYYY-MM-dd-HH-mm
DailyRollingFileAppender需要设置的两个属性:datePattern和fileName。其中datePattern用于确定时间间隔以及当日志文件过了一个时间间隔后用于重命名之前的日志文件;fileName用于设置日志文件的初始名字。在实现过程中,datePattern用于实例化SimpleDateFormat,记录当前时间以及计算下一个时间间隔时间。在每次写日志操作之前先判断当前时间是否已经操作计算出的下一间隔时间,若是,则将之前的日志文件重命名(向日志文件名尾添加datePattern指定的时间信息),并创新的日志文件,同时重新设置当前时间以及下一次的时间间隔。
2 super.activateOptions();
3 if (datePattern != null && fileName != null) {
4 now.setTime(System.currentTimeMillis());
5 sdf = new SimpleDateFormat(datePattern);
6 int type = computeCheckPeriod();
7 printPeriodicity(type);
8 rc.setType(type);
9 File file = new File(fileName);
scheduledFilename = fileName
+ sdf.format(new Date(file.lastModified()));
} else {
LogLog.error("Either File or DatePattern options are not set for appender ["
+ name + "].");
}
}
void rollOver() throws IOException {
if (datePattern == null) {
errorHandler.error("Missing DatePattern option in rollOver().");
return;
}
String datedFilename = fileName + sdf.format(now);
if (scheduledFilename.equals(datedFilename)) {
return;
}
this.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 + " -> " + scheduledFilename);
} else {
LogLog.error("Failed to rename [" + fileName + "] to ["
+ scheduledFilename + "].");
}
try {
this.setFile(fileName, true, this.bufferedIO, this.bufferSize);
} catch (IOException e) {
errorHandler.error("setFile(" + fileName + ", true) call failed.");
}
scheduledFilename = datedFilename;
}
protected void subAppend(LoggingEvent event) {
long n = System.currentTimeMillis();
if (n >= nextCheck) {
now.setTime(n);
nextCheck = rc.getNextCheckMillis(now);
try {
rollOver();
} catch (IOException ioe) {
if (ioe instanceof InterruptedIOException) {
Thread.currentThread().interrupt();
}
LogLog.error("rollOver() failed.", ioe);
}
}
super.subAppend(event);
}
按Log4J文档,DailyRollingFileAppender存在线程同步问题。不过本人木有找到哪里出问题了,望高人指点。
RollingFileAppender类
RollingFileAppender继承自FileAppender,不同于DailyRollingFileAppender是基于时间作为阀值,RollingFileAppender则是基于文件大小作为阀值。当日志文件超过指定大小,日志文件会被重命名成”日志文件名.1”,若此文件已经存在,则将此文件重命名成”日志文件名.2”,一次类推。若文件数已经超过设置的可备份日志文件最大个数,则将最旧的日志文件删除。如果要设置不删除任何日志文件,可以将maxBackupIndex设置成Integer最大值,如果这样,这里rollover()方法的实现会引起一些性能问题,因为它要冲最大值开始遍历查找已经备份的日志文件。
;
;
4
5 public void rollOver() {
6 File target;
7 File file;
8 if (qw != null) {
9 long size = ((CountingQuietWriter) qw).getCount();
LogLog.debug("rolling over count=" + size);
// if operation fails, do not roll again until
// maxFileSize more bytes are written
nextRollover = size + maxFileSize;
}
LogLog.debug("maxBackupIndex=" + maxBackupIndex);
boolean renameSucceeded = true;
// If maxBackups <= 0, then there is no file renaming to be done.
) {
// Delete the oldest file, to keep Windows happy.
file = new File(fileName + '.' + maxBackupIndex);
if (file.exists())
renameSucceeded = file.delete();
// Map {(maxBackupIndex - 1), , 2, 1} to {maxBackupIndex, , 3,
// 2}
&& renameSucceeded; i--) {
file = new File(fileName + "." + i);
if (file.exists()) {
));
LogLog.debug("Renaming file " + file + " to " + target);
renameSucceeded = file.renameTo(target);
}
}
if (renameSucceeded) {
// Rename fileName to fileName.1
);
this.closeFile(); // keep windows happy.
file = new File(fileName);
LogLog.debug("Renaming file " + file + " to " + target);
renameSucceeded = file.renameTo(target);
//
// if file rename failed, reopen file with append = true
//
if (!renameSucceeded) {
try {
this.setFile(fileName, true, bufferedIO, bufferSize);
} catch (IOException e) {
if (e instanceof InterruptedIOException) {
Thread.currentThread().interrupt();
}
LogLog.error("setFile(" + fileName
+ ", true) call failed.", e);
}
}
}
}
//
// if all renames were successful, then
//
if (renameSucceeded) {
try {
this.setFile(fileName, false, bufferedIO, bufferSize);
;
} catch (IOException e) {
if (e instanceof InterruptedIOException) {
Thread.currentThread().interrupt();
}
LogLog.error("setFile(" + fileName + ", false) call failed.", e);
}
}
}
public synchronized void setFile(String fileName, boolean append,
boolean bufferedIO, int bufferSize) throws IOException {
super.setFile(fileName, append, this.bufferedIO, this.bufferSize);
if (append) {
File f = new File(fileName);
((CountingQuietWriter) qw).setCount(f.length());
}
}
protected void setQWForFiles(Writer writer) {
this.qw = new CountingQuietWriter(writer, errorHandler);
}
protected void subAppend(LoggingEvent event) {
super.subAppend(event);
if (fileName != null && qw != null) {
long size = ((CountingQuietWriter) qw).getCount();
if (size >= maxFileSize && size >= nextRollover) {
rollOver();
}
}
}
AsyncAppender类
AsyncAppender顾名思义,就是异步的调用Appender中的doAppend()方法。有多种方法实现这样的功能,比如每当调用doAppend()方法时,doAppend()方法内部启动一个线程来处理这一次调用的逻辑,这个线程可以是新建的线程也可以是线程池,然而我们知道线程是一个比较耗资源的实体,为每一次的操作都创建一个新的线程,而这个线程在这一次调用结束后就不再使用,这种模式是非常不划算的,性能低下;而且即使在这里使用线程池,也会导致在非常多请求同时过来时引起消耗大量的线程池中的线程或者因为线程池已满而阻塞请求。因而这种直接使用线程去处理每一次的请求是不可取的。
另一种常用的方案可以使用生产者和消费中的模式来实现类似的逻辑。即每一次请求做为一个生产者,将请求放到一个Queue中,而由另外一个或多个消费者读取Queue中的内容以处理真正的逻辑。
在最新的Java版本中,我们可以使用BlockingQueue类简单的实现类似的需求,然而由于Log4J的存在远早于BlockingQueue的创建,因而为了实现对以前版本的兼容,它还是自己实现了这样一套生产者消费者模型。
AsyncAppender并不会在每一次的doAppend()调用中都直接将消息输出,而是使用了buffer,即只有等到buffer中LoggingEvent实例到达bufferSize个的时候才真正的处理这些消息,当然我们也可以讲bufferSize设置成1,从而实现每一个LoggingEvent实例的请求都会直接执行。如果bufferSize设置过大,在应用程序异常终止时可能会丢失部分日志。
private final List buffer = new ArrayList();
private final Map discardMap = new HashMap();
private int bufferSize = DEFAULT_BUFFER_SIZE;
private final Thread dispatcher;
private boolean locationInfo = false;
private boolean blocking = true;
对其他字段,discardMap用于存放当当前LoggingEvent请求数已经超过bufferSize或当前线程被中断的情况下能继续保留这些日志信息;locationInfo用于设置是否需要保留位置信息;blocking用于设置在消费者正在处理时,是否需要生产者“暂停”下来,默认为true;而dispatcher即是消费者线程,它在构建AsyncAppender是启动,每次监听buffer这个list,如果发现buffer中存在LoggingEvent实例,则将所有buffer和discardMap中的LoggingEvent实例拷贝到数组中,清空buffer和discardMap,并调用AsyncAppender内部注册的Appender实例打印日志。
2 boolean isActive = true;
3 try {
4 while (isActive) {
5 LoggingEvent[] events = null;
6 synchronized (buffer) {
7 int bufferSize = buffer.size();
8 isActive = !parent.closed;
9
) && isActive) {
buffer.wait();
bufferSize = buffer.size();
isActive = !parent.closed;
}
) {
events = new LoggingEvent[bufferSize
+ discardMap.size()];
buffer.toArray(events);
int index = bufferSize;
for (Iterator iter = discardMap.values().iterator(); iter
.hasNext();) {
events[index++] = ((DiscardSummary) iter.next())
.createEvent();
}
buffer.clear();
discardMap.clear();
buffer.notifyAll();
}
}
if (events != null) {
; i < events.length; i++) {
synchronized (appenders) {
appenders.appendLoopOnAppenders(events[i]);
}
}
}
}
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
这里其实有一个bug,即当程序停止时只剩下discardMap中有日志信息,而buffer中没有日志信息,由于Dispatcher线程不检查discardMap中的日志信息,因而此时会导致discardMap中的日志信息丢失。即使在生成者中当buffer为空时,它也会激活buffer锁,然而即使激活后buffer本身大小还是为0,因而不会处理之后的逻辑,因而这个逻辑也处理不了该bug。
对于生产者,它首先处理当消费者线程出现异常而不活动时,此时将同步的输出日志;而后根据配置获取LoggingEvent中的数据;再获得buffer的对象锁,如果buffer还没满,则直接将LoggingEvent实例添加到buffer中,否则如果blocking设置为true,即生产者会等消费者处理完后再继续下一次接收数据。如果blocking设置为fasle或者消费者线程被打断,那么当前的LoggingEvent实例则会保存在discardMap中,因为此时buffer已满。
)) {
3 synchronized (appenders) {
4 appenders.appendLoopOnAppenders(event);
5 }
6 return;
7 }
8 event.getNDC();
9 event.getThreadName();
event.getMDCCopy();
if (locationInfo) {
event.getLocationInformation();
}
event.getRenderedMessage();
event.getThrowableStrRep();
synchronized (buffer) {
while (true) {
int previousSize = buffer.size();
if (previousSize < bufferSize) {
buffer.add(event);
) {
buffer.notifyAll();
}
break;
}
boolean discard = true;
if (blocking && !Thread.interrupted()
&& Thread.currentThread() != dispatcher) {
try {
buffer.wait();
discard = false;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
if (discard) {
String loggerName = event.getLoggerName();
DiscardSummary summary = (DiscardSummary) discardMap
.get(loggerName);
if (summary == null) {
summary = new DiscardSummary(event);
discardMap.put(loggerName, summary);
} else {
summary.add(event);
}
break;
}
}
}
}
最后,AsyncAppender是Appender的一个容器,它实现了AppenderAttachable接口,改接口的实现主要将实现逻辑代理给AppenderAttachableImpl类。
测试代码如下:
2 public void testAsyncAppender() throws Exception {
3 AsyncAppender appender = new AsyncAppender();
4 appender.addAppender(new ConsoleAppender(new TTCCLayout()));
);
6 appender.setLocationInfo(true);
7 appender.activateOptions();
8 configAppender(appender);
9
logTest();
}
JDBCAppender类
JDBCAppender将日志保存到数据库的表中,由于数据库保存操作是一个比较费时的操作,因而JDBCAppender默认使用缓存机制,当然你也可以设置缓存大小为1实现实时向数据库插入日志。JDBCAppender中的Layout默认只支持PatternLayout,用户可以通过设置自己的PatternLayout,其中ConversionPattern设置成插入数据库的SQL语句或通过setSql()方法设置SQL语句,JDBCAppender内部会创建相应的PatternLayout,如可以设置SQL语句为:
insert into LogTable(Thread, Class, Message) values(“%t”, “%c”, “%m”)
在doAppend()方法中,JDBCAppender通过layout获取SQL语句,将LoggingEvent实例插入到数据库中。
2 protected String databaseUser = "me";
3 protected String databasePassword = "mypassword";
4 protected Connection connection = null;
5 protected String sqlStatement = "";
;
7 protected ArrayList buffer;
8 protected ArrayList removes;
9 private boolean locationInfo = false;
public void append(LoggingEvent event) {
event.getNDC();
event.getThreadName();
event.getMDCCopy();
if (locationInfo) {
event.getLocationInformation();
}
event.getRenderedMessage();
event.getThrowableStrRep();
buffer.add(event);
if (buffer.size() >= bufferSize)
flushBuffer();
}
public void flushBuffer() {
removes.ensureCapacity(buffer.size());
for (Iterator i = buffer.iterator(); i.hasNext();) {
try {
LoggingEvent logEvent = (LoggingEvent) i.next();
String sql = getLogStatement(logEvent);
execute(sql);
removes.add(logEvent);
} catch (SQLException e) {
errorHandler.error("Failed to excute sql", e,
ErrorCode.FLUSH_FAILURE);
}
}
buffer.removeAll(removes);
removes.clear();
}
protected String getLogStatement(LoggingEvent event) {
return getLayout().format(event);
}
protected void execute(String sql) throws SQLException {
Connection con = null;
Statement stmt = null;
try {
con = getConnection();
stmt = con.createStatement();
stmt.executeUpdate(sql);
} catch (SQLException e) {
if (stmt != null)
stmt.close();
throw e;
}
stmt.close();
closeConnection(con);
}
protected Connection getConnection() throws SQLException {
if (!DriverManager.getDrivers().hasMoreElements())
setDriver("sun.jdbc.odbc.JdbcOdbcDriver");
if (connection == null) {
connection = DriverManager.getConnection(databaseURL, databaseUser,
databasePassword);
}
return connection;
}
protected void closeConnection(Connection con) {
}
用户可以编写自己的JDBCAppender,继承自JDBCAppender,重写getConnection()和closeConnection(),可以实现从数据库连接池中获取connection,在每次将JDBCAppender缓存中的LoggingEvent列表插入数据库时从连接池中获取缓存,而在该操作完成后将获得的连接释放回连接池。用户也可以重写getLogstatement()以自定义插入LoggingEvent的SQL语句。
JMSAppender类
JMSAppender类将LoggingEvent实例序列化成ObjectMessage,并将其发送到JMS Server的一个指定Topic中。它的实现比较简单,设置相应的connectionFactoryName、topicName、providerURL、userName、password等JMS相应的信息,在activateOptions()方法中创建相应的JMS链接,在doAppend()方法中将LoggingEvent序列化成ObjectMessage发送到JMS
Server中,它也可以通过locationInfo字段是否需要计算位置信息。不过这里的实现感觉有一些bug:在序列化LoggingEvent实例之前没有先缓存必要的信息,如threadName,因为这些信息默认是不设置的,具体可以参考JDBCAppender、AsyncAppender等。
2 String securityCredentials;
3 String initialContextFactoryName;
4 String urlPkgPrefixes;
5 String providerURL;
6 String topicBindingName;
7 String tcfBindingName;
8 String userName;
9 String password;
10 boolean locationInfo;
11
12 TopicConnection topicConnection;
13 TopicSession topicSession;
14 TopicPublisher topicPublisher;
15
16 public void activateOptions() {
17 TopicConnectionFactory topicConnectionFactory;
18 try {
19 Context jndi;
20 LogLog.debug("Getting initial context.");
21 if (initialContextFactoryName != null) {
22 Properties env = new Properties();
23 env.put(Context.INITIAL_CONTEXT_FACTORY,
24 initialContextFactoryName);
25 if (providerURL != null) {
26 env.put(Context.PROVIDER_URL, providerURL);
27 } else {
28 LogLog.warn("You have set InitialContextFactoryName option but not the "
29 + "ProviderURL. This is likely to cause problems.");
30 }
31 if (urlPkgPrefixes != null) {
32 env.put(Context.URL_PKG_PREFIXES, urlPkgPrefixes);
33 }
34 if (securityPrincipalName != null) {
35 env.put(Context.SECURITY_PRINCIPAL, securityPrincipalName);
36 if (securityCredentials != null) {
37 env.put(Context.SECURITY_CREDENTIALS,
38 securityCredentials);
39 } else {
40 LogLog.warn("You have set SecurityPrincipalName option but not the "
41 + "SecurityCredentials. This is likely to cause problems.");
42 }
43 }
44 jndi = new InitialContext(env);
45 } else {
46 jndi = new InitialContext();
47 }
48 LogLog.debug("Looking up [" + tcfBindingName + "]");
49 topicConnectionFactory = (TopicConnectionFactory) lookup(jndi,
50 tcfBindingName);
51 LogLog.debug("About to create TopicConnection.");
52 if (userName != null) {
53 topicConnection = topicConnectionFactory.createTopicConnection(
54 userName, password);
55 } else {
56 topicConnection = topicConnectionFactory
57 .createTopicConnection();
58 }
59 LogLog.debug("Creating TopicSession, non-transactional, "
60 + "in AUTO_ACKNOWLEDGE mode.");
61 topicSession = topicConnection.createTopicSession(false,
62 Session.AUTO_ACKNOWLEDGE);
63 LogLog.debug("Looking up topic name [" + topicBindingName + "].");
64 Topic topic = (Topic) lookup(jndi, topicBindingName);
65 LogLog.debug("Creating TopicPublisher.");
66 topicPublisher = topicSession.createPublisher(topic);
67 LogLog.debug("Starting TopicConnection.");
68 topicConnection.start();
69 jndi.close();
70 } catch (JMSException e) {
71 errorHandler.error(
72 "Error while activating options for appender named ["
73 + name + "].", e, ErrorCode.GENERIC_FAILURE);
74 } catch (NamingException e) {
75 errorHandler.error(
76 "Error while activating options for appender named ["
77 + name + "].", e, ErrorCode.GENERIC_FAILURE);
78 } catch (RuntimeException e) {
79 errorHandler.error(
80 "Error while activating options for appender named ["
81 + name + "].", e, ErrorCode.GENERIC_FAILURE);
82 }
83 }
84
85 public void append(LoggingEvent event) {
86 if (!checkEntryConditions()) {
87 return;
88 }
89 try {
90 ObjectMessage msg = topicSession.createObjectMessage();
91 if (locationInfo) {
92 event.getLocationInformation();
93 }
94 msg.setObject(event);
95 topicPublisher.publish(msg);
96 } catch (JMSException e) {
97 errorHandler.error("Could not publish message in JMSAppender ["
98 + name + "].", e, ErrorCode.GENERIC_FAILURE);
99 } catch (RuntimeException e) {
errorHandler.error("Could not publish message in JMSAppender ["
+ name + "].", e, ErrorCode.GENERIC_FAILURE);
}
}
TelnetAppender类
TelnetAppender类将日志消息发送到指定的Socket端口(默认为23),用户可以使用telnet连接以获取日志信息。这里的实现貌似没有考虑到telnet客户端如何退出的问题。另外,在windows中可能默认没有telnet支持,此时只需要到”控制面板”->”程序和功能”->”打开或关闭windows功能”中大概Telnet服务即可。TelnetAppender使用内部类SocketHandler封装发送日志消息到客户端,如果没有Telnet客户端连接,则日志消息将会直接被抛弃。
;
3
4 public void activateOptions() {
5 try {
6 sh = new SocketHandler(port);
7 sh.start();
8 } catch (InterruptedIOException e) {
9 Thread.currentThread().interrupt();
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (RuntimeException e) {
e.printStackTrace();
}
super.activateOptions();
}
protected void append(LoggingEvent event) {
if (sh != null) {
sh.send(layout.format(event));
if (layout.ignoresThrowable()) {
String[] s = event.getThrowableStrRep();
if (s != null) {
StringBuffer buf = new StringBuffer();
; i < s.length; i++) {
buf.append(s[i]);
buf.append("\r\n");
}
sh.send(buf.toString());
}
}
}
}
在SocketHandler中,创建一个新的线程以监听指定的端口,如果有Telnet客户端连接过来,则将其加入到connections集合中。这样在send()方法中就可以遍历connections集合,并将日志信息发送到每个连接的Telnet客户端。
2 private Vector connections = new Vector();
3 private ServerSocket serverSocket;
;
5
6 public synchronized void send(final String message) {
7 Iterator ce = connections.iterator();
8 for (Iterator e = writers.iterator(); e.hasNext();) {
9 ce.next();
PrintWriter writer = (PrintWriter) e.next();
writer.print(message);
if (writer.checkError()) {
ce.remove();
e.remove();
}
}
}
public void run() {
while (!serverSocket.isClosed()) {
try {
Socket newClient = serverSocket.accept();
PrintWriter pw = new PrintWriter(
newClient.getOutputStream());
if (connections.size() < MAX_CONNECTIONS) {
synchronized (this) {
connections.addElement(newClient);
writers.addElement(pw);
pw.print("TelnetAppender v1.0 ("
+ connections.size()
+ " active connections)\r\n\r\n");
pw.flush();
}
} else {
pw.print("Too many connections.\r\n");
pw.flush();
newClient.close();
}
}
}
SMTPAppender类
SMTPAppender将日志消息以邮件的形式发送出来,默认实现,它会先缓存日志信息,只有当遇到日志级别是ERROR或ERROR以上的日志消息时才通过邮件的形式发送出来,如果在遇到触发发送的日志发生之前缓存中的日志信息已满,则最早的日志信息会被覆盖。用户可以通过setEvaluatorClass()方法改变触发发送日志的条件。
2 if (!checkEntryConditions()) {
3 return;
4 }
5 event.getThreadName();
6 event.getNDC();
7 event.getMDCCopy();
8 if (locationInfo) {
9 event.getLocationInformation();
}
event.getRenderedMessage();
event.getThrowableStrRep();
cb.add(event);
if (evaluator.isTriggeringEvent(event)) {
sendBuffer();
}
}
protected void sendBuffer() {
try {
String s = formatBody();
boolean allAscii = true;
; i < s.length() && allAscii; i++) {
allAscii = s.charAt(i) <= 0x7F;
}
MimeBodyPart part;
if (allAscii) {
part = new MimeBodyPart();
part.setContent(s, layout.getContentType());
} else {
try {
ByteArrayOutputStream os = new ByteArrayOutputStream();
Writer writer = new OutputStreamWriter(MimeUtility.encode(
os, "quoted-printable"), "UTF-8");
writer.write(s);
writer.close();
InternetHeaders headers = new InternetHeaders();
headers.setHeader("Content-Type", layout.getContentType()
+ "; charset=UTF-8");
headers.setHeader("Content-Transfer-Encoding",
"quoted-printable");
part = new MimeBodyPart(headers, os.toByteArray());
} catch (Exception ex) {
StringBuffer sbuf = new StringBuffer(s);
; i < sbuf.length(); i++) {
if (sbuf.charAt(i) >= 0x80) {
sbuf.setCharAt(i, '?');
}
}
part = new MimeBodyPart();
part.setContent(sbuf.toString(), layout.getContentType());
}
}
Multipart mp = new MimeMultipart();
mp.addBodyPart(part);
msg.setContent(mp);
msg.setSentDate(new Date());
Transport.send(msg);
} catch (MessagingException e) {
LogLog.error("Error occured while sending e-mail notification.", e);
} catch (RuntimeException e) {
LogLog.error("Error occured while sending e-mail notification.", e);
}
}
protected String formatBody() {
StringBuffer sbuf = new StringBuffer();
String t = layout.getHeader();
if (t != null)
sbuf.append(t);
int len = cb.length();
; i < len; i++) {
LoggingEvent event = cb.get();
sbuf.append(layout.format(event));
if (layout.ignoresThrowable()) {
String[] s = event.getThrowableStrRep();
if (s != null) {
; j < s.length; j++) {
sbuf.append(s[j]);
sbuf.append(Layout.LINE_SEP);
}
}
}
}
t = layout.getFooter();
if (t != null) {
sbuf.append(t);
}
return sbuf.toString();
}
SocketAppender类
SocketAppender将日志消息(LoggingEvent序列化实例)发送到指定Host的port端口。在创建SocketAppender时,SocketAppender会根据设置的Host和端口建立和远程服务器的链接,并创建ObjectOutputStream实例。
2 if (this.address == null)
3 return;
4 try {
5 cleanUp();
6 oos = new ObjectOutputStream(
7 new Socket(address, port).getOutputStream());
8 } catch (IOException e) {
9 if (e instanceof InterruptedIOException) {
Thread.currentThread().interrupt();
}
String msg = "Could not connect to remote log4j server at ["
+ address.getHostName() + "].";
) {
msg += " We will try again later.";
fireConnector(); // fire the connector thread
} else {
msg += " We are not retrying.";
errorHandler.error(msg, e, ErrorCode.GENERIC_FAILURE);
}
LogLog.error(msg);
}
}
如果创建失败,调用fireConnector()方法,创建一个Connector线程,在每间隔reconnectionDelay(默认值为30000ms,若将其设置为0表示在链接出问题时不创建新的线程检测)的时间里不断重试链接。当链接重新建立后,Connector线程退出并将connector实例置为null以在下一次链接出现问题时创建的Connector线程检测。
2 void fireConnector() {
3 if (connector == null) {
4 LogLog.debug("Starting a new connector thread.");
5 connector = new Connector();
6 connector.setDaemon(true);
7 connector.setPriority(Thread.MIN_PRIORITY);
8 connector.start();
9 }
}
class Connector extends Thread {
boolean interrupted = false;
public void run() {
Socket socket;
while (!interrupted) {
try {
sleep(reconnectionDelay);
LogLog.debug("Attempting connection to "
+ address.getHostName());
socket = new Socket(address, port);
synchronized (this) {
oos = new ObjectOutputStream(socket.getOutputStream());
connector = null;
LogLog.debug("Connection established. Exiting connector thread.");
break;
}
} catch (InterruptedException e) {
LogLog.debug("Connector interrupted. Leaving loop.");
return;
} catch (java.net.ConnectException e) {
LogLog.debug("Remote host " + address.getHostName()
+ " refused connection.");
} catch (IOException e) {
if (e instanceof InterruptedIOException) {
Thread.currentThread().interrupt();
}
LogLog.debug("Could not connect to "
+ address.getHostName() + ". Exception is " + e);
}
}
}
}
而后,在每一次日志记录请求时只需将LoggingEvent实例序列化到之前创建的ObjectOutputStream中即可,若该操作失败,则会重新建立Connector线程以隔时检测远程日志服务器可以重新链接。
2 if (event == null)
3 return;
4 if (address == null) {
5 errorHandler
6 .error("No remote host is set for SocketAppender named \""
7 + this.name + "\".");
8 return;
9 }
if (oos != null) {
try {
if (locationInfo) {
event.getLocationInformation();
}
if (application != null) {
event.setProperty("application", application);
}
event.getNDC();
event.getThreadName();
event.getMDCCopy();
event.getRenderedMessage();
event.getThrowableStrRep();
oos.writeObject(event);
oos.flush();
if (++counter >= RESET_FREQUENCY) {
;
// Failing to reset the object output stream every now and
// then creates a serious memory leak.
// System.err.println("Doing oos.reset()");
oos.reset();
}
} catch (IOException e) {
if (e instanceof InterruptedIOException) {
Thread.currentThread().interrupt();
}
oos = null;
LogLog.warn("Detected problem with connection: " + e);
) {
fireConnector();
} else {
errorHandler
.error("Detected problem with connection, not reconnecting.",
e, ErrorCode.GENERIC_FAILURE);
}
}
}
}
SocketNode类
Log4J为日志服务器的实现提供了SocketNode类,它接收客户端的链接,并根据配置打印到相关的Appender中。
2 Socket socket;
3 LoggerRepository hierarchy;
4 ObjectInputStream ois;
5
6 public SocketNode(Socket socket, LoggerRepository hierarchy) {
7 this.socket = socket;
8 this.hierarchy = hierarchy;
9 try {
ois = new ObjectInputStream(new BufferedInputStream(
socket.getInputStream()));
} catch () {
}
}
public void run() {
LoggingEvent event;
Logger remoteLogger;
try {
if (ois != null) {
while (true) {
event = (LoggingEvent) ois.readObject();
remoteLogger = hierarchy.getLogger(event.getLoggerName());
if (event.getLevel().isGreaterOrEqual(
remoteLogger.getEffectiveLevel())) {
remoteLogger.callAppenders(event);
}
}
}
} catch () {
} finally {
if (ois != null) {
try {
ois.close();
} catch (Exception e) {
logger.info("Could not close connection.", e);
}
}
if (socket != null) {
try {
socket.close();
} catch (InterruptedIOException e) {
Thread.currentThread().interrupt();
} catch (IOException ex) {
}
}
}
}
}
事实上,Log4J提供了两个日志服务器的实现类:SimpleSocketServer和SocketServer。他们都会接收客户端的连接,为每个客户端链接创建一个SocketNode实例,并根据指定的配置文件打印日志消息。它们的不同在于SimpleSocketServer同时支持xml和properties配置文件,而SocketServer只支持properties配置文件;另外,SocketServer支持不同客户端使用不同的配置文件(以客户端主机名作为选择配置文件的方式),而SimpleSocketServer不支持。
最后,使用SocketAppender时,在应用程序退出时,最好显示的调用LoggerManager.shutdown()方法,不然如果是通过垃圾回收器来隐式的关闭(finalize()方法)SocketAppender,在Windows平台中可能会存在TCP管道中未传输的数据丢失的情况。另外,在网络连接不可用时,SocketAppender可能会阻塞应用程序,当网络可用,但是远程日志服务器不可用时,相应的日志会被丢失。如果日志传输给远程日志服务器的速度要慢于日志产生速度,此时会影响应用程序性能。这些问题在下一小节的SocketHubAppender中同样存在。
测试代码
可以使用一下代码测试SocketAppender和SocketNode:
2 public void testSocketAppender() throws Exception {
3 SocketAppender appender = new SocketAppender(
);
5 appender.setLocationInfo(true);
6 appender.setApplication("AppenderTest");
7 appender.activateOptions();
8 configAppender(appender);
9
Logger log = Logger.getLogger("levin.log4j.test.TestBasic");
; i++) {
);
) {
log.info("Normal test.");
} else {
log.info("Exception test", new Exception());
}
}
}
@Test
public void testSimpleSocketServer() throws Exception {
ConsoleAppender appender = new ConsoleAppender(new TTCCLayout());
appender.activateOptions();
configAppender(appender);
);
while(true) {
Socket socket = serverSocket.accept();
new Thread(new SocketNode(socket,
LogManager.getLoggerRepository()),
).start();
}
}
SocketHubAppender类
SocketHubAppender类似SocketAppender,它也将日志信息(序列化后的LoggingEvent实例)发送到指定的日志服务器,该日志服务器可以是SocketNode支持的服务器。不同的是,SocketAppender指定日志服务器的地址和端口号,而SocketHubAppender并不直接指定日志服务器的地址和端口号,它自己启动一个指定端口的服务器,由日志服务器注册到到该服务器,从而产生一个连接参数,SocketHubAppender根据这些参数发送日志信息到注册的日志服务器,因而SocketHubAppender支持同时发送相同的日志信息到多个日志服务器。
另外,SocketHubAppender还会缓存部分LoggingEvent实力,从而支持在新注册一个日志服务器时,它会先将那些缓存下来的LoggingEvent发送给新注册服务器,然后接受新的LoggingEvent日志打印请求。
具体实现以及注意事项参考SocketAppender。最好补充一点,SocketHubAppender可以和chainsaw一起使用,它好像使用了zeroconf协议,和SocketHubAppender以及SocketAppender中的ZeroConfSupport类相关,不怎么了解这个协议,也没有时间细看了。
LF5Appender类
将日志显示在Swing窗口中。对Swing不熟,没怎么看代码,不过可以使用一下测试用例简单的做一些测试,提供一些感觉。
public void testLF5Appender() throws Exception {
LF5Appender appender = new LF5Appender();
appender.setLayout(new TTCCLayout());
appender.activateOptions();
configAppender(appender);
logTest();
}
其他Appender类
ExternallyRolledFileAppender类继承自RollingFileAppender,因而它最基本的也是基于日志文件大小来备份日志文件。然而它同时还支持外界通过Socket发送“RollOver”给它以实现在特定情况下手动备份日志文件。Log4J提供Roller类来实现这样的功能,其使用方法是:
java -cp log4j-1.2.16.jar org.apache.log4j.varia.Roller <hostname> <port>
但是由于任何可以和应用程序运行的服务器连接的代码都能像该服务器发送“RollOver”消息,因而这种方式并不适合production环境在,在production中最好能加入一些限制信息,比如安全验证等信息。
NTEventLogAppender将日志打印到NT事件日志系统中(NT event log system)。顾名思义,它只能用在Windows中,而且需要NTEventLogAppender.dll、NTEventLogAppender.amd64.dll、NTEventLogAppender.ia64.dll或NTEventLogAppender.x86.dll动态链接库在Windows
PATH路径中。在Windows 7中可以通过控制面板->管理工具->查看事件日志中查看相应的日志信息。
SyslogAppender将日志打印到syslog中,我对syslog不怎么了解,通过查看网上信息的结果,看起来syslog只是存在于Linux和Unix中。SyslogAppender额外的需要配置Facility和SyslogHost字段。具体可以查看:http://www.cnblogs.com/frankliiu-java/articles/1754835.html和http://sjsky.iteye.com/blog/962870。
NullAppender作为一个Null Object模式存在,不会输出任何打印日志消息。