0
# Configuration
1
2
Log4j Core provides comprehensive configuration management supporting multiple file formats (XML, JSON, YAML, Properties) and programmatic configuration through a fluent builder API. The configuration system manages loggers, appenders, layouts, filters, and global settings.
3
4
## Capabilities
5
6
### Core Configuration Interface
7
8
Base interface that all configuration implementations must implement.
9
10
```java { .api }
11
/**
12
* Core configuration interface managing logging components
13
*/
14
public interface Configuration {
15
/**
16
* Get configuration name
17
* @return Configuration name
18
*/
19
String getName();
20
21
/**
22
* Get logger configuration by name
23
* @param name Logger name
24
* @return LoggerConfig instance
25
*/
26
LoggerConfig getLoggerConfig(String name);
27
28
/**
29
* Get appender by name
30
* @param name Appender name
31
* @return Appender instance with generic type
32
*/
33
<T extends Appender> T getAppender(String name);
34
35
/**
36
* Get all appenders
37
* @return Map of appender names to instances
38
*/
39
Map<String, Appender> getAppenders();
40
41
/**
42
* Get all logger configurations
43
* @return Map of logger names to configurations
44
*/
45
Map<String, LoggerConfig> getLoggers();
46
47
/**
48
* Get root logger configuration
49
* @return Root LoggerConfig instance
50
*/
51
LoggerConfig getRootLogger();
52
53
/**
54
* Get configuration source
55
* @return ConfigurationSource instance
56
*/
57
ConfigurationSource getConfigurationSource();
58
59
/**
60
* Get string substitution handler
61
* @return StrSubstitutor for variable replacement
62
*/
63
StrSubstitutor getStrSubstitutor();
64
65
/**
66
* Get plugin packages list
67
* @return List of plugin package names
68
*/
69
List<String> getPluginPackages();
70
71
/**
72
* Get configuration properties
73
* @return Map of property names to values
74
*/
75
Map<String, String> getProperties();
76
77
/**
78
* Initialize the configuration
79
*/
80
void initialize();
81
82
/**
83
* Start the configuration
84
*/
85
void start();
86
87
/**
88
* Stop the configuration with timeout
89
* @param timeout Maximum wait time
90
* @param timeUnit Time unit for timeout
91
* @return true if stopped within timeout
92
*/
93
boolean stop(long timeout, TimeUnit timeUnit);
94
95
/**
96
* Get configuration state
97
* @return Current lifecycle state
98
*/
99
LifeCycle.State getState();
100
101
/**
102
* Check if configuration is started
103
* @return true if started
104
*/
105
boolean isStarted();
106
107
/**
108
* Check if configuration is stopped
109
* @return true if stopped
110
*/
111
boolean isStopped();
112
}
113
```
114
115
### Configuration Factory
116
117
Factory for creating and managing configurations from various sources.
118
119
```java { .api }
120
/**
121
* Get the configuration factory instance
122
* @return ConfigurationFactory singleton
123
*/
124
public static ConfigurationFactory getInstance();
125
126
/**
127
* Create configuration from source
128
* @param loggerContext Logger context
129
* @param name Configuration name
130
* @param configLocation Configuration location URI
131
* @return Configuration instance
132
*/
133
public abstract Configuration getConfiguration(LoggerContext loggerContext, String name, URI configLocation);
134
135
/**
136
* Get supported configuration file types
137
* @return Array of supported file extensions
138
*/
139
public abstract String[] getSupportedTypes();
140
141
/**
142
* Create configuration from configuration source
143
* @param loggerContext Logger context
144
* @param source Configuration source
145
* @return Configuration instance
146
*/
147
public Configuration getConfiguration(LoggerContext loggerContext, ConfigurationSource source);
148
```
149
150
**Usage Examples:**
151
152
```java
153
import org.apache.logging.log4j.core.config.ConfigurationFactory;
154
import org.apache.logging.log4j.core.LoggerContext;
155
import java.net.URI;
156
157
// Get factory and create configuration
158
ConfigurationFactory factory = ConfigurationFactory.getInstance();
159
LoggerContext context = LoggerContext.getContext(false);
160
161
// Load configuration from file
162
URI configLocation = new URI("file:///path/to/log4j2.xml");
163
Configuration config = factory.getConfiguration(context, "MyConfig", configLocation);
164
165
// Check supported types
166
String[] supportedTypes = factory.getSupportedTypes();
167
// Returns: [".xml", ".json", ".yaml", ".yml", ".properties"]
168
```
169
170
### Configurator Utility
171
172
Static utility class for common configuration operations.
173
174
```java { .api }
175
/**
176
* Initialize logger context with configuration
177
* @param name Context name
178
* @param loader ClassLoader to use
179
* @param configLocation Configuration file location
180
* @return Initialized LoggerContext
181
*/
182
public static LoggerContext initialize(String name, ClassLoader loader, String configLocation);
183
184
/**
185
* Initialize with configuration and external context
186
* @param name Context name
187
* @param loader ClassLoader to use
188
* @param configLocation Configuration file location
189
* @param externalContext External context object
190
* @return Initialized LoggerContext
191
*/
192
public static LoggerContext initialize(String name, ClassLoader loader, String configLocation, Object externalContext);
193
194
/**
195
* Shutdown logger context
196
* @param context LoggerContext to shutdown
197
*/
198
public static void shutdown(LoggerContext context);
199
200
/**
201
* Set log level for specific logger
202
* @param loggerName Logger name
203
* @param level Level to set
204
*/
205
public static void setLevel(String loggerName, Level level);
206
207
/**
208
* Set root logger level
209
* @param level Level to set for root logger
210
*/
211
public static void setRootLevel(Level level);
212
213
/**
214
* Set level for logger and all descendant loggers
215
* @param loggerName Logger name
216
* @param level Level to set
217
*/
218
public static void setAllLevels(String loggerName, Level level);
219
220
/**
221
* Reconfigure with new configuration file
222
* @param configLocation New configuration file location
223
* @return Updated LoggerContext
224
*/
225
public static LoggerContext reconfigure(String configLocation);
226
```
227
228
**Usage Examples:**
229
230
```java
231
import org.apache.logging.log4j.core.config.Configurator;
232
import org.apache.logging.log4j.Level;
233
234
// Initialize with custom configuration
235
LoggerContext context = Configurator.initialize(
236
"MyApplication",
237
MyApp.class.getClassLoader(),
238
"log4j2-production.xml"
239
);
240
241
// Set various logger levels
242
Configurator.setRootLevel(Level.INFO);
243
Configurator.setLevel("com.example", Level.DEBUG);
244
Configurator.setLevel("com.example.security", Level.TRACE);
245
Configurator.setAllLevels("com.example.noisy", Level.WARN);
246
247
// Reconfigure at runtime
248
LoggerContext newContext = Configurator.reconfigure("log4j2-debug.xml");
249
250
// Shutdown when application exits
251
Configurator.shutdown(context);
252
```
253
254
### LoggerConfig Management
255
256
Configuration class for individual loggers within the system.
257
258
```java { .api }
259
/**
260
* LoggerConfig manages configuration for individual loggers
261
*/
262
public class LoggerConfig {
263
/**
264
* Add appender to this logger config
265
* @param appender Appender to add
266
* @param level Minimum level for this appender
267
* @param filter Filter for this appender
268
*/
269
public void addAppender(Appender appender, Level level, Filter filter);
270
271
/**
272
* Remove appender by name
273
* @param name Appender name to remove
274
*/
275
public void removeAppender(String name);
276
277
/**
278
* Get all appenders for this logger
279
* @return Map of appender names to instances
280
*/
281
public Map<String, Appender> getAppenders();
282
283
/**
284
* Get logger level
285
* @return Current Level
286
*/
287
public Level getLevel();
288
289
/**
290
* Set logger level
291
* @param level Level to set
292
*/
293
public void setLevel(Level level);
294
295
/**
296
* Check if logger is additive
297
* @return true if additive
298
*/
299
public boolean isAdditive();
300
301
/**
302
* Set logger additivity
303
* @param additive Additivity flag
304
*/
305
public void setAdditive(boolean additive);
306
307
/**
308
* Get logger name
309
* @return Logger name
310
*/
311
public String getName();
312
313
/**
314
* Get parent logger config
315
* @return Parent LoggerConfig or null
316
*/
317
public LoggerConfig getParent();
318
}
319
```
320
321
**Usage Examples:**
322
323
```java
324
import org.apache.logging.log4j.core.config.LoggerConfig;
325
import org.apache.logging.log4j.core.appender.FileAppender;
326
327
// Get logger configuration
328
Configuration config = context.getConfiguration();
329
LoggerConfig loggerConfig = config.getLoggerConfig("com.example.MyClass");
330
331
// Configure logger
332
loggerConfig.setLevel(Level.DEBUG);
333
loggerConfig.setAdditive(false);
334
335
// Add appender to specific logger
336
FileAppender fileAppender = FileAppender.newBuilder()
337
.setName("MyClassFile")
338
.withFileName("myclass.log")
339
.build();
340
341
loggerConfig.addAppender(fileAppender, Level.INFO, null);
342
343
// Remove appender
344
loggerConfig.removeAppender("MyClassFile");
345
```
346
347
## Configuration Builder API
348
349
Programmatic configuration through fluent builder interface.
350
351
### Configuration Builder
352
353
```java { .api }
354
/**
355
* Fluent API for building configurations programmatically
356
* @param <T> Built configuration type
357
*/
358
public interface ConfigurationBuilder<T extends BuiltConfiguration> {
359
/**
360
* Set plugin packages
361
* @param packages Comma-separated package names
362
* @return ConfigurationBuilder instance
363
*/
364
ConfigurationBuilder<T> setPackages(String packages);
365
366
/**
367
* Set configuration name
368
* @param name Configuration name
369
* @return ConfigurationBuilder instance
370
*/
371
ConfigurationBuilder<T> setConfigurationName(String name);
372
373
/**
374
* Set status level for internal Log4j logging
375
* @param level Status level
376
* @return ConfigurationBuilder instance
377
*/
378
ConfigurationBuilder<T> setStatusLevel(Level level);
379
380
/**
381
* Create new appender component
382
* @param name Appender name
383
* @param type Appender type
384
* @return AppenderComponentBuilder instance
385
*/
386
AppenderComponentBuilder newAppender(String name, String type);
387
388
/**
389
* Create new layout component
390
* @param type Layout type
391
* @return LayoutComponentBuilder instance
392
*/
393
LayoutComponentBuilder newLayout(String type);
394
395
/**
396
* Create new filter component
397
* @param type Filter type
398
* @return FilterComponentBuilder instance
399
*/
400
FilterComponentBuilder newFilter(String type);
401
402
/**
403
* Create new logger component
404
* @param name Logger name
405
* @param level Logger level
406
* @return LoggerComponentBuilder instance
407
*/
408
LoggerComponentBuilder newLogger(String name, Level level);
409
410
/**
411
* Create new root logger component
412
* @param level Root logger level
413
* @return RootLoggerComponentBuilder instance
414
*/
415
RootLoggerComponentBuilder newRootLogger(Level level);
416
417
/**
418
* Build the configuration
419
* @return Built configuration instance
420
*/
421
T build();
422
}
423
```
424
425
### Configuration Builder Factory
426
427
```java { .api }
428
/**
429
* Factory for creating configuration builders
430
*/
431
public class ConfigurationBuilderFactory {
432
/**
433
* Create new configuration builder
434
* @return ConfigurationBuilder instance
435
*/
436
public static ConfigurationBuilder<BuiltConfiguration> newConfigurationBuilder();
437
}
438
```
439
440
### Component Builders
441
442
```java { .api }
443
/**
444
* Builder for appender components
445
*/
446
public interface AppenderComponentBuilder extends ComponentBuilder<AppenderComponentBuilder> {
447
AppenderComponentBuilder add(LayoutComponentBuilder layout);
448
AppenderComponentBuilder add(FilterComponentBuilder filter);
449
AppenderComponentBuilder addAttribute(String key, String value);
450
}
451
452
/**
453
* Builder for layout components
454
*/
455
public interface LayoutComponentBuilder extends ComponentBuilder<LayoutComponentBuilder> {
456
LayoutComponentBuilder addAttribute(String key, String value);
457
}
458
459
/**
460
* Builder for filter components
461
*/
462
public interface FilterComponentBuilder extends ComponentBuilder<FilterComponentBuilder> {
463
FilterComponentBuilder addAttribute(String key, String value);
464
}
465
466
/**
467
* Builder for logger components
468
*/
469
public interface LoggerComponentBuilder extends ComponentBuilder<LoggerComponentBuilder> {
470
LoggerComponentBuilder add(AppenderRef ref);
471
LoggerComponentBuilder add(FilterComponentBuilder filter);
472
LoggerComponentBuilder addAttribute(String key, String value);
473
}
474
475
/**
476
* Builder for root logger components
477
*/
478
public interface RootLoggerComponentBuilder extends ComponentBuilder<RootLoggerComponentBuilder> {
479
RootLoggerComponentBuilder add(AppenderRef ref);
480
RootLoggerComponentBuilder add(FilterComponentBuilder filter);
481
}
482
```
483
484
**Usage Examples:**
485
486
```java
487
import org.apache.logging.log4j.core.config.builder.api.*;
488
import org.apache.logging.log4j.core.config.builder.impl.BuiltConfiguration;
489
490
// Create configuration programmatically
491
ConfigurationBuilder<BuiltConfiguration> builder = ConfigurationBuilderFactory.newConfigurationBuilder();
492
493
// Set global properties
494
builder.setConfigurationName("ProgrammaticConfig")
495
.setStatusLevel(Level.WARN)
496
.setPackages("com.example.plugins");
497
498
// Create console appender
499
AppenderComponentBuilder consoleAppender = builder.newAppender("Console", "CONSOLE")
500
.addAttribute("target", "SYSTEM_OUT");
501
502
// Create pattern layout
503
LayoutComponentBuilder layoutBuilder = builder.newLayout("PatternLayout")
504
.addAttribute("pattern", "%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n");
505
consoleAppender.add(layoutBuilder);
506
507
// Create file appender
508
AppenderComponentBuilder fileAppender = builder.newAppender("File", "File")
509
.addAttribute("fileName", "application.log")
510
.addAttribute("append", "true")
511
.add(layoutBuilder);
512
513
// Create root logger
514
RootLoggerComponentBuilder rootLogger = builder.newRootLogger(Level.INFO)
515
.add(builder.newAppenderRef("Console"))
516
.add(builder.newAppenderRef("File"));
517
518
// Create specific logger
519
LoggerComponentBuilder logger = builder.newLogger("com.example", Level.DEBUG)
520
.add(builder.newAppenderRef("File"))
521
.addAttribute("additivity", "false");
522
523
// Add components to configuration
524
builder.add(consoleAppender);
525
builder.add(fileAppender);
526
builder.add(rootLogger);
527
builder.add(logger);
528
529
// Build and apply configuration
530
BuiltConfiguration config = builder.build();
531
LoggerContext context = LoggerContext.getContext(false);
532
context.start(config);
533
```
534
535
### Appender References
536
537
```java { .api }
538
/**
539
* Reference to an appender for use in logger configurations
540
*/
541
public class AppenderRef {
542
/**
543
* Create appender reference
544
* @param ref Appender name to reference
545
* @param level Minimum level for this reference
546
* @param filter Filter for this reference
547
* @return AppenderRef instance
548
*/
549
public static AppenderRef createAppenderRef(String ref, Level level, Filter filter);
550
551
/**
552
* Get referenced appender name
553
* @return Appender name
554
*/
555
public String getRef();
556
557
/**
558
* Get level for this reference
559
* @return Level or null
560
*/
561
public Level getLevel();
562
563
/**
564
* Get filter for this reference
565
* @return Filter or null
566
*/
567
public Filter getFilter();
568
}
569
```
570
571
## Configuration File Formats
572
573
### XML Configuration Example
574
```xml
575
<?xml version="1.0" encoding="UTF-8"?>
576
<Configuration status="WARN">
577
<Appenders>
578
<Console name="Console" target="SYSTEM_OUT">
579
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
580
</Console>
581
<File name="File" fileName="application.log">
582
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
583
</File>
584
</Appenders>
585
<Loggers>
586
<Logger name="com.example" level="DEBUG" additivity="false">
587
<AppenderRef ref="File"/>
588
</Logger>
589
<Root level="INFO">
590
<AppenderRef ref="Console"/>
591
<AppenderRef ref="File"/>
592
</Root>
593
</Loggers>
594
</Configuration>
595
```
596
597
### JSON Configuration Example
598
```json
599
{
600
"Configuration": {
601
"status": "WARN",
602
"Appenders": {
603
"Console": {
604
"name": "Console",
605
"target": "SYSTEM_OUT",
606
"PatternLayout": {
607
"pattern": "%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"
608
}
609
}
610
},
611
"Loggers": {
612
"Root": {
613
"level": "INFO",
614
"AppenderRef": { "ref": "Console" }
615
}
616
}
617
}
618
}
619
```
620
621
### YAML Configuration Example
622
```yaml
623
Configuration:
624
status: WARN
625
Appenders:
626
Console:
627
name: Console
628
target: SYSTEM_OUT
629
PatternLayout:
630
pattern: "%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"
631
Loggers:
632
Root:
633
level: INFO
634
AppenderRef:
635
ref: Console
636
```