[Java] Resolve issue on escape character show when using LogstashEncoder

When passing data to LogStash, it will show escape character in log message. But sometime, it cannot update logstash pipeline to replace specific character so need to implement in code level.

This problem caused by escape character found in String. As LogstashEncoder will serialize object to JSON, it will replace escape ASCII character to encoded value (e.g. new line => \n).

To resolve it, it can use CharacterEscapesJsonFactoryDecorator in log settings file (e.g. log4j.xml) to override specific ASCII code and replaced by defined value.

This example will replace string to empty string.

 <appender name="console-json" class="ch.qos.logback.core.ConsoleAppender">
        <encoder class="net.logstash.logback.encoder.LogstashEncoder" >
            <jsonFactoryDecorator class="net.logstash.logback.decorate.CharacterEscapesJsonFactoryDecorator">
                <escape>
                    <!-- ASCII 10 => new line  -->
                    <targetCharacterCode>10</targetCharacterCode>
                    <escapeSequence></escapeSequence>
                </escape>
            </jsonFactoryDecorator>
        </encoder>
</appender>

Test result:

About C.H. Ling 260 Articles
a .net / Java developer from Hong Kong and currently located in United Kingdom. Thanks for Google because it solve many technical problems so I build this blog as return. Besides coding and trying advance technology, hiking and traveling is other favorite to me, so I will write down something what I see and what I feel during it. Happy reading!!!

Be the first to comment

Leave a Reply

Your email address will not be published.


*


This site uses Akismet to reduce spam. Learn how your comment data is processed.