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  
18  package org.apache.logging.log4j.core.async;
19  
20  import org.apache.logging.log4j.status.StatusLogger;
21  import org.apache.logging.log4j.util.PropertiesUtil;
22  
23  /**
24   * Strategy for deciding whether thread name should be cached or not.
25   */
26  public enum ThreadNameCachingStrategy { // LOG4J2-467
27      CACHED {
28          @Override
29          public String getThreadName() {
30              String result = THREADLOCAL_NAME.get();
31              if (result == null) {
32                  result = Thread.currentThread().getName();
33                  THREADLOCAL_NAME.set(result);
34              }
35              return result;
36          }
37      },
38      UNCACHED {
39          @Override
40          public String getThreadName() {
41              return Thread.currentThread().getName();
42          }
43      };
44  
45      private static final StatusLogger LOGGER = StatusLogger.getLogger();
46      private static final ThreadLocal<String> THREADLOCAL_NAME = new ThreadLocal<>();
47  
48      abstract String getThreadName();
49  
50      public static ThreadNameCachingStrategy create() {
51          final String name = PropertiesUtil.getProperties().getStringProperty("AsyncLogger.ThreadNameStrategy",
52                  CACHED.name());
53          try {
54              final ThreadNameCachingStrategy result = ThreadNameCachingStrategy.valueOf(name);
55              LOGGER.debug("AsyncLogger.ThreadNameStrategy={}", result);
56              return result;
57          } catch (final Exception ex) {
58              LOGGER.debug("Using AsyncLogger.ThreadNameStrategy.CACHED: '{}' not valid: {}", name, ex.toString());
59              return CACHED;
60          }
61      }
62  }