001/*
002 * Copyright 2015 Apache Software Foundation.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *      http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package org.apache.logging.log4j.core.lookup;
017
018import java.net.URI;
019import java.net.URISyntaxException;
020
021import org.apache.logging.log4j.core.LogEvent;
022import org.apache.logging.log4j.core.LoggerContext;
023import org.apache.logging.log4j.core.config.plugins.Plugin;
024import org.apache.logging.log4j.core.impl.ContextAnchor;
025import org.apache.logging.log4j.status.StatusLogger;
026
027/**
028 * Lookup properties of Log4j
029 */
030@Plugin(name = "log4j", category = StrLookup.CATEGORY)
031public class Log4jLookup extends AbstractLookup {
032
033    public final static String KEY_CONFIG_LOCATION = "configLocation";
034    public final static String KEY_CONFIG_PARENT_LOCATION = "configParentLocation";
035
036    private static final org.apache.logging.log4j.Logger LOGGER = StatusLogger.getLogger();
037
038    private static String asPath(final URI uri) {
039        if (uri.getScheme() == null || uri.getScheme().equals("file")) {
040            return uri.getPath();
041        }
042        return uri.toString();
043    }
044
045    private static URI getParent(final URI uri) throws URISyntaxException {
046        final String s = uri.toString();
047        final int offset = s.lastIndexOf('/');
048        if (offset > -1) {
049            return new URI(s.substring(0, offset));
050        }
051        return new URI("../");
052    }
053
054    @Override
055    public String lookup(final LogEvent event, final String key) {
056        final LoggerContext ctx = ContextAnchor.THREAD_CONTEXT.get();
057        if (ctx == null) {
058            return null;
059        }
060
061        switch (key) {
062        case KEY_CONFIG_LOCATION:
063            return asPath(ctx.getConfigLocation());
064
065        case KEY_CONFIG_PARENT_LOCATION:
066            try {
067                return asPath(getParent(ctx.getConfigLocation()));
068            } catch (final URISyntaxException use) {
069                LOGGER.error(use);
070                return null;
071            }
072
073        default:
074            return null;
075        }
076    }
077}