1
2
3
4
5
6
7
8
9
10
11
12
13
14 package ch.qos.logback.core.joran.action;
15
16 import ch.qos.logback.core.util.CachingDateFormatter;
17 import org.xml.sax.Attributes;
18
19 import ch.qos.logback.core.joran.spi.ActionException;
20 import ch.qos.logback.core.joran.spi.InterpretationContext;
21 import ch.qos.logback.core.util.OptionHelper;
22
23
24
25
26
27
28
29
30
31 public class TimestampAction extends Action {
32 static String DATE_PATTERN_ATTRIBUTE = "datePattern";
33 static String TIME_REFERENCE_ATTRIBUTE = "timeReference";
34 static String CONTEXT_BIRTH = "contextBirth";
35
36 boolean inError = false;
37
38 @Override
39 public void begin(InterpretationContext ec, String name, Attributes attributes)
40 throws ActionException {
41 String keyStr = attributes.getValue(KEY_ATTRIBUTE);
42 if (OptionHelper.isEmpty(keyStr)) {
43 addError("Attribute named [" + KEY_ATTRIBUTE + "] cannot be empty");
44 inError = true;
45 }
46 String datePatternStr = attributes.getValue(DATE_PATTERN_ATTRIBUTE);
47 if (OptionHelper.isEmpty(datePatternStr)) {
48 addError("Attribute named [" + DATE_PATTERN_ATTRIBUTE
49 + "] cannot be empty");
50 inError = true;
51 }
52
53 String timeReferenceStr = attributes.getValue(TIME_REFERENCE_ATTRIBUTE);
54 long timeReference;
55 if (CONTEXT_BIRTH.equalsIgnoreCase(timeReferenceStr)) {
56 addInfo("Using context birth as time reference.");
57 timeReference = context.getBirthTime();
58 } else {
59 timeReference = System.currentTimeMillis();
60 addInfo("Using current interpretation time, i.e. now, as time reference.");
61 }
62
63
64 if (inError)
65 return;
66
67 CachingDateFormatter sdf = new CachingDateFormatter(datePatternStr);
68 String val = sdf.format(timeReference);
69
70 addInfo("Adding property to the context with key=\"" + keyStr
71 + "\" and value=\"" + val + "\" to the context");
72 context.putProperty(keyStr, val);
73 }
74
75 @Override
76 public void end(InterpretationContext ec, String name) throws ActionException {
77 }
78
79 }