Specify time zone of log4j's date

2019-01-15 07:32发布

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.

5条回答
爷、活的狠高调
2楼-- · 2019-01-15 07:51

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);
}
查看更多
The star\"
3楼-- · 2019-01-15 07:57

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

查看更多
成全新的幸福
4楼-- · 2019-01-15 08:01

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.

查看更多
疯言疯语
5楼-- · 2019-01-15 08:04

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.

查看更多
Bombasti
6楼-- · 2019-01-15 08:10

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

查看更多
登录 后发表回答