문제

Is it possible to specify the time zone that log4j will use? I need the dates in the log file to be a different time zone than the application's. log4j's PatternLayout uses SimpleDateFormat. Unfortunately there doesn't appear to be a way to control SimpleDateFormat's time zone via the pattern string (DateFormat has setTimeZone method but that doesn't help).

I looked at log4j's source and SimpleDateFormat is being instiantiated in PatternParser.finalizeConverter. Unfortunately there's not an easy way to get a hold of the DateFormat to set the time zone.

도움이 되었습니까?

해결책

If you use the Log4J extras JAR file on your classpath, the EnhancedPatternLayout class supports this configuration option. See the Javadoc at this link. It's handled as part of the %d pattern component like this:

log4j.appender.stdout.layout.ConversionPattern=%d{}{America/New_York} %p [%c] - %m%n

You can download the extras package here.

다른 팁

My Case... must change the patternLayout to EnhancedPatternLayout. (log4j-1.2.17.jar)

log4j.appender.logfile.layout=org.apache.log4j.EnhancedPatternLayout log4j.appender.logfile.layout.ConversionPattern=[%d{ISO8601}{GMT+9}]%-5p - %m%n

The log pattern above has right idea but not fully correct (you don't get any timestamp in log).
Use this pattern for sure:
%d{ISO8601}{America/New_York} %p [%c] - %m%n
or
%d{ISO8601}{GMT-5} %p [%c] - %m%n

It is preferable to use something like {America/New_York} rather than {GMT-5} because by specifying a timezone an automatic adjustment will be made if daylight savings is operational. Specifying something like GMT-5 will simply adjust the GMT time zone by the specified amount of hours.

Also if you whant to dinamicaly obtein the default time zone, you can extend EnhancedPatternLayout and overwrite the method "setConversionPattern" like this:

@Override
public void setConversionPattern(String conversionPattern) {
    String defaultTimeZoneId = TimeZone.getDefault().getID();
    String conversionPatternModif = conversionPattern.replaceAll(
        "\\%d\\{([^\\{\\}]*)\\}([ ]*[^\\{]*)", 
        "%d{$1}{"+defaultTimeZoneId+"}$2");

    super.setConversionPattern(conversionPatternModif);
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top