答案 0 :(得分:2)
使用log4j和extras 1.2 jar找到了一种方法,但不能与Log4J 2一起使用。
<强>爪哇强>
import org.apache.log4j.Logger;
import org.apache.log4j.spi.LoggingEvent;
import org.apache.log4j.receivers.varia.LogFilePatternReceiver;
public class LogParser extends LogFilePatternReceiver {
final static Logger logger = Logger.getLogger(LogParser.class);
public void doPost(LoggingEvent event) {
System.out.println(event.getTimeStamp());
System.out.println(event.getMessage());
}
public static void main(String[] args) {
(new LogParser()).run();
}
private void run(){
LogFilePatternReceiver r = new LogParser();
r.setLogFormat("TIMESTAMP LEVEL [THREAD] CLASS (FILE:LINE) - MESSAGE");
r.setFileURL("file:///tmp/log");
r.setTimestampFormat("yyyy-MM-dd HH:mm:ss,SSS");
r.setTailing(true);
r.setLoggerRepository(logger.getLoggerRepository());
r.activateOptions();
}
}
<强>的log4j.xml 强>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="console" class="org.apache.log4j.ConsoleAppender">
<param name="Target" value="System.out"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d %-5p [%t] %C{2} (%F:%L) - %m%n"/>
</layout>
</appender>
<root>
<priority value ="debug" />
<appender-ref ref="console" />
</root>
</log4j:configuration>
示例日志文件
2017-12-02 16:53:42,618 DEBUG [main] LogParser (LogParser.java:15) - message 1
2017-12-02 16:53:42,624 DEBUG [main] LogParser (LogParser.java:16) - message 2
<强>结果强>
2017-12-02 19:21:31,633 INFO [main] spi.Log4JULogger (Log4JULogger.java:104) - activateOptions
2017-12-02 19:21:31,652 DEBUG [LogFilePatternReceiver-plugin] spi.Log4JULogger (Log4JULogger.java:58) - regexp is (\S+-\S+-\S+ \S+:\S+:\S+,\S+)[ ]+(\S*\s*?)[ ]+\[(.*?)\][ ]+(.*?)[ ]+\((.*?):(.*?)\)[ ]+\-[ ]+(.*)
2017-12-02 19:21:31,652 INFO [LogFilePatternReceiver-plugin] spi.Log4JULogger (Log4JULogger.java:104) - attempting to load file: file:///tmp/log
1512194022618
message 1
1512194022624
message 2
2017-12-02 19:21:33,656 DEBUG [LogFilePatternReceiver-plugin] spi.Log4JULogger (Log4JULogger.java:58) - tailing file
2017-12-02 19:21:35,660 DEBUG [LogFilePatternReceiver-plugin] spi.Log4JULogger (Log4JULogger.java:58) - tailing file