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;
018
019import java.io.Serializable;
020import java.util.Collection;
021import java.util.Locale;
022import java.util.Objects;
023import java.util.concurrent.ConcurrentHashMap;
024import java.util.concurrent.ConcurrentMap;
025
026import org.apache.logging.log4j.spi.StandardLevel;
027import org.apache.logging.log4j.util.Strings;
028
029/**
030 * Levels used for identifying the severity of an event. Levels are organized from most specific to least:
031 * <ul>
032 * <li>{@link #OFF} (most specific, no logging)</li>
033 * <li>{@link #FATAL} (most specific, little data)</li>
034 * <li>{@link #ERROR}</li>
035 * <li>{@link #WARN}</li>
036 * <li>{@link #INFO}</li>
037 * <li>{@link #DEBUG}</li>
038 * <li>{@link #TRACE} (least specific, a lot of data)</li>
039 * <li>{@link #ALL} (least specific, all data)</li>
040 * </ul>
041 *
042 * Typically, configuring a level in a filter or on a logger will cause logging events of that level and those that are
043 * more specific to pass through the filter. A special level, {@link #ALL}, is guaranteed to capture all levels when
044 * used in logging configurations.
045 */
046public final class Level implements Comparable<Level>, Serializable {
047
048    /**
049     * No events will be logged.
050     */
051    public static final Level OFF;
052
053    /**
054     * A severe error that will prevent the application from continuing.
055     */
056    public static final Level FATAL;
057
058    /**
059     * An error in the application, possibly recoverable.
060     */
061    public static final Level ERROR;
062
063    /**
064     * An event that might possible lead to an error.
065     */
066    public static final Level WARN;
067
068    /**
069     * An event for informational purposes.
070     */
071    public static final Level INFO;
072
073    /**
074     * A general debugging event.
075     */
076    public static final Level DEBUG;
077
078    /**
079     * A fine-grained debug message, typically capturing the flow through the application.
080     */
081    public static final Level TRACE;
082
083    /**
084     * All events should be logged.
085     */
086    public static final Level ALL;
087
088    /**
089     * @since 2.1
090     */
091    public static final String CATEGORY = "Level";
092
093    private static final ConcurrentMap<String, Level> LEVELS = new ConcurrentHashMap<>(); // SUPPRESS CHECKSTYLE
094
095    private static final long serialVersionUID = 1581082L;
096
097    static {
098        OFF = new Level("OFF", StandardLevel.OFF.intLevel());
099        FATAL = new Level("FATAL", StandardLevel.FATAL.intLevel());
100        ERROR = new Level("ERROR", StandardLevel.ERROR.intLevel());
101        WARN = new Level("WARN", StandardLevel.WARN.intLevel());
102        INFO = new Level("INFO", StandardLevel.INFO.intLevel());
103        DEBUG = new Level("DEBUG", StandardLevel.DEBUG.intLevel());
104        TRACE = new Level("TRACE", StandardLevel.TRACE.intLevel());
105        ALL = new Level("ALL", StandardLevel.ALL.intLevel());
106    }
107
108    private final String name;
109    private final int intLevel;
110    private final StandardLevel standardLevel;
111
112    private Level(final String name, final int intLevel) {
113        if (Strings.isEmpty(name)) {
114            throw new IllegalArgumentException("Illegal null or empty Level name.");
115        }
116        if (intLevel < 0) {
117            throw new IllegalArgumentException("Illegal Level int less than zero.");
118        }
119        this.name = name;
120        this.intLevel = intLevel;
121        this.standardLevel = StandardLevel.getStandardLevel(intLevel);
122        if (LEVELS.putIfAbsent(name, this) != null) {
123            throw new IllegalStateException("Level " + name + " has already been defined.");
124        }
125    }
126
127    /**
128     * Gets the integral value of this Level.
129     *
130     * @return the value of this Level.
131     */
132    public int intLevel() {
133        return this.intLevel;
134    }
135
136    /**
137     * Gets the standard Level values as an enum.
138     *
139     * @return an enum of the standard Levels.
140     */
141    public StandardLevel getStandardLevel() {
142        return standardLevel;
143    }
144
145    /**
146     * Compares this level against the levels passed as arguments and returns true if this level is in between the given
147     * levels.
148     *
149     * @param minLevel The minimum level to test.
150     * @param maxLevel The maximum level to test.
151     * @return True true if this level is in between the given levels
152     * @since 2.4
153     */
154    public boolean isInRange(final Level minLevel, final Level maxLevel) {
155        return this.intLevel >= minLevel.intLevel && this.intLevel <= maxLevel.intLevel;
156    }
157
158    /**
159     * Compares this level against the level passed as an argument and returns true if this level is the same or is less
160     * specific.
161     *
162     * @param level The level to test.
163     * @return True if this level Level is less specific or the same as the given Level.
164     */
165    public boolean isLessSpecificThan(final Level level) {
166        return this.intLevel >= level.intLevel;
167    }
168
169    /**
170     * Compares this level against the level passed as an argument and returns true if this level is the same or is more
171     * specific.
172     *
173     * @param level The level to test.
174     * @return True if this level Level is more specific or the same as the given Level.
175     */
176    public boolean isMoreSpecificThan(final Level level) {
177        return this.intLevel <= level.intLevel;
178    }
179
180    @Override
181    @SuppressWarnings("CloneDoesntCallSuperClone")
182    // CHECKSTYLE:OFF
183    public Level clone() throws CloneNotSupportedException {
184        throw new CloneNotSupportedException();
185    }
186    // CHECKSTYLE:ON
187
188    @Override
189    public int compareTo(final Level other) {
190        return intLevel < other.intLevel ? -1 : (intLevel > other.intLevel ? 1 : 0);
191    }
192
193    @Override
194    public boolean equals(final Object other) {
195        return other instanceof Level && other == this;
196    }
197
198    public Class<Level> getDeclaringClass() {
199        return Level.class;
200    }
201
202    @Override
203    public int hashCode() {
204        return this.name.hashCode();
205    }
206
207    /**
208     * Gets the symbolic name of this Level. Equivalent to calling {@link #toString()}.
209     *
210     * @return the name of this Level.
211     */
212    public String name() {
213        return this.name;
214    }
215
216    @Override
217    public String toString() {
218        return this.name;
219    }
220
221    /**
222     * Retrieves an existing Level or creates on if it didn't previously exist.
223     * 
224     * @param name The name of the level.
225     * @param intValue The integer value for the Level. If the level was previously created this value is ignored.
226     * @return The Level.
227     * @throws java.lang.IllegalArgumentException if the name is null or intValue is less than zero.
228     */
229    public static Level forName(final String name, final int intValue) {
230        final Level level = LEVELS.get(name);
231        if (level != null) {
232            return level;
233        }
234        try {
235            return new Level(name, intValue);
236        } catch (final IllegalStateException ex) {
237            // The level was added by something else so just return that one.
238            return LEVELS.get(name);
239        }
240    }
241
242    /**
243     * Return the Level associated with the name or null if the Level cannot be found.
244     * 
245     * @param name The name of the Level.
246     * @return The Level or null.
247     */
248    public static Level getLevel(final String name) {
249        return LEVELS.get(name);
250    }
251
252    /**
253     * Converts the string passed as argument to a level. If the conversion fails, then this method returns
254     * {@link #DEBUG}.
255     *
256     * @param sArg The name of the desired Level.
257     * @return The Level associated with the String.
258     */
259    public static Level toLevel(final String sArg) {
260        return toLevel(sArg, Level.DEBUG);
261    }
262
263    /**
264     * Converts the string passed as argument to a level. If the conversion fails, then this method returns the value of
265     * <code>defaultLevel</code>.
266     *
267     * @param name The name of the desired Level.
268     * @param defaultLevel The Level to use if the String is invalid.
269     * @return The Level associated with the String.
270     */
271    public static Level toLevel(final String name, final Level defaultLevel) {
272        if (name == null) {
273            return defaultLevel;
274        }
275        final Level level = LEVELS.get(name.toUpperCase(Locale.ENGLISH));
276        return level == null ? defaultLevel : level;
277    }
278
279    /**
280     * Return an array of all the Levels that have been registered.
281     * 
282     * @return An array of Levels.
283     */
284    public static Level[] values() {
285        final Collection<Level> values = Level.LEVELS.values();
286        return values.toArray(new Level[values.size()]);
287    }
288
289    /**
290     * Return the Level associated with the name.
291     * 
292     * @param name The name of the Level to return.
293     * @return The Level.
294     * @throws java.lang.NullPointerException if the Level name is {@code null}.
295     * @throws java.lang.IllegalArgumentException if the Level name is not registered.
296     */
297    public static Level valueOf(final String name) {
298        Objects.requireNonNull(name, "No level name given.");
299        final String levelName = name.toUpperCase(Locale.ENGLISH);
300        final Level level = LEVELS.get(levelName);
301        if (level != null) {
302            return level;
303        }
304        throw new IllegalArgumentException("Unknown level constant [" + levelName + "].");
305    }
306
307    /**
308     * Returns the enum constant of the specified enum type with the specified name. The name must match exactly an
309     * identifier used to declare an enum constant in this type. (Extraneous whitespace characters are not permitted.)
310     *
311     * @param enumType the {@code Class} object of the enum type from which to return a constant
312     * @param name the name of the constant to return
313     * @param <T> The enum type whose constant is to be returned
314     * @return the enum constant of the specified enum type with the specified name
315     * @throws java.lang.IllegalArgumentException if the specified enum type has no constant with the specified name, or
316     *             the specified class object does not represent an enum type
317     * @throws java.lang.NullPointerException if {@code enumType} or {@code name} are {@code null}
318     * @see java.lang.Enum#valueOf(Class, String)
319     */
320    public static <T extends Enum<T>> T valueOf(final Class<T> enumType, final String name) {
321        return Enum.valueOf(enumType, name);
322    }
323
324    // for deserialization
325    protected Object readResolve() {
326        return Level.valueOf(this.name);
327    }
328}