View Javadoc

1   /**
2    * Logback: the generic, reliable, fast and flexible logging framework.
3    * 
4    * Copyright (C) 1999-2006, QOS.ch
5    * 
6    * This library is free software, you can redistribute it and/or modify it under
7    * the terms of the GNU Lesser General Public License as published by the Free
8    * Software Foundation.
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        //maximumCacheValidity = CachedDateFormat.getMaximumCacheValidity(pattern);
41      } catch (IllegalArgumentException e) {
42        addWarn("Could not instantiate SimpleDateFormat with pattern " + datePattern, e);
43        // default to the ISO8601 format
44        simpleFormat = new SimpleDateFormat(CoreConstants.ISO8601_PATTERN);
45      }
46      
47      List optionList = getOptionList();
48      
49      // if the option list contains a TZ option, then set it.
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      // if called multiple times within the same millisecond
60      // return old value
61      if(timestamp == lastTimestamp) {
62        return timesmapStr;
63      } else {
64        lastTimestamp = timestamp;
65        // SimpleDateFormat is not thread safe. However, since
66        // the AppenderBase.doAppend is synchronized, we are should be
67        // OK. See also http://jira.qos.ch/browse/LBCLASSIC-36
68        timesmapStr = simpleFormat.format(new Date(timestamp));
69        return timesmapStr;
70      }
71    }
72  }