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.appender.rolling;
018
019import java.lang.reflect.Method;
020
021import org.apache.logging.log4j.core.Core;
022import org.apache.logging.log4j.core.LogEvent;
023import org.apache.logging.log4j.core.config.plugins.Plugin;
024import org.apache.logging.log4j.core.config.plugins.PluginAttribute;
025import org.apache.logging.log4j.core.config.plugins.PluginFactory;
026import org.apache.logging.log4j.core.util.Loader;
027import org.apache.logging.log4j.status.StatusLogger;
028
029/**
030 * Triggers a rollover on every restart, but only if the file size is greater than zero.
031 */
032@Plugin(name = "OnStartupTriggeringPolicy", category = Core.CATEGORY_NAME, printObject = true)
033public class OnStartupTriggeringPolicy extends AbstractTriggeringPolicy {
034
035    private static final long JVM_START_TIME = initStartTime();
036
037    private final long minSize;
038
039    private OnStartupTriggeringPolicy(final long minSize) {
040        this.minSize = minSize;
041    }
042
043    /**
044     * Returns the result of {@code ManagementFactory.getRuntimeMXBean().getStartTime()},
045     * or the current system time if JMX is not available.
046     */
047    private static long initStartTime() {
048        // LOG4J2-379:
049        // We'd like to call ManagementFactory.getRuntimeMXBean().getStartTime(),
050        // but Google App Engine throws a java.lang.NoClassDefFoundError
051        // "java.lang.management.ManagementFactory is a restricted class".
052        // The reflection is necessary because without it, Google App Engine
053        // will refuse to initialize this class.
054        try {
055            final Class<?> factoryClass = Loader.loadSystemClass("java.lang.management.ManagementFactory");
056            final Method getRuntimeMXBean = factoryClass.getMethod("getRuntimeMXBean");
057            final Object runtimeMXBean = getRuntimeMXBean.invoke(null);
058
059            final Class<?> runtimeMXBeanClass = Loader.loadSystemClass("java.lang.management.RuntimeMXBean");
060            final Method getStartTime = runtimeMXBeanClass.getMethod("getStartTime");
061            final Long result = (Long) getStartTime.invoke(runtimeMXBean);
062
063            return result;
064        } catch (final Throwable t) {
065            StatusLogger.getLogger().error("Unable to call ManagementFactory.getRuntimeMXBean().getStartTime(), "
066                    + "using system time for OnStartupTriggeringPolicy", t);
067            // We have little option but to declare "now" as the beginning of time.
068            return System.currentTimeMillis();
069        }
070    }
071
072    /**
073     * Provide the RollingFileManager to the policy.
074     * @param manager The RollingFileManager.
075     */
076    @Override
077    public void initialize(final RollingFileManager manager) {
078        if (manager.getFileTime() < JVM_START_TIME && manager.getFileSize() >= minSize) {
079            if (minSize == 0) {
080                manager.setRenameEmptyFiles(true);
081            }
082            manager.skipFooter(true);
083            manager.rollover();
084            manager.skipFooter(false);
085        }
086    }
087
088    /**
089     * Determine if a rollover should be triggered.
090     * @param event   A reference to the current event.
091     * @return true if the target file's timestamp is older than the JVM start time.
092     */
093    @Override
094    public boolean isTriggeringEvent(final LogEvent event) {
095        return false;
096    }
097
098    @Override
099    public String toString() {
100        return "OnStartupTriggeringPolicy";
101    }
102
103    @PluginFactory
104    public static OnStartupTriggeringPolicy createPolicy(
105            @PluginAttribute(value = "minSize", defaultLong = 1) final long minSize) {
106        return new OnStartupTriggeringPolicy(minSize);
107    }
108}