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.util.HashMap;
020import java.util.Locale;
021import java.util.Map;
022
023import org.apache.logging.log4j.Level;
024import org.apache.logging.log4j.core.LogEvent;
025import org.apache.logging.log4j.core.config.plugins.Plugin;
026
027/**
028 * Returns the event's level in a StringBuilder.
029 */
030@Plugin(name = "LevelPatternConverter", category = "Converter")
031@ConverterKeys({ "p", "level" })
032public final class LevelPatternConverter extends LogEventPatternConverter {
033    private static final String OPTION_LENGTH = "length";
034    private static final String OPTION_LOWER = "lowerCase";
035
036    /**
037     * Singleton.
038     */
039    private static final LevelPatternConverter INSTANCE = new LevelPatternConverter(null);
040
041    private final Map<Level, String> levelMap;
042
043    /**
044     * Private constructor.
045     */
046    private LevelPatternConverter(final Map<Level, String> map) {
047        super("Level", "level");
048        this.levelMap = map;
049    }
050
051    /**
052     * Obtains an instance of pattern converter.
053     *
054     * @param options
055     *            options, may be null. May contain a list of level names and The value that should be displayed for the
056     *            Level.
057     * @return instance of pattern converter.
058     */
059    public static LevelPatternConverter newInstance(final String[] options) {
060        if (options == null || options.length == 0) {
061            return INSTANCE;
062        }
063        final Map<Level, String> levelMap = new HashMap<Level, String>();
064        int length = Integer.MAX_VALUE; // More than the longest level name.
065        boolean lowerCase = false;
066        final String[] definitions = options[0].split(",");
067        for (final String def : definitions) {
068            final String[] pair = def.split("=");
069            if (pair == null || pair.length != 2) {
070                LOGGER.error("Invalid option {}", def);
071                continue;
072            }
073            final String key = pair[0].trim();
074            final String value = pair[1].trim();
075            if (OPTION_LENGTH.equalsIgnoreCase(key)) {
076                length = Integer.parseInt(value);
077            } else if (OPTION_LOWER.equalsIgnoreCase(key)) {
078                lowerCase = Boolean.parseBoolean(value);
079            } else {
080                final Level level = Level.toLevel(key, null);
081                if (level == null) {
082                    LOGGER.error("Invalid Level {}", key);
083                } else {
084                    levelMap.put(level, value);
085                }
086            }
087        }
088        if (levelMap.size() == 0 && length == Integer.MAX_VALUE && !lowerCase) {
089            return INSTANCE;
090        }
091        for (final Level level : Level.values()) {
092            if (!levelMap.containsKey(level)) {
093                final String left = left(level, length);
094                levelMap.put(level, lowerCase ? left.toLowerCase(Locale.US) : left);
095            }
096        }
097        return new LevelPatternConverter(levelMap);
098    }
099
100    /**
101     * Returns the leftmost chars of the level name for the given level.
102     *
103     * @param level
104     *            The level
105     * @param length
106     *            How many chars to return
107     * @return The abbreviated level name, or the whole level name if the {@code length} is greater than the level name
108     *         length,
109     */
110    private static String left(final Level level, int length) {
111        final String string = level.toString();
112        if (length >= string.length()) {
113            return string;
114        }
115        return string.substring(0, length);
116    }
117
118    /**
119     * {@inheritDoc}
120     */
121    @Override
122    public void format(final LogEvent event, final StringBuilder output) {
123        output.append(levelMap == null ? event.getLevel().toString() : levelMap.get(event.getLevel()));
124    }
125
126    /**
127     * {@inheritDoc}
128     */
129    @Override
130    public String getStyleClass(final Object e) {
131        if (e instanceof LogEvent) {
132            return "level " + ((LogEvent) e).getLevel().name().toLowerCase(Locale.ENGLISH);
133        }
134
135        return "level";
136    }
137}