0
# Lookups
1
2
Lookups provide variable substitution capabilities in Log4j configurations, allowing dynamic values to be inserted into configuration elements at runtime. The lookup system supports environment variables, system properties, context data, and custom lookup implementations.
3
4
## Capabilities
5
6
### Core Lookup Interface
7
8
Base interface for implementing custom lookup providers.
9
10
```java { .api }
11
/**
12
* Core lookup interface for variable substitution
13
*/
14
public interface StrLookup {
15
/**
16
* Look up a variable by key
17
* @param key Variable key to look up
18
* @return Variable value or null if not found
19
*/
20
String lookup(String key);
21
22
/**
23
* Look up a variable with LogEvent context
24
* @param event LogEvent providing context for lookup
25
* @param key Variable key to look up
26
* @return Variable value or null if not found
27
*/
28
String lookup(LogEvent event, String key);
29
}
30
```
31
32
### System Properties Lookup
33
34
Looks up Java system properties using `System.getProperty()`.
35
36
```java { .api }
37
/**
38
* SystemPropertiesLookup for accessing Java system properties
39
*/
40
public class SystemPropertiesLookup implements StrLookup {
41
/**
42
* Look up system property by key
43
* @param key System property name
44
* @return System property value or null
45
*/
46
public String lookup(String key);
47
48
/**
49
* Look up system property with LogEvent context
50
* @param event LogEvent for context
51
* @param key System property name
52
* @return System property value or null
53
*/
54
public String lookup(LogEvent event, String key);
55
}
56
```
57
58
**Usage Examples:**
59
60
Configuration usage:
61
```xml
62
<Configuration>
63
<Properties>
64
<Property name="logPath">${sys:user.home}/logs</Property>
65
<Property name="javaVersion">${sys:java.version}</Property>
66
</Properties>
67
<Appenders>
68
<File name="File" fileName="${logPath}/application.log">
69
<PatternLayout pattern="Java ${javaVersion} - %d %level %logger - %msg%n"/>
70
</File>
71
</Appenders>
72
</Configuration>
73
```
74
75
### Environment Variables Lookup
76
77
Looks up operating system environment variables.
78
79
```java { .api }
80
/**
81
* EnvironmentLookup for accessing OS environment variables
82
*/
83
public class EnvironmentLookup implements StrLookup {
84
/**
85
* Look up environment variable by key
86
* @param key Environment variable name
87
* @return Environment variable value or null
88
*/
89
public String lookup(String key);
90
91
/**
92
* Look up environment variable with LogEvent context
93
* @param event LogEvent for context
94
* @param key Environment variable name
95
* @return Environment variable value or null
96
*/
97
public String lookup(LogEvent event, String key);
98
}
99
```
100
101
**Usage Examples:**
102
103
Configuration usage:
104
```xml
105
<Configuration>
106
<Properties>
107
<Property name="appName">${env:APP_NAME}</Property>
108
<Property name="environment">${env:ENVIRONMENT}</Property>
109
<Property name="logLevel">${env:LOG_LEVEL:-INFO}</Property>
110
</Properties>
111
<Appenders>
112
<File name="File" fileName="logs/${appName}-${environment}.log"/>
113
</Appenders>
114
</Configuration>
115
```
116
117
### Context Map Lookup
118
119
Looks up values from the thread context map (MDC).
120
121
```java { .api }
122
/**
123
* ContextMapLookup for accessing ThreadContext data
124
*/
125
public class ContextMapLookup implements StrLookup {
126
/**
127
* Look up context value by key
128
* @param key Context key
129
* @return Context value or null
130
*/
131
public String lookup(String key);
132
133
/**
134
* Look up context value with LogEvent context
135
* @param event LogEvent containing context data
136
* @param key Context key
137
* @return Context value or null
138
*/
139
public String lookup(LogEvent event, String key);
140
}
141
```
142
143
**Usage Examples:**
144
145
```java
146
// Set context data
147
ThreadContext.put("userId", "12345");
148
ThreadContext.put("requestId", "req-abc-123");
149
150
// Configuration can reference context values
151
```
152
153
Configuration usage:
154
```xml
155
<Configuration>
156
<Appenders>
157
<File name="UserFile" fileName="logs/user-${ctx:userId}.log">
158
<PatternLayout pattern="Request ${ctx:requestId} - %d %level %logger - %msg%n"/>
159
</File>
160
</Appenders>
161
</Configuration>
162
```
163
164
### Date Lookup
165
166
Provides current date and time formatting capabilities.
167
168
```java { .api }
169
/**
170
* DateLookup for formatting current date/time
171
*/
172
public class DateLookup implements StrLookup {
173
/**
174
* Format current date/time using specified pattern
175
* @param key Date format pattern (SimpleDateFormat)
176
* @return Formatted date string
177
*/
178
public String lookup(String key);
179
180
/**
181
* Format current date/time with LogEvent timestamp
182
* @param event LogEvent for timestamp context
183
* @param key Date format pattern
184
* @return Formatted date string
185
*/
186
public String lookup(LogEvent event, String key);
187
}
188
```
189
190
**Usage Examples:**
191
192
Configuration usage:
193
```xml
194
<Configuration>
195
<Properties>
196
<Property name="currentDate">${date:yyyy-MM-dd}</Property>
197
<Property name="timestamp">${date:yyyy-MM-dd_HH-mm-ss}</Property>
198
</Properties>
199
<Appenders>
200
<File name="DailyFile" fileName="logs/app-${currentDate}.log"/>
201
<File name="StartupFile" fileName="logs/startup-${timestamp}.log"/>
202
</Appenders>
203
</Configuration>
204
```
205
206
### Java Lookup
207
208
Provides access to Java runtime information.
209
210
```java { .api }
211
/**
212
* JavaLookup for accessing Java runtime information
213
*/
214
public class JavaLookup implements StrLookup {
215
/**
216
* Look up Java runtime information
217
* @param key Information key (version, runtime, vm, os, locale, hw)
218
* @return Java runtime information
219
*/
220
public String lookup(String key);
221
}
222
```
223
224
**Usage Examples:**
225
226
Configuration usage:
227
```xml
228
<Configuration>
229
<Properties>
230
<Property name="javaVersion">${java:version}</Property>
231
<Property name="javaRuntime">${java:runtime}</Property>
232
<Property name="javaVm">${java:vm}</Property>
233
<Property name="osInfo">${java:os}</Property>
234
<Property name="hwInfo">${java:hw}</Property>
235
</Properties>
236
</Configuration>
237
```
238
239
### Main Arguments Lookup
240
241
Provides access to main method arguments.
242
243
```java { .api }
244
/**
245
* MainMapLookup for accessing main method arguments
246
*/
247
public class MainMapLookup implements StrLookup {
248
/**
249
* Look up main argument by index
250
* @param key Argument index as string
251
* @return Argument value or null
252
*/
253
public String lookup(String key);
254
}
255
```
256
257
### JNDI Lookup
258
259
Provides JNDI (Java Naming and Directory Interface) lookups.
260
261
```java { .api }
262
/**
263
* JndiLookup for JNDI resource access
264
* NOTE: Disabled by default for security reasons in Log4j 2.17.0+
265
*/
266
public class JndiLookup implements StrLookup {
267
/**
268
* Look up JNDI resource
269
* @param key JNDI name
270
* @return JNDI resource or null
271
*/
272
public String lookup(String key);
273
}
274
```
275
276
**Security Note:** JNDI lookup is disabled by default in Log4j 2.17.0+ due to security concerns. Enable only if absolutely necessary and in trusted environments.
277
278
### Upper/Lower Case Lookups
279
280
Transforms lookup values to upper or lower case.
281
282
```java { .api }
283
/**
284
* UpperLookup - converts nested lookup results to uppercase
285
*/
286
public class UpperLookup implements StrLookup {
287
public String lookup(String key);
288
}
289
290
/**
291
* LowerLookup - converts nested lookup results to lowercase
292
*/
293
public class LowerLookup implements StrLookup {
294
public String lookup(String key);
295
}
296
```
297
298
**Usage Examples:**
299
300
Configuration usage:
301
```xml
302
<Configuration>
303
<Properties>
304
<Property name="upperEnv">${upper:${env:ENVIRONMENT}}</Property>
305
<Property name="lowerUser">${lower:${sys:user.name}}</Property>
306
</Properties>
307
</Configuration>
308
```
309
310
## Custom Lookup Implementation
311
312
### Creating Custom Lookups
313
314
```java { .api }
315
/**
316
* Example custom lookup plugin
317
*/
318
@Plugin(name = "database", category = StrLookup.CATEGORY)
319
public class DatabaseLookup implements StrLookup {
320
321
private final DataSource dataSource;
322
323
public DatabaseLookup(DataSource dataSource) {
324
this.dataSource = dataSource;
325
}
326
327
/**
328
* Look up value from database
329
* @param key Database key to query
330
* @return Database value or null
331
*/
332
@Override
333
public String lookup(String key) {
334
try (Connection conn = dataSource.getConnection();
335
PreparedStatement stmt = conn.prepareStatement("SELECT value FROM config WHERE key = ?")) {
336
stmt.setString(1, key);
337
try (ResultSet rs = stmt.executeQuery()) {
338
return rs.next() ? rs.getString("value") : null;
339
}
340
} catch (SQLException e) {
341
LOGGER.error("Database lookup failed for key: {}", key, e);
342
return null;
343
}
344
}
345
346
/**
347
* Factory method for creating lookup instances
348
* @return DatabaseLookup instance
349
*/
350
@PluginFactory
351
public static DatabaseLookup createLookup() {
352
// Initialize DataSource
353
return new DatabaseLookup(createDataSource());
354
}
355
}
356
```
357
358
## Lookup Syntax and Nesting
359
360
### Basic Syntax
361
- `${lookup:key}` - Simple lookup
362
- `${lookup:key:-default}` - Lookup with default value
363
364
### Nested Lookups
365
```xml
366
<!-- Nested environment and system property lookups -->
367
<Property name="logFile">${env:${sys:app.name.property}}.log</Property>
368
369
<!-- Complex nesting with defaults -->
370
<Property name="dbUrl">${env:DATABASE_URL:-${sys:default.db.url:-jdbc:h2:mem:test}}</Property>
371
```
372
373
### Conditional Lookups
374
```xml
375
<!-- Use environment-specific configuration -->
376
<Property name="configFile">config-${env:ENVIRONMENT:-development}.xml</Property>
377
```
378
379
## Built-in Lookup Prefixes
380
381
Standard lookup prefixes available in Log4j Core:
382
383
- `${ctx:key}` - Thread context map lookup
384
- `${date:pattern}` - Date formatting lookup
385
- `${env:key}` - Environment variables lookup
386
- `${sys:key}` - System properties lookup
387
- `${java:key}` - Java runtime information lookup
388
- `${main:index}` - Main method arguments lookup
389
- `${upper:nested}` - Uppercase transformation lookup
390
- `${lower:nested}` - Lowercase transformation lookup
391
- `${jndi:name}` - JNDI lookup (security restricted)