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 */
017package org.apache.logging.log4j.core.lookup;
018
019import java.util.MissingResourceException;
020import java.util.ResourceBundle;
021
022import org.apache.logging.log4j.Logger;
023import org.apache.logging.log4j.Marker;
024import org.apache.logging.log4j.MarkerManager;
025import org.apache.logging.log4j.core.LogEvent;
026import org.apache.logging.log4j.core.config.plugins.Plugin;
027import org.apache.logging.log4j.status.StatusLogger;
028
029/**
030 * Looks up keys from resource bundles.
031 */
032@Plugin(name = "bundle", category = StrLookup.CATEGORY)
033public class ResourceBundleLookup extends AbstractLookup {
034
035    private static final Logger LOGGER = StatusLogger.getLogger();
036    private static final Marker LOOKUP = MarkerManager.getMarker("LOOKUP");
037
038    /**
039     * Looks up the value for the key in the format "BundleName:BundleKey".
040     *
041     * For example: "com.domain.messages:MyKey".
042     *
043     * @param event
044     *            The current LogEvent.
045     * @param key
046     *            the key to be looked up, may be null
047     * @return The value associated with the key.
048     */
049    @Override
050    public String lookup(final LogEvent event, final String key) {
051        if (key == null) {
052            return null;
053        }
054        final String[] keys = key.split(":");
055        final int keyLen = keys.length;
056        if (keyLen != 2) {
057            LOGGER.warn(LOOKUP, "Bad ResourceBundle key format [{}]. Expected format is BundleName:KeyName.", key);
058            return null;
059        }
060        final String bundleName = keys[0];
061        final String bundleKey = keys[1];
062        try {
063            // The ResourceBundle class caches bundles, no need to cache here.
064            return ResourceBundle.getBundle(bundleName).getString(bundleKey);
065        } catch (final MissingResourceException e) {
066            LOGGER.warn(LOOKUP, "Error looking up ResourceBundle [{}].", bundleName, e);
067            return null;
068        }
069    }
070}