1
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.action.ActionUtil.Scope;
20 import ch.qos.logback.core.joran.spi.ActionException;
21 import ch.qos.logback.core.joran.spi.InterpretationContext;
22 import ch.qos.logback.core.util.OptionHelper;
23
24
32 public class TimestampAction extends Action {
33 static String DATE_PATTERN_ATTRIBUTE = "datePattern";
34 static String TIME_REFERENCE_ATTRIBUTE = "timeReference";
35 static String CONTEXT_BIRTH = "contextBirth";
36
37 boolean inError = false;
38
39 @Override
40 public void begin(InterpretationContext ec, String name, Attributes attributes) 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 + "] cannot be empty");
49 inError = true;
50 }
51
52 String timeReferenceStr = attributes.getValue(TIME_REFERENCE_ATTRIBUTE);
53 long timeReference;
54 if (CONTEXT_BIRTH.equalsIgnoreCase(timeReferenceStr)) {
55 addInfo("Using context birth as time reference.");
56 timeReference = context.getBirthTime();
57 } else {
58 timeReference = System.currentTimeMillis();
59 addInfo("Using current interpretation time, i.e. now, as time reference.");
60 }
61
62 if (inError)
63 return;
64
65 String scopeStr = attributes.getValue(SCOPE_ATTRIBUTE);
66 Scope scope = ActionUtil.stringToScope(scopeStr);
67
68 CachingDateFormatter sdf = new CachingDateFormatter(datePatternStr);
69 String val = sdf.format(timeReference);
70
71 addInfo("Adding property to the context with key=\"" + keyStr + "\" and value=\"" + val + "\" to the " + scope + " scope");
72 ActionUtil.setProperty(ec, keyStr, val, scope);
73 }
74
75 @Override
76 public void end(InterpretationContext ec, String name) throws ActionException {
77 }
78
79 }
80