1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.apache.logging.log4j.core.lookup;
17
18 import java.io.File;
19 import java.net.URI;
20 import java.net.URISyntaxException;
21 import java.net.URL;
22
23 import org.apache.logging.log4j.core.LogEvent;
24 import org.apache.logging.log4j.core.LoggerContext;
25 import org.apache.logging.log4j.core.config.ConfigurationSource;
26 import org.apache.logging.log4j.core.config.plugins.Plugin;
27 import org.apache.logging.log4j.core.impl.ContextAnchor;
28 import org.apache.logging.log4j.status.StatusLogger;
29
30
31
32
33 @Plugin(name = "log4j", category = StrLookup.CATEGORY)
34 public class Log4jLookup extends AbstractLookup {
35
36 public final static String KEY_CONFIG_LOCATION = "configLocation";
37 public final static String KEY_CONFIG_PARENT_LOCATION = "configParentLocation";
38
39 private static final org.apache.logging.log4j.Logger LOGGER = StatusLogger.getLogger();
40
41 private static String asPath(final URI uri) {
42 if (uri.getScheme() == null || uri.getScheme().equals("file")) {
43 return uri.getPath();
44 }
45 return uri.toString();
46 }
47
48 private static URI getParent(final URI uri) throws URISyntaxException {
49 final String s = uri.toString();
50 final int offset = s.lastIndexOf('/');
51 if (offset > -1) {
52 return new URI(s.substring(0, offset));
53 }
54 return new URI("../");
55 }
56
57 @Override
58 public String lookup(final LogEvent event, final String key) {
59 final LoggerContext ctx = ContextAnchor.THREAD_CONTEXT.get();
60 if (ctx == null) {
61 return null;
62 }
63 final ConfigurationSource configSrc = ctx.getConfiguration().getConfigurationSource();
64 final File file = configSrc.getFile();
65 if (file != null) {
66 switch (key) {
67 case KEY_CONFIG_LOCATION:
68 return file.getAbsolutePath();
69
70 case KEY_CONFIG_PARENT_LOCATION:
71 return file.getParentFile().getAbsolutePath();
72
73 default:
74 return null;
75 }
76 }
77
78 final URL url = configSrc.getURL();
79 try {
80 switch (key) {
81 case KEY_CONFIG_LOCATION:
82 return asPath(url.toURI());
83
84 case KEY_CONFIG_PARENT_LOCATION:
85 return asPath(getParent(url.toURI()));
86
87 default:
88 return null;
89 }
90 } catch (final URISyntaxException use) {
91 LOGGER.error(use);
92 return null;
93 }
94 }
95 }