View Javadoc
1   /*
2    * Copyright 2015 Apache Software Foundation.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package org.apache.logging.log4j.core.lookup;
17  
18  import java.net.URI;
19  import java.net.URISyntaxException;
20  
21  import org.apache.logging.log4j.core.LogEvent;
22  import org.apache.logging.log4j.core.LoggerContext;
23  import org.apache.logging.log4j.core.config.plugins.Plugin;
24  import org.apache.logging.log4j.core.impl.ContextAnchor;
25  import org.apache.logging.log4j.status.StatusLogger;
26  
27  /**
28   * Lookup properties of Log4j
29   */
30  @Plugin(name = "log4j", category = StrLookup.CATEGORY)
31  public class Log4jLookup extends AbstractLookup {
32  
33      public final static String KEY_CONFIG_LOCATION = "configLocation";
34      public final static String KEY_CONFIG_PARENT_LOCATION = "configParentLocation";
35  
36      private static final org.apache.logging.log4j.Logger LOGGER = StatusLogger.getLogger();
37  
38      private static String asPath(final URI uri) {
39          if (uri.getScheme() == null || uri.getScheme().equals("file")) {
40              return uri.getPath();
41          }
42          return uri.toString();
43      }
44  
45      private static URI getParent(final URI uri) throws URISyntaxException {
46          final String s = uri.toString();
47          final int offset = s.lastIndexOf('/');
48          if (offset > -1) {
49              return new URI(s.substring(0, offset));
50          }
51          return new URI("../");
52      }
53  
54      @Override
55      public String lookup(final LogEvent event, final String key) {
56          final LoggerContext ctx = ContextAnchor.THREAD_CONTEXT.get();
57          if (ctx == null) {
58              return null;
59          }
60  
61          switch (key) {
62          case KEY_CONFIG_LOCATION:
63              return asPath(ctx.getConfigLocation());
64  
65          case KEY_CONFIG_PARENT_LOCATION:
66              try {
67                  return asPath(getParent(ctx.getConfigLocation()));
68              } catch (final URISyntaxException use) {
69                  LOGGER.error(use);
70                  return null;
71              }
72  
73          default:
74              return null;
75          }
76      }
77  }