1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.logging.log4j.spring.boot;
18
19 import org.apache.logging.log4j.Logger;
20 import org.apache.logging.log4j.core.LogEvent;
21 import org.apache.logging.log4j.core.config.plugins.Plugin;
22 import org.apache.logging.log4j.core.lookup.StrLookup;
23 import org.apache.logging.log4j.status.StatusLogger;
24 import org.springframework.core.env.Environment;
25
26 import java.util.regex.Matcher;
27 import java.util.regex.Pattern;
28
29
30
31
32 @Plugin(name = "spring", category = StrLookup.CATEGORY)
33 public class SpringLookup extends SpringEnvironmentHolder implements StrLookup {
34
35 private static final Logger LOGGER = StatusLogger.getLogger();
36 private static final String ACTIVE = "profiles.active";
37 private static final String DEFAULT = "profiles.default";
38 private static final String PATTERN = "\\[(\\d+?)\\]";
39 private static final Pattern ACTIVE_PATTERN = Pattern.compile(ACTIVE + PATTERN);
40 private static final Pattern DEFAULT_PATTERN = Pattern.compile(DEFAULT + PATTERN);
41
42 public SpringLookup() {
43 getEnvironment();
44 }
45
46 @Override
47 public String lookup(String key) {
48 Environment env = getEnvironment();
49 if (env != null) {
50 String lowerKey = key.toLowerCase();
51 if (lowerKey.startsWith(ACTIVE)) {
52 switch (env.getActiveProfiles().length) {
53 case 0: {
54 return null;
55 }
56 case 1: {
57 return env.getActiveProfiles()[0];
58 }
59 default: {
60 Matcher matcher = ACTIVE_PATTERN.matcher(key);
61 if (matcher.matches()) {
62 try {
63 int index = Integer.parseInt(matcher.group(1));
64 if (index < env.getActiveProfiles().length) {
65 return env.getActiveProfiles()[index];
66 }
67 LOGGER.warn("Index out of bounds for Spring active profiles: {}", index);
68 return null;
69 } catch (Exception ex) {
70 LOGGER.warn("Unable to parse {} as integer value", matcher.group(1));
71 return null;
72 }
73
74 }
75 return String.join(",", env.getActiveProfiles());
76 }
77 }
78 } else if (lowerKey.startsWith(DEFAULT)) {
79 switch (env.getDefaultProfiles().length) {
80 case 0: {
81 return null;
82 }
83 case 1: {
84 return env.getDefaultProfiles()[0];
85 }
86 default: {
87 Matcher matcher = DEFAULT_PATTERN.matcher(key);
88 if (matcher.matches()) {
89 try {
90 int index = Integer.parseInt(matcher.group(1));
91 if (index < env.getDefaultProfiles().length) {
92 return env.getDefaultProfiles()[index];
93 }
94 LOGGER.warn("Index out of bounds for Spring default profiles: {}", index);
95 return null;
96 } catch (Exception ex) {
97 LOGGER.warn("Unable to parse {} as integer value", matcher.group(1));
98 return null;
99 }
100
101 }
102 return String.join(",", env.getDefaultProfiles());
103 }
104 }
105 }
106
107 return env.getProperty(key);
108
109 }
110 return null;
111 }
112
113 @Override
114 public String lookup(LogEvent event, String key) {
115 return lookup((key));
116 }
117 }