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.access.pattern;
015
016import java.time.ZoneId;
017import java.util.List;
018
019import ch.qos.logback.access.spi.IAccessEvent;
020import ch.qos.logback.core.CoreConstants;
021import ch.qos.logback.core.util.CachingDateFormatter;
022
023public class DateConverter extends AccessConverter {
024
025    CachingDateFormatter cachingDateFormatter = null;
026
027    @Override
028    public void start() {
029
030        String datePattern = getFirstOption();
031        if (datePattern == null) {
032            datePattern = CoreConstants.CLF_DATE_PATTERN;
033        }
034
035        if (datePattern.equals(CoreConstants.ISO8601_STR)) {
036            datePattern = CoreConstants.ISO8601_PATTERN;
037        }
038        ZoneId zoneId = null;
039        List<String> optionList = getOptionList();
040
041        // if the option list contains a TZ option, then set it.
042        if (optionList != null && optionList.size() > 1) {
043            String zoneIdString = (String) optionList.get(1);
044            zoneId = ZoneId.of(zoneIdString);
045        }
046
047        try {
048            cachingDateFormatter = new CachingDateFormatter(datePattern, zoneId);
049            // maximumCacheValidity = CachedDateFormat.getMaximumCacheValidity(pattern);
050        } catch (IllegalArgumentException e) {
051            addWarn("Could not instantiate SimpleDateFormat with pattern " + datePattern, e);
052            addWarn("Defaulting to  " + CoreConstants.CLF_DATE_PATTERN);
053            cachingDateFormatter = new CachingDateFormatter(CoreConstants.CLF_DATE_PATTERN, zoneId);
054        }
055
056    }
057
058    @Override
059    public String convert(IAccessEvent accessEvent) {
060        long timestamp = accessEvent.getTimeStamp();
061        return cachingDateFormatter.format(timestamp);
062    }
063}