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.core.lookup;
18
19 import org.apache.logging.log4j.ThreadContext;
20 import org.apache.logging.log4j.core.LogEvent;
21 import org.apache.logging.log4j.core.config.plugins.Plugin;
22 import org.apache.logging.log4j.core.ContextDataInjector;
23 import org.apache.logging.log4j.core.impl.ContextDataInjectorFactory;
24 import org.apache.logging.log4j.util.ReadOnlyStringMap;
25
26 /**
27 * Looks up keys from the context. By default this is the {@link ThreadContext}, but users may
28 * {@linkplain ContextDataInjectorFactory configure} a custom {@link ContextDataInjector} which obtains context data
29 * from some other source.
30 */
31 @Plugin(name = "ctx", category = StrLookup.CATEGORY)
32 public class ContextMapLookup implements StrLookup {
33
34 private final ContextDataInjector injector = ContextDataInjectorFactory.createInjector();
35
36 /**
37 * Looks up the value from the ThreadContext Map.
38 * @param key the key to be looked up, may be null
39 * @return The value associated with the key.
40 */
41 @Override
42 public String lookup(final String key) {
43 return currentContextData().getValue(key);
44 }
45
46 private ReadOnlyStringMap currentContextData() {
47 return injector.rawContextData();
48 }
49
50 /**
51 * Looks up the value from the ThreadContext Map.
52 * @param event The current LogEvent.
53 * @param key the key to be looked up, may be null
54 * @return The value associated with the key.
55 */
56 @Override
57 public String lookup(final LogEvent event, final String key) {
58 return event == null ? null : event.getContextData().<String>getValue(key);
59 }
60 }