View Javadoc
1   /**
2    * Logback: the reliable, generic, fast and flexible logging framework.
3    * Copyright (C) 1999-2015, QOS.ch. All rights reserved.
4    *
5    * This program and the accompanying materials are dual-licensed under
6    * either the terms of the Eclipse Public License v1.0 as published by
7    * the Eclipse Foundation
8    *
9    *   or (per the licensee's choosing)
10   *
11   * under the terms of the GNU Lesser General Public License version 2.1
12   * as published by the Free Software Foundation.
13   */
14  package ch.qos.logback.classic.pattern;
15  
16  import java.time.ZoneId;
17  import java.util.List;
18  import java.util.Locale;
19  
20  import ch.qos.logback.classic.spi.ILoggingEvent;
21  import ch.qos.logback.core.CoreConstants;
22  import ch.qos.logback.core.util.CachingDateFormatter;
23  
24  public class DateConverter extends ClassicConverter {
25  
26      long lastTimestamp = -1;
27      String timestampStrCache = null;
28      CachingDateFormatter cachingDateFormatter = null;
29  
30      public void start() {
31  
32          String datePattern = getFirstOption();
33          if (datePattern == null) {
34              datePattern = CoreConstants.ISO8601_PATTERN;
35          }
36  
37          if (datePattern.equals(CoreConstants.ISO8601_STR)) {
38              datePattern = CoreConstants.ISO8601_PATTERN;
39          }
40  
41          List<String> optionList = getOptionList();
42          ZoneId zoneId = null;
43          // if the option list contains a TZ option, then set it.
44          if (optionList != null && optionList.size() > 1) {
45              String zoneIdString = (String) optionList.get(1);
46              zoneId = ZoneId.of(zoneIdString);
47              addInfo("Setting zoneId to \""+zoneId+"\"");
48          }
49  
50          Locale locale = null;
51          if (optionList != null && optionList.size() > 2) {
52              String localeIdStr = (String) optionList.get(2);
53              locale = Locale.forLanguageTag(localeIdStr);
54              addInfo("Setting locale to \""+locale+"\"");
55          }
56          try {
57              // if zoneId is null, the CachingDateFormatter will use the ZoneId.systemDefault()
58              cachingDateFormatter = new CachingDateFormatter(datePattern, zoneId, locale);
59          } catch (IllegalArgumentException e) {
60              addWarn("Could not instantiate SimpleDateFormat with pattern " + datePattern, e);
61              // default to the ISO8601 format
62              cachingDateFormatter = new CachingDateFormatter(CoreConstants.ISO8601_PATTERN, zoneId);
63          }
64  
65          super.start();
66      }
67  
68      public String convert(ILoggingEvent le) {
69          long timestamp = le.getTimeStamp();
70          return cachingDateFormatter.format(timestamp);
71      }
72  }