View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements. See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache license, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License. You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the license for the specific language governing permissions and
15   * limitations under the license.
16   */
17  package org.apache.logging.log4j;
18  
19  import java.io.Serializable;
20  import java.util.Collection;
21  import java.util.Locale;
22  import java.util.Objects;
23  import java.util.concurrent.ConcurrentHashMap;
24  import java.util.concurrent.ConcurrentMap;
25  
26  import org.apache.logging.log4j.spi.StandardLevel;
27  import org.apache.logging.log4j.util.Strings;
28  
29  /**
30   * Levels used for identifying the severity of an event. Levels are organized from most specific to least:
31   * <ul>
32   * <li>{@link #OFF} (most specific, no logging)</li>
33   * <li>{@link #FATAL} (most specific, little data)</li>
34   * <li>{@link #ERROR}</li>
35   * <li>{@link #WARN}</li>
36   * <li>{@link #INFO}</li>
37   * <li>{@link #DEBUG}</li>
38   * <li>{@link #TRACE} (least specific, a lot of data)</li>
39   * <li>{@link #ALL} (least specific, all data)</li>
40   * </ul>
41   *
42   * Typically, configuring a level in a filter or on a logger will cause logging events of that level and those that are
43   * more specific to pass through the filter. A special level, {@link #ALL}, is guaranteed to capture all levels when
44   * used in logging configurations.
45   */
46  public final class Level implements Comparable<Level>, Serializable {
47  
48      /**
49       * No events will be logged.
50       */
51      public static final Level OFF;
52  
53      /**
54       * A severe error that will prevent the application from continuing.
55       */
56      public static final Level FATAL;
57  
58      /**
59       * An error in the application, possibly recoverable.
60       */
61      public static final Level ERROR;
62  
63      /**
64       * An event that might possible lead to an error.
65       */
66      public static final Level WARN;
67  
68      /**
69       * An event for informational purposes.
70       */
71      public static final Level INFO;
72  
73      /**
74       * A general debugging event.
75       */
76      public static final Level DEBUG;
77  
78      /**
79       * A fine-grained debug message, typically capturing the flow through the application.
80       */
81      public static final Level TRACE;
82  
83      /**
84       * All events should be logged.
85       */
86      public static final Level ALL;
87  
88      /**
89       * @since 2.1
90       */
91      public static final String CATEGORY = "Level";
92  
93      private static final ConcurrentMap<String, Level> LEVELS = new ConcurrentHashMap<>(); // SUPPRESS CHECKSTYLE
94  
95      private static final long serialVersionUID = 1581082L;
96  
97      static {
98          OFF = new Level("OFF", StandardLevel.OFF.intLevel());
99          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 }