001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements. See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache license, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License. You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the license for the specific language governing permissions and
015 * limitations under the license.
016 */
017package org.apache.logging.log4j.core.pattern;
018
019import java.lang.management.ManagementFactory;
020
021import org.apache.logging.log4j.core.LogEvent;
022import org.apache.logging.log4j.core.config.plugins.Plugin;
023
024/**
025 * Returns the relative time in milliseconds since JVM Startup.
026 */
027@Plugin(name = "RelativeTimePatternConverter", category = PatternConverter.CATEGORY)
028@ConverterKeys({ "r", "relative" })
029public class RelativeTimePatternConverter extends LogEventPatternConverter {
030    /**
031     * Cached formatted timestamp.
032     */
033    private long lastTimestamp = Long.MIN_VALUE;
034    private final long startTime = ManagementFactory.getRuntimeMXBean().getStartTime();
035    private String relative;
036
037    /**
038     * Private constructor.
039     */
040    public RelativeTimePatternConverter() {
041        super("Time", "time");
042    }
043
044    /**
045     * Obtains an instance of RelativeTimePatternConverter.
046     *
047     * @param options options, currently ignored, may be null.
048     * @return instance of RelativeTimePatternConverter.
049     */
050    public static RelativeTimePatternConverter newInstance(
051        final String[] options) {
052        return new RelativeTimePatternConverter();
053    }
054
055    /**
056     * {@inheritDoc}
057     */
058    @Override
059    public void format(final LogEvent event, final StringBuilder toAppendTo) {
060        final long timestamp = event.getTimeMillis();
061
062        synchronized (this) {
063            if (timestamp != lastTimestamp) {
064                lastTimestamp = timestamp;
065                relative = Long.toString(timestamp - startTime);
066            }
067        }
068        toAppendTo.append(relative);
069    }
070}