SocketAppender and PatternLayout

一个人想着一个人 提交于 2019-12-05 14:44:23

It seems that SocketAppender don't use a layout.

SocketAppenders do not use a layout. They ship a serialized LoggingEvent object to the server side.

See documentation here


So I use a SyslogAppender to replace. It's not perfect because of unused possibilies (like facility and priority) but works fine.

As a workaround,

  • For Log4j 1.x
  • Copy SocketAppender code to your local project
  • Change, "requiresLayout" method as

        public boolean requiresLayout() {
                return true;
        }
    
  • Change append method as ;

     public void append(LoggingEvent event) {
    
        ///......
    
        event.getThrowableStrRep();
    
        if (this.layout == null) {
            errorHandler.error("No layout for appender " + name,
                    null, ErrorCode.MISSING_LAYOUT);
            return;
        }
    
        String message = this.layout.format(event);
    
        oos.writeObject(message);
        ///...... 
     }
    
  • Set this class as your appender.

  • Now on, you can set any layout to this appender.

Hope it helps.

Workaround that @myuce posted is working, but you also need to replace ObjectOutputStream (OOS) within "standard" OutputStream (OS).

You can check inside OOS - it's prepending output with some additional stuff for "the receiver".

??t?{"@timestamp":"2018-03-27T14...

So... I've just replaced (it's scala in my case):

oos = new ObjectOutputStream(new Socket(address, port).getOutputStream()); and oos = new ObjectOutputStream(socket.getOutputStream());

within: stream = new Socket(address, port).getOutputStream and stream = socket.getOutputStream (and variable name [of course every occurrence;] for clarity).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!