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 java.util.MissingResourceException; 20 import java.util.ResourceBundle; 21 22 import org.apache.logging.log4j.core.LogEvent; 23 import org.apache.logging.log4j.core.config.plugins.Plugin; 24 25 /** 26 * Looks up keys from resource bundles. 27 */ 28 @Plugin(name = "bundle", category = "Lookup") 29 public class ResourceBundleLookup implements StrLookup { 30 31 /** 32 * Looks up the value for the key in the format "BundleName:BundleKey". 33 * 34 * For example: "com.domain.messages:MyKey". 35 * 36 * @param key 37 * the key to be looked up, may be null 38 * @return The value for the key. 39 */ 40 @Override 41 public String lookup(final String key) { 42 if (key == null) { 43 return null; 44 } 45 final String[] keys = key.split(":"); 46 final int keyLen = keys.length; 47 if (keyLen != 2) { 48 // throw new IllegalArgumentException("Bad key format " + key + ", format is BundleName:Value"); 49 // log? 50 return null; 51 } 52 final String bundleName = keys[0]; 53 final String bundleKey = keys[1]; 54 try { 55 // The ResourceBundle class caches bundles, no need to cache here. 56 return ResourceBundle.getBundle(bundleName).getString(bundleKey); 57 } catch (final MissingResourceException e) { 58 // log? 59 return null; 60 } 61 } 62 63 /** 64 * Looks up the value for the key in the format "BundleName:BundleKey". 65 * 66 * For example: "com.domain.messages:MyKey". 67 * 68 * @param event 69 * The current LogEvent. 70 * @param key 71 * the key to be looked up, may be null 72 * @return The value associated with the key. 73 */ 74 @Override 75 public String lookup(final LogEvent event, final String key) { 76 return lookup(key); 77 } 78 }