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