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.selector; 018 019import java.net.URI; 020import java.util.ArrayList; 021import java.util.Collections; 022import java.util.List; 023import java.util.concurrent.TimeUnit; 024 025import org.apache.logging.log4j.core.LoggerContext; 026import org.apache.logging.log4j.core.impl.ContextAnchor; 027 028/** 029 * Returns either this Thread's context or the default LoggerContext. 030 */ 031public class BasicContextSelector implements ContextSelector { 032 033 private static final LoggerContext CONTEXT = new LoggerContext("Default"); 034 035 @Override 036 public void shutdown(String fqcn, ClassLoader loader, boolean currentContext, boolean allContexts) { 037 LoggerContext ctx = getContext(fqcn, loader, currentContext); 038 if (ctx != null && ctx.isStarted()) { 039 ctx.stop(DEFAULT_STOP_TIMEOUT, TimeUnit.MILLISECONDS); 040 } 041 } 042 043 @Override 044 public boolean hasContext(String fqcn, ClassLoader loader, boolean currentContext) { 045 LoggerContext ctx = getContext(fqcn, loader, currentContext); 046 return ctx != null && ctx.isStarted(); 047 } 048 049 @Override 050 public LoggerContext getContext(final String fqcn, final ClassLoader loader, final boolean currentContext) { 051 final LoggerContext ctx = ContextAnchor.THREAD_CONTEXT.get(); 052 return ctx != null ? ctx : CONTEXT; 053 } 054 055 056 @Override 057 public LoggerContext getContext(final String fqcn, final ClassLoader loader, final boolean currentContext, 058 final URI configLocation) { 059 060 final LoggerContext ctx = ContextAnchor.THREAD_CONTEXT.get(); 061 return ctx != null ? ctx : CONTEXT; 062 } 063 064 public LoggerContext locateContext(final String name, final String configLocation) { 065 return CONTEXT; 066 } 067 068 @Override 069 public void removeContext(final LoggerContext context) { 070 // does not remove anything 071 } 072 073 @Override 074 public boolean isClassLoaderDependent() { 075 return false; 076 } 077 078 @Override 079 public List<LoggerContext> getLoggerContexts() { 080 final List<LoggerContext> list = new ArrayList<>(); 081 list.add(CONTEXT); 082 return Collections.unmodifiableList(list); 083 } 084 085}