View Javadoc

1   /**
2    * Logback: the reliable, generic, fast and flexible logging framework.
3    * Copyright (C) 1999-2011, QOS.ch. All rights reserved.
4    *
5    * This program and the accompanying materials are dual-licensed under
6    * either the terms of the Eclipse Public License v1.0 as published by
7    * the Eclipse Foundation
8    *
9    *   or (per the licensee's choosing)
10   *
11   * under the terms of the GNU Lesser General Public License version 2.1
12   * as published by the Free Software Foundation.
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   * Given a key and a date-and-time pattern, puts a property to the context, with
25   * the specified key and value equal to the current time in the format
26   * corresponding to the specified date-and-time pattern.
27   * 
28   * @author Ceki Gülcü
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  }