1
2
3
4
5
6
7
8
9
10 package ch.qos.logback.classic.pattern;
11
12 import java.text.SimpleDateFormat;
13 import java.util.Date;
14 import java.util.List;
15 import java.util.TimeZone;
16
17 import ch.qos.logback.classic.spi.LoggingEvent;
18 import ch.qos.logback.core.CoreConstants;
19
20
21 public class DateConverter extends ClassicConverter {
22
23 long lastTimestamp = -1;
24 String timesmapStr = null;
25 SimpleDateFormat simpleFormat = null;
26
27 public void start() {
28
29 String datePattern = getFirstOption();
30 if(datePattern == null) {
31 datePattern = CoreConstants.ISO8601_PATTERN;
32 }
33
34 if (datePattern.equals(CoreConstants.ISO8601_STR)) {
35 datePattern = CoreConstants.ISO8601_PATTERN;
36 }
37
38 try {
39 simpleFormat = new SimpleDateFormat(datePattern);
40
41 } catch (IllegalArgumentException e) {
42 addWarn("Could not instantiate SimpleDateFormat with pattern " + datePattern, e);
43
44 simpleFormat = new SimpleDateFormat(CoreConstants.ISO8601_PATTERN);
45 }
46
47 List optionList = getOptionList();
48
49
50 if (optionList != null && optionList.size() > 1) {
51 TimeZone tz = TimeZone.getTimeZone((String) optionList.get(1));
52 simpleFormat.setTimeZone(tz);
53 }
54 }
55
56 public String convert(LoggingEvent le) {
57 long timestamp = le.getTimeStamp();
58
59
60
61 if(timestamp == lastTimestamp) {
62 return timesmapStr;
63 } else {
64 lastTimestamp = timestamp;
65
66
67
68 timesmapStr = simpleFormat.format(new Date(timestamp));
69 return timesmapStr;
70 }
71 }
72 }