View Javadoc

1   /**
2    * LOGBack: the reliable, fast and flexible logging library for Java.
3    *
4    * Copyright (C) 1999-2006, QOS.ch
5    *
6    * This library is free software, you can redistribute it and/or
7    * modify it under the terms of the GNU Lesser General Public License as
8    * published by the Free Software Foundation.
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        //maximumCacheValidity = CachedDateFormat.getMaximumCacheValidity(pattern);
42      } catch (IllegalArgumentException e) {
43        addWarn(
44          "Could not instantiate SimpleDateFormat with pattern " + datePattern, e);
45        // default to the ISO8601 format
46        simpleFormat = new SimpleDateFormat(CoreConstants.CLF_DATE_PATTERN);
47      }
48      
49      List optionList = getOptionList();
50      
51      // if the option list contains a TZ option, then set it.
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      // if called multiple times within the same millisecond
64      // return old value
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  }