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 */ 017 018package org.apache.logging.log4j.core.async; 019 020import org.apache.logging.log4j.status.StatusLogger; 021import org.apache.logging.log4j.util.PropertiesUtil; 022 023/** 024 * Strategy for deciding whether thread name should be cached or not. 025 */ 026public enum ThreadNameCachingStrategy { // LOG4J2-467 027 CACHED { 028 @Override 029 public String getThreadName() { 030 String result = THREADLOCAL_NAME.get(); 031 if (result == null) { 032 result = Thread.currentThread().getName(); 033 THREADLOCAL_NAME.set(result); 034 } 035 return result; 036 } 037 }, 038 UNCACHED { 039 @Override 040 public String getThreadName() { 041 return Thread.currentThread().getName(); 042 } 043 }; 044 045 private static final StatusLogger LOGGER = StatusLogger.getLogger(); 046 private static final ThreadLocal<String> THREADLOCAL_NAME = new ThreadLocal<>(); 047 048 abstract String getThreadName(); 049 050 public static ThreadNameCachingStrategy create() { 051 final String name = PropertiesUtil.getProperties().getStringProperty("AsyncLogger.ThreadNameStrategy", 052 CACHED.name()); 053 try { 054 final ThreadNameCachingStrategy result = ThreadNameCachingStrategy.valueOf(name); 055 LOGGER.debug("AsyncLogger.ThreadNameStrategy={}", result); 056 return result; 057 } catch (final Exception ex) { 058 LOGGER.debug("Using AsyncLogger.ThreadNameStrategy.CACHED: '{}' not valid: {}", name, ex.toString()); 059 return CACHED; 060 } 061 } 062}