如何解析syslog4j syslog服务器中的syslog消息

时间:2013-11-01 10:16:34

标签: parsing syslog rsyslog syslog4j

我想解析发送到syslog4J中实现的syslog服务器的syslog消息。可以在syslog4J中执行此操作吗?

我想要做的是能够隔离syslog消息中的各个字段,如主机名,时间戳,消息,严重性级别等,并制作统一的syslog模式以供将来分析。

这个功能之王在rsyslog或syslogNG中可用。

SyslogServerConfigIF config = new TCPNetSyslogServerConfig("0.0.0.0", 1455);
config.setUseStructuredData(true);

SyslogServerIF syslogserver = SyslogServer.getInstance("tcp");
syslogserver.initialize("tcp", config);
syslogserver.run();

1 个答案:

答案 0 :(得分:1)

首先创建一个新的Event Handler类来处理消息。请注意,解析应该在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 config中将新类注册为EventHandler:

eventHandler = new SyslogMessageHandler(); config.addEventHandler(eventHandler);

然后您就可以开始测试和调试各种格式和模式了:)