Log4J Custom Fields

后端 未结 3 1681
再見小時候
再見小時候 2020-12-15 06:08

Introduction:

I\'m trying to get additional fields to log with log4j, and its working but only when I create an appender in code and not in the log4j.properties

相关标签:
3条回答
  • 2020-12-15 07:07

    I'm not sure that you will achieve this with properties configuration, but I think you can do this with XML, which gives you a lot of customization options:

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
    <log4j:configuration
      xmlns:log4j="http://jakarta.apache.org/log4j/"
      debug="true"
      reset="true"
    >
      <appender name="stdout" class="org.apache.log4j.ConsoleAppender">
        <param name="Target" value="System.out"/>
        <layout class="your.package.AppServerPatternLayout">
          <param name="ConversionPattern" value="YOUR CONVERSION PATTERN"/>
        </layout>
      </appender>
    
      <root>
        <level value="info"/>
        <appender-ref ref="stdout" />
      </root>
    
      <loggerFactory class="your.package.AppServerLoggerFactory">
        <param name="server" value="MyServer"/>
        <param name="component" value="MyComponent"/>
        <param name="version" value="1.0r"/>
      </loggerFactory>
    
    </log4j:configuration>
    

    You will need to define setters on AppServerLoggerFactory for server, component and version. Also, read log4j.dtd on general layout of xml configuration file.

    Save this file as log4j.xml and define -Dlog4j.configuration=/path/to/log4j.xml in your startup script, or replace log4j.properties with log4j.xml in your web-app.

    I've never tried a custom LoggerFactory before, but it may be that because it is installed by the configurator you can use standard getLogger factory calls, e.g.

    //Logger logger = AppServerLogger.getLogger("some.log");
    Logger logger = Logger.getLogger("some.log");
    
    0 讨论(0)
  • 2020-12-15 07:13

    From the example you posted, I can only guess that AppServerPatternLayout is not in the package logging. Everything else looks find. Add

    log4j.DEBUG=true
    

    to your properties file. log4j will then dump what it does while reading the properties. Maybe that gives you an idea what's wrong.

    If that doesn't help, consider to use Nested Diagnostic Contexts.

    0 讨论(0)
  • 2020-12-15 07:14

    Can it be that when you load via properties the AppServerPatternLayout is instantiated before the AppServerLoggerFactory is created? If you pick up the values of your custom fields at creation as opposed to at first use that could be an explanation.

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