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