自定义日志记录以在运行时收集消息 [英] Custom logging to gather messages at runtime
问题描述
有没有办法在运行时创建log4j Logger,将日志消息收集到缓冲区?
Is there a way to create a log4j Logger at runtime that will gather logging messages into a buffer?
我目前有一个记录大量事件的类。对于需要监视已记录事件的远程应用程序,我只想交换记录到缓冲区然后检索缓冲区的记录器,而不是重构该类。例如。如下所示:
I currently have a class that logs a number of events. For a remote application that needs to monitor the logged events, I'd like to just swap in a logger that logs to a buffer and then retrieve the buffer, rather than refactor the class. E.g. given something like:
Class Foo{
Logger log = ....;
public void doSomething(){
log.debug(...
.. actual code
log.debug(...
}
}
//我想通过一些外部代码做什么:
//what I'd like to do from some outside code:
String showFooLog(){
Foo f = new Foo();
f.log=new Logger(...
f.doSomething();
return f.log.contents();
}
这可能吗?
编辑:找到一个更短的解决方案,从Jared的帖子中指出(虽然它仍然不是线程安全的)。谢谢你帮助。
Is this possible?
Found a shorter solution, pointed to from Jared's posting( although it's still not threadsafe). Thanks for the help.
Logger l = Logger.getLogger( ... );
StringWriter writer = new StringWriter();
WriterAppender appender = new WriterAppender( new HTMLLayout(), writer );
l.addAppender( appender );
... run code here
writer.flush();
l.removeAppender( appender );
return writer.toString()
推荐答案
它这桩可能的 - 尽管你可能会需要创建自己的Appender。不过,这很容易做到。这是一个粗略的例子(需要考虑线程安全......这不是线程安全....我不确定我喜欢静态......但这应该足以推动你在正确的方向):
It's absolutely possible - although you're probably going to need to create your own Appender. This is really easy to do, though. Here's a rough-out of an example (need to think out thread-safety...this isn't threadsafe....and I'm not sure I like the statics...but this should be good enough to push you in the right direction):
public class BufferAppender extends org.apache.log4j.AppenderSkeleton {
private static Map<String, StringBuffer> buffers = new HashMap<String, StringBuffer>();
@Override
protected void append(LoggingEvent evt) {
String toAppend = this.layout.format(evt);
StringBuffer sb = getBuffer(evt.getLoggerName());
buffer.append(toAppend);
}
public static String getBufferContents(String loggerName) {
StringBuffer sb = buffers.get(sb);
if(sb == null) {
return null;
} else {
return sb.toString();
}
}
public static void clearBuffer(String loggerName) {
createBuffer(loggerName);
}
private static StringBuffer getBuffer(String loggerName) {
StringBuffer sb = buffers.get(loggerName);
if(sb == null) {
sb = createBuffer(loggerName);
}
return sb;
}
private static StringBuffer createBuffer(String loggerName) {
StringBuffer sb = new StringBuffer();
buffers.put(loggerName, sb);
return sb;
}
}
这篇关于自定义日志记录以在运行时收集消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!