/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.juli;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.TreeMap;
import java.util.logging.Formatter;
import java.util.logging.Level;
import java.util.logging.LogRecord;

/**
 * Formatter suitable for logs handled by systemd/journald:
 * <ul>
 *   <li>Timestamps are removed (already added by journald)</li>
 *   <li>Messages are prefixed with a marker specifying the log level. For example:
 *     <pre>    &lt;6&gt;Tomcat started</pre>
 *   </li>
 *   <li>Tabulations are replaced by spaces (they are escaped as <tt>#011</tt> in /var/log/syslog otherwise)</li>
 * </ul>
 *
 * If systemd isn't enabled the format falls back to the default one-line format.
 */
public class SystemdFormatter extends Formatter {

    /** Default formatter if Tomcat isn't managed by systemd */
    private final Formatter defaultFormatter = new OneLineFormatter();

    private boolean systemdEnabled = System.getenv("INVOCATION_ID") != null && System.getenv("JOURNAL_STREAM") != null;

    /** Mapping between JUL levels and systemd logging levels */
    private TreeMap<Integer, String> levelMapping = new TreeMap<>();
    {
        levelMapping.put(Level.OFF.intValue(),     "<0>"); // emergency
        levelMapping.put(Level.SEVERE.intValue(),  "<2>"); // critical
        levelMapping.put(Level.WARNING.intValue(), "<4>"); // warning
        levelMapping.put(Level.INFO.intValue(),    "<6>"); // info
        levelMapping.put(Level.CONFIG.intValue(),  "<6>"); // info
        levelMapping.put(Level.FINE.intValue(),    "<7>"); // debug
        levelMapping.put(Level.FINER.intValue(),   "<7>"); // debug
        levelMapping.put(Level.FINEST.intValue(),  "<7>"); // debug
    }

    @Override
    public String format(LogRecord record) {
        if (!systemdEnabled) {
            return defaultFormatter.format(record);
        }

        StringBuilder sb = new StringBuilder();

        // Severity
        String prefix = getSystemdLevel(record.getLevel());
        sb.append(prefix);

        // Message
        sb.append(formatMessage(record));

        // Stack trace
        if (record.getThrown() != null) {
            sb.append("\n").append(prefix);
            sb.append(toString(record.getThrown())
                            .replaceAll("\t", "    ")       // tabulations are escaped as #011 in /var/log/syslog
                            .replaceAll("\\n", "\n" + prefix)
            );
        }

        // New line for next record
        sb.append(System.lineSeparator());

        return sb.toString();
    }

    private String toString(Throwable t) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        t.printStackTrace(pw);
        pw.close();

        return sw.toString();
    }

    /**
     * Returns the systemd log level mapped to the specified JUL level.
     */
    private String getSystemdLevel(Level level) {
        String systemdLevel = levelMapping.get(level.intValue());
        if (systemdLevel == null) {
            // no exact match (custom level?), pick the nearest one above
            systemdLevel = levelMapping.ceilingEntry(level.intValue()).getValue();
            levelMapping.put(level.intValue(), systemdLevel);
        }
        return systemdLevel;
    }
}
