how to change htmllayout in log4j2

前端 未结 1 1885
借酒劲吻你
借酒劲吻你 2020-12-20 09:29

When I use log4j, I can create a new class extends org.apache.log4j.HTMLLayout and override it to make a new format of the log. When using log4j2, I can only use the layout

相关标签:
1条回答
  • 2020-12-20 10:13

    Here is what i did, I needed to add <img> HTML tags in logs generated by log4j2 and by default HTML elements like <, >, " are replaced by escape characters like lt; , gt; , quot;. (Ref:https://issues.apache.org/jira/browse/LOG4J2-439)

    So i just copied whole HTMLLayout class from source, which is available at log4j-core / src / main / java / org / apache / logging / log4j / core / layout

    and changed its name to "CustomHTMLLayout" and updated it wherever required (you can choose any name), now your custom layout class is as good as HTMLLayout class.

    there is method called toSerializable which contains actual formatting of each record, so you can manipulate it as per your need.

    once class is modified, you need to provide the new layout in your log4j2.html as following:

    <?xml version="1.0" encoding="UTF-8"?> 
    <Configuration packages="com.redknee.bssauto.helpers"> 
    <Appenders> 
    <RollingFile name="Rolling-default" fileName="logs/bssauto.html" filePattern="logs/$${date:yyyy-MM}/bssauto-%d{MM-dd-yyyy}-%i.log.gz">
    <CustomHTMLLayout charset="UTF-8" title="BSSAuto Logs" locationInfo="true" />
     <Policies>
       <TimeBasedTriggeringPolicy />
       <SizeBasedTriggeringPolicy size="10 MB" />
     </Policies>
    </RollingFile>      
    </Appenders> 
    <Loggers> 
    <Root level="trace"> 
      <AppenderRef ref="Rolling-default"/>
    </Root> 
    </Loggers> 
    </Configuration>
    

    Notice following

    <Configuration packages="com.bssauto.helpers">
    

    here packages should have all packages containing custom class for layouts. so here com.bssauto.helpers is package under which i have CustomHTMLLayout class.

    <CustomHTMLLayout charset="UTF-8" title="BSSAuto Logs" locationInfo="true" />
    

    and CustomHTMLLayout is custom layout class created by extending AbstractStringLayout

    Make sure you are using latest log4j2 version, I used log4j 2.2

    0 讨论(0)
提交回复
热议问题