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.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
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 }