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 package org.apache.logging.log4j.core.lookup; 018 019 import org.apache.logging.log4j.core.LogEvent; 020 import org.apache.logging.log4j.core.config.plugins.Plugin; 021 import org.apache.logging.log4j.message.MapMessage; 022 023 import java.util.Map; 024 025 /** 026 * The basis for a lookup based on a Map. 027 * @param <V> The type of object contained in the Map. 028 */ 029 @Plugin(name = "map", type = "Lookup") 030 public class MapLookup<V> implements StrLookup<V> { 031 /** 032 * Map keys are variable names and value. 033 */ 034 private final Map<String, V> map; 035 036 /** 037 * Creates a new instance backed by a Map. Used by the default lookup. 038 * 039 * @param map the map of keys to values, may be null 040 */ 041 public MapLookup(Map<String, V> map) { 042 this.map = map; 043 } 044 045 /** 046 * Constructor when used directly as a plugin. 047 */ 048 public MapLookup() { 049 this.map = null; 050 } 051 052 /** 053 * Looks up a String key to a String value using the map. 054 * <p/> 055 * If the map is null, then null is returned. 056 * The map result object is converted to a string using toString(). 057 * 058 * @param key the key to be looked up, may be null 059 * @return the matching value, null if no match 060 */ 061 public String lookup(String key) { 062 if (map == null) { 063 return null; 064 } 065 Object obj = map.get(key); 066 if (obj == null) { 067 return null; 068 } 069 return obj.toString(); 070 } 071 072 public String lookup(LogEvent event, String key) { 073 if (map == null && !(event.getMessage() instanceof MapMessage)) { 074 return null; 075 } 076 if (map != null && map.containsKey(key)) { 077 Object obj = map.get(key); 078 if (obj != null) { 079 return obj.toString(); 080 } 081 } 082 if (event.getMessage() instanceof MapMessage) { 083 return ((MapMessage) event.getMessage()).get(key); 084 } 085 return null; 086 } 087 }