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