我喜欢拦截一些(最重要的)日志消息并在GUI中显示它们或检查是否记录了任何错误。通常我使用java.util.logging
,java.util.logging.Handler
和java.util.logging.Formatter
。
然而,当前项目使用Log4J(2.x)并且每个功能都有不同的名称,并且似乎至少是复杂的四倍。
有人可以给我一些关于如何使用Log4J存档这样的东西的提示:
/**
* <p>
* logs error so they can be returned to the server (and tested in unit tests)
* </p>
*
* @author "Martin Krischik" <martin.krischik@noser.com>
* @version 1.0 $Revision: 2229 $
* @see java.util.logging.Handler
* @since 1.0
*/
@SuppressWarnings ("synthetic-access")
protected final class LogHandler
extends
java.util.logging.Handler
{
/**
* <p>
* A very simple formatter which displays only what is relevant to end users. Developer
* should look at the log file
* </p>
*
* @author "Martin Krischik" <martin.krischik@noser.com>
* @version 1.0 $Revision: 2229 $
* @see java.util.logging.Formatter
* @since 1.0
*/
private class LogFormatter
extends
java.util.logging.Formatter
{
/**
* <p>
* line separator
* </p>
*/
private final String lineSeparator = System.getProperty ("line.separator");
/**
* <p>
* Format the given LogRecord.
* </p>
*
* @param record
* the log record to be formatted.
* @return a formatted log record
* @see java.util.logging.Formatter#format(java.util.logging.LogRecord)
*/
@Override
public synchronized String format (final java.util.logging.LogRecord record)
{
final StringBuilder retval = new StringBuilder (4096);
final String message = this.formatMessage (record);
final java.util.logging.Level level = record.getLevel ();
retval.append (level.getLocalizedName ());
retval.append (": ");
retval.append (message);
retval.append (this.lineSeparator);
return retval.toString ();
} // format
} // LogFormatter
/**
* <p>
* A very simple formatter which displays only what is relevant to end users. Developer
* should look at the log file
* </p>
*/
private final DBUpdate.LogHandler.LogFormatter formatter =
new DBUpdate.LogHandler.LogFormatter ();
/**
* @throws SecurityException
* some severity error
* @see java.util.logging.Handler#close()
*/
@Override
public void close ()
throws SecurityException
{
return;
} // close
/**
* @see java.util.logging.Handler#flush()
*/
@Override
public void flush ()
{
return;
} // flush
/**
* @param record
* record to log.
* @see java.util.logging.Handler#publish(java.util.logging.LogRecord)
*/
@Override
public void publish (final java.util.logging.LogRecord record)
{
if (record.getLevel ().intValue () >= this.getLevel ().intValue ())
{
REST_Responce.this.errorMessages.add (this.formatter.format (record));
} // if
return;
} // publish
} // LogHandler