首先创建一个新的事件处理程序类来处理消息。请注意,解析应该在 event() 方法中完成,因为它将为每个 syslog 事件调用。
public class SyslogMessageHandler implements SyslogServerSessionEventHandlerIF {
@Override
public void event(Object session, SyslogServerIF syslogServer,
SocketAddress socketAddress, SyslogServerEventIF event) {
// Simple parsing for Strings in the message
if (!event.getMessage().contains(" msg=\"")) {
Logger.getLogger(getClass().getSimpleName()).log(Level.INFO, event.getMessage());
}
// You can also build Objects and/or use Pattern/Matcher for parsing.
MyHTTPLogInfo info = new MyHTTPLogInfo(event.getMessage());
Pattern myPattern = Pattern.compile("^GET\\s+/([^\\s\\?]*)(\\?\\S*)?\\s+HTTP/1\\.\\d$");
Matcher matcher = myPattern.matcher(info.getHttpRequest());
if (matcher.matches()) {
Logger.getLogger(getClass().getSimpleName()).log(Level.INFO, info.getMyCustomLogOutput());
}
}
@Override
public void exception(Object session, SyslogServerIF syslogServer, SocketAddress socketAddress, Exception exception) {
Logger.getLogger(getClass().getSimpleName()).log(Level.INFO, "exception()");
}
@Override
public Object sessionOpened(SyslogServerIF syslogServer, SocketAddress socketAddress) {
Logger.getLogger(getClass().getSimpleName()).log(Level.INFO, "sessionOpened()");
return new Date();
}
@Override
public void sessionClosed(Object session, SyslogServerIF syslogServer, SocketAddress socketAddress, boolean timeout) {
Logger.getLogger(getClass().getSimpleName()).log(Level.INFO, "sessionClosed() {0}", session);
}
@Override
public void initialize(SyslogServerIF syslogServer) {
Logger.getLogger(getClass().getSimpleName()).log(Level.INFO, "initialize()");
}
@Override
public void destroy(SyslogServerIF syslogServer) {
Logger.getLogger(getClass().getSimpleName()).log(Level.INFO, "destroy()");
}
最后在 syslog4j 配置中将该新类注册为 EventHandler:
eventHandler = new SyslogMessageHandler();
config.addEventHandler(eventHandler);
然后你就可以开始测试和调试你的各种格式和模式了:)