您的位置 首页 java

时区问题-改变JVM默认时区是否影响log4j打印日志中的日期时间?

引言

在【 】描述了由于代码BUG导致存储到数据库的时间比正常时间少八小时的案例。当时分析的时候发现 log4j 打印的日志文件中日期时间都是正确的,下面对这个问题进行下验证和分析。

测试环境

Java version

  java  version "1.8.0_341"
Java(TM) SE Runtime Environment (build 1.8.0_341-b10)
Java HotSpot(TM) Client VM (build 25.341-b10, mixed mode, sharing)  

pom

 <dependency>
    <groupId>org. apache .logging.log4j</groupId>
    <artifactId>log4j-api</artifactId>
    <version>2.19.0</version>
</dependency>
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-core</artifactId>
    <version>2.19.0</version>
</dependency>  

测试代码&配置

 import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.TimeZone;

public class Log4jTimezoneTest {
     private   static  Logger LOGGER = LogManager.getLogger();
    public static  void  main(String[] args){
        // JVM默认时区:东八区
        LOGGER.info("Hello World!");
        
        // 模拟应用问题场景:改变JVM默认时区
        TimeZone.setDefault(TimeZone.getTimeZone("GMT"));
        LOGGER.info("Hello World!");
    }
}  
 <?xml version="1.0" encoding="UTF-8"?>
<Configuration>
    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            < Pattern Layout pattern="%d [%t] %-5level %c:%M(%L) - %msg%n"/>
        </Console>
    </Appenders>
    <Loggers>
        <Root level="DEBUG">
            <AppenderRef ref="Console"/>
        </Root>
    </Loggers>
</Configuration>  

分析过程

FixedDateFormat

一路跟踪代码,最终格式化日期时间的类是:org.apache.logging.log4j.core.util.datetime.FixedDateFormat。

基本使用

 import org.apache.logging.log4j.core.util.datetime.FixedDateFormat;
import java.util.TimeZone;

public class TimeZoneTest {
    public static void main(String[] args){
        long time = System.currentTimeMillis();
    // 默认时区为 东八区 
        FixedDateFormat fixedDateFormat = FixedDateFormat.createIfSupported(null);
         String  str = fixedDateFormat.format(time);
        System.out.println(str);

        // 改变默认时区为零时区
        TimeZone.setDefault(TimeZone.getTimeZone("GMT"));
        fixedDateFormat = FixedDateFormat.createIfSupported(null);
        str = fixedDateFormat.format(time);
        System.out.println(str);
    }
}  

初始化

时区问题-改变JVM默认时区是否影响log4j打印日志中的日期时间?

创建FixedDateFormat实例

FixedDateFormat在初始化的时候配置了时区信息。

FixedFormat

枚举类型,定义了日期时间的各种样式。下面以 FixedFormat.ISO8601 为例解释下各个字段的含义:

 ISO8601("yyyy-MM-dd'T'HH:mm:ss,SSS", "yyyy-MM-dd'T'", 2, ':', 1, ',', 1, 3, null)  

字段

字段示例

说明

pattern

yyyy-MM-dd’T’HH:mm:ss,SSS

日期时间格式

datePattern

yyyy-MM-dd’T’

日期格式

escapeCount

2

pattern中 T 两边单引号的个数

timeSeparator

:

小时与分钟、分钟与秒之间的分隔符

timeSepLength

1

timeSeparator字符长度

millisSeparator

,

秒与毫秒之间的分隔符

millisSepLength

1

millisSeparator字符长度

secondFractionDigits

3

millisSeparator后面时间字符的长度

timeZoneFormat

null,其他示例:+08、+0800、+08:00

日期时间格式中是否显示时区信息,类型为FixedTimeZoneFormat,三种样式:HH、HHMM、HHCMM

format

格式化日期流程

1.初始化char数组

 // double size for locales with lengthy DateFormatSymbols
final char[] result = new char[length << 1];  

char数组用于存放格式化后的pattern数据。

2.计算从当天午夜开始的毫秒数

midnightToday:当天午夜时间戳,默认值为0;
midnightTomorrow:明天午夜时间戳,默认值为0;
这里是个缓存的逻辑:
如果待格式化的时间戳在midnightToday和midnightTomorrow之间,则直接返回:【待格式化时间戳】减去【midnightToday】;否则执行下面计算并缓存相应的值:

2.2.1格式化日期并缓存

对于一个时间戳来说从零点到24点之间,日期部分是不变的,所以解析并缓存起来。

 private void updateCachedDate(final long now) {
    if (fastDateFormat != null) {
        final  StringBuilder  result = fastDateFormat.format(now, new StringBuilder());
        cachedDate = result.toString().toCharArray();
        dateLength = result.length();
    }
}  

2.2.2计算当前午夜时间戳

 midnightToday = calcMidnightMillis(now, 0);  

计算午夜时间戳

2.2.3计算明天午夜时间戳

与2.2.2不同的是addDays是1。

 midnightTomorrow = calcMidnightMillis(now, 1);  

2.3时间戳【减】当前午夜时间戳

 return currentTime - midnightToday;  

3.将缓存的日期写入 字符数组

 private void writeDate(final char[] buffer, final int startPos) {
    if (cachedDate != null) {
        System.array copy (cachedDate, 0, buffer, startPos, dateLength);
    }
}  

4.将【午夜开始的毫秒数】转换为时、分、秒… …

计算时分秒及毫秒

小结

FixedDateFormat在初始化的时候对时区进行了配置,当系统默认时区变化的时候,并不会影响到FixedDateFormat中的时区配置。

Benchmark

在日常开发中,少不了日期时间格式化,通常的使用方式:

  • SimpleDateFormat,非线程安全
  • DateTimeFormatter,线程安全
  • log4j中FixedDateFormat、FastDateFormat

不同格式化类的性能测试

一起讨论

假设现在有一套系统部署在东八区,由于业务需求,需要在零时区也部署一套,涉及到时区方面如何考虑?

国际化

文章来源:智云一二三科技

文章标题:时区问题-改变JVM默认时区是否影响log4j打印日志中的日期时间?

文章地址:https://www.zhihuclub.com/180600.shtml

关于作者: 智云科技

热门文章

网站地图