001/** 002 * Logback: the reliable, generic, fast and flexible logging framework. 003 * Copyright (C) 1999-2015, QOS.ch. All rights reserved. 004 * 005 * This program and the accompanying materials are dual-licensed under 006 * either the terms of the Eclipse Public License v1.0 as published by 007 * the Eclipse Foundation 008 * 009 * or (per the licensee's choosing) 010 * 011 * under the terms of the GNU Lesser General Public License version 2.1 012 * as published by the Free Software Foundation. 013 */ 014package ch.qos.logback.classic.pattern; 015 016import java.time.ZoneId; 017import java.util.List; 018import java.util.Locale; 019 020import ch.qos.logback.classic.spi.ILoggingEvent; 021import ch.qos.logback.core.CoreConstants; 022import ch.qos.logback.core.util.CachingDateFormatter; 023 024public class DateConverter extends ClassicConverter { 025 026 long lastTimestamp = -1; 027 String timestampStrCache = null; 028 CachingDateFormatter cachingDateFormatter = null; 029 030 public void start() { 031 032 String datePattern = getFirstOption(); 033 034 if (datePattern == null) { 035 datePattern = CoreConstants.ISO8601_PATTERN; 036 } 037 038 if (datePattern.equals(CoreConstants.ISO8601_STR)) { 039 datePattern = CoreConstants.ISO8601_PATTERN; 040 } 041 042 if (datePattern.equals(CoreConstants.STRICT_STR)) { 043 datePattern = CoreConstants.STRICT_ISO8601_PATTERN; 044 } 045 046 List<String> optionList = getOptionList(); 047 ZoneId zoneId = null; 048 // if the option list contains a TZ option, then set it. 049 if (optionList != null && optionList.size() > 1) { 050 String zoneIdString = (String) optionList.get(1); 051 zoneId = ZoneId.of(zoneIdString); 052 addInfo("Setting zoneId to \""+zoneId+"\""); 053 } 054 055 Locale locale = null; 056 if (optionList != null && optionList.size() > 2) { 057 String localeIdStr = (String) optionList.get(2); 058 locale = Locale.forLanguageTag(localeIdStr); 059 addInfo("Setting locale to \""+locale+"\""); 060 } 061 try { 062 // if zoneId is null, the CachingDateFormatter will use the ZoneId.systemDefault() 063 cachingDateFormatter = new CachingDateFormatter(datePattern, zoneId, locale); 064 } catch (IllegalArgumentException e) { 065 addWarn("Could not instantiate SimpleDateFormat with pattern " + datePattern, e); 066 // default to the ISO8601 format 067 cachingDateFormatter = new CachingDateFormatter(CoreConstants.ISO8601_PATTERN, zoneId); 068 } 069 070 super.start(); 071 } 072 073 public String convert(ILoggingEvent le) { 074 long timestamp = le.getTimeStamp(); 075 return cachingDateFormatter.format(timestamp); 076 } 077}