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 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 SimpleLevelPatternConverter();
043
044    /**
045     * Private constructor.
046     */
047    private LevelPatternConverter() {
048        super("Level", "level");
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<>();
064        int length = Integer.MAX_VALUE; // More than the longest level name.
065        boolean lowerCase = false;
066        final String[] definitions = options[0].split(Patterns.COMMA_SEPARATOR);
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.isEmpty() && 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 LevelMapLevelPatternConverter(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, final 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        throw new UnsupportedOperationException("Overridden by subclasses");
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
138    private static final class SimpleLevelPatternConverter extends LevelPatternConverter {
139
140        /**
141         * {@inheritDoc}
142         */
143        @Override
144        public void format(final LogEvent event, final StringBuilder output) {
145            output.append(event.getLevel());
146        }
147    }
148
149    private static final class LevelMapLevelPatternConverter extends LevelPatternConverter {
150
151        private final Map<Level, String> levelMap;
152
153        private LevelMapLevelPatternConverter(final Map<Level, String> levelMap) {
154            this.levelMap = levelMap;
155        }
156
157        /**
158         * {@inheritDoc}
159         */
160        @Override
161        public void format(final LogEvent event, final StringBuilder output) {
162            output.append(levelMap.get(event.getLevel()));
163        }
164    }
165}