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.lookup;
018
019import org.apache.logging.log4j.ThreadContext;
020import org.apache.logging.log4j.core.LogEvent;
021import org.apache.logging.log4j.core.config.plugins.Plugin;
022import org.apache.logging.log4j.core.ContextDataInjector;
023import org.apache.logging.log4j.core.impl.ContextDataInjectorFactory;
024import org.apache.logging.log4j.util.ReadOnlyStringMap;
025
026/**
027 * Looks up keys from the context. By default this is the {@link ThreadContext}, but users may
028 * {@linkplain ContextDataInjectorFactory configure} a custom {@link ContextDataInjector} which obtains context data
029 * from some other source.
030 */
031@Plugin(name = "ctx", category = StrLookup.CATEGORY)
032public class ContextMapLookup implements StrLookup {
033
034    private final ContextDataInjector injector = ContextDataInjectorFactory.createInjector();
035
036    /**
037     * Looks up the value from the ThreadContext Map.
038     * @param key  the key to be looked up, may be null
039     * @return The value associated with the key.
040     */
041    @Override
042    public String lookup(final String key) {
043        return currentContextData().getValue(key);
044    }
045
046    private ReadOnlyStringMap currentContextData() {
047        return injector.rawContextData();
048    }
049
050    /**
051     * Looks up the value from the ThreadContext Map.
052     * @param event The current LogEvent.
053     * @param key  the key to be looked up, may be null
054     * @return The value associated with the key.
055     */
056    @Override
057    public String lookup(final LogEvent event, final String key) {
058        return event == null ? null : event.getContextData().<String>getValue(key);
059    }
060}