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