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.core.LogEvent; 20 import org.apache.logging.log4j.core.config.plugins.Plugin; 21 import org.apache.logging.log4j.message.MapMessage; 22 23 import java.util.Map; 24 25 /** 26 * The basis for a lookup based on a Map. 27 */ 28 @Plugin(name = "map", category = "Lookup") 29 public class MapLookup implements StrLookup { 30 /** 31 * Map keys are variable names and value. 32 */ 33 private final Map<String, String> map; 34 35 /** 36 * Creates a new instance backed by a Map. Used by the default lookup. 37 * 38 * @param map the map of keys to values, may be null 39 */ 40 public MapLookup(final Map<String, String> map) { 41 this.map = map; 42 } 43 44 /** 45 * Constructor when used directly as a plugin. 46 */ 47 public MapLookup() { 48 this.map = null; 49 } 50 51 /** 52 * Looks up a String key to a String value using the map. 53 * <p/> 54 * If the map is null, then null is returned. 55 * The map result object is converted to a string using toString(). 56 * 57 * @param key the key to be looked up, may be null 58 * @return the matching value, null if no match 59 */ 60 @Override 61 public String lookup(final String key) { 62 if (map == null) { 63 return null; 64 } 65 final String obj = map.get(key); 66 if (obj == null) { 67 return null; 68 } 69 return obj; 70 } 71 72 @Override 73 public String lookup(final LogEvent event, final String key) { 74 if (map == null && !(event.getMessage() instanceof MapMessage)) { 75 return null; 76 } 77 if (map != null && map.containsKey(key)) { 78 final String obj = map.get(key); 79 if (obj != null) { 80 return obj; 81 } 82 } 83 if (event.getMessage() instanceof MapMessage) { 84 return ((MapMessage) event.getMessage()).get(key); 85 } 86 return null; 87 } 88 }