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