1
2
3
4
5
6
7
8
9
10
11
12
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 CachingDateFormatter cachingDateFormatter = null;
27
28 public void start() {
29
30 String datePattern = getFirstOption();
31
32 if (datePattern == null) {
33 datePattern = CoreConstants.ISO8601_PATTERN;
34 } else if (datePattern.equals(CoreConstants.ISO8601_STR)) {
35 datePattern = CoreConstants.ISO8601_PATTERN;
36 } else if (datePattern.equals(CoreConstants.STRICT_STR)) {
37 datePattern = CoreConstants.STRICT_ISO8601_PATTERN;
38 }
39
40 List<String> optionList = getOptionList();
41 ZoneId zoneId = null;
42
43 if (optionList != null && optionList.size() > 1) {
44 String zoneIdString = (String) optionList.get(1);
45 zoneId = ZoneId.of(zoneIdString);
46 addInfo("Setting zoneId to \""+zoneId+"\"");
47 }
48
49 Locale locale = null;
50 if (optionList != null && optionList.size() > 2) {
51 String localeIdStr = (String) optionList.get(2);
52 locale = Locale.forLanguageTag(localeIdStr);
53 addInfo("Setting locale to \""+locale+"\"");
54 }
55 try {
56
57
58 cachingDateFormatter = new CachingDateFormatter(datePattern, zoneId, locale);
59 } catch (IllegalArgumentException e) {
60 addWarn("Could not instantiate SimpleDateFormat with pattern " + datePattern, e);
61
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 }