0
# Configuration
1
2
Programmatic and XML-based configuration for loggers, appenders, and overall system behavior. Logback provides flexible configuration through multiple mechanisms including XML files, Groovy scripts, and programmatic APIs.
3
4
## Capabilities
5
6
### Basic Configuration
7
8
Simple programmatic configuration utilities for quick setup.
9
10
```java { .api }
11
/**
12
* Utility class for basic programmatic configuration
13
*/
14
public class BasicConfigurator {
15
/**
16
* Configure the logger context with a basic console appender
17
* @param lc the logger context to configure
18
*/
19
public static void configure(LoggerContext lc);
20
21
/**
22
* Configure with custom appender
23
* @param lc the logger context
24
* @param appender the appender to add to root logger
25
*/
26
public static void configureDefaultContext();
27
}
28
```
29
30
**Usage Examples:**
31
32
```java
33
import ch.qos.logback.classic.BasicConfigurator;
34
import ch.qos.logback.classic.LoggerContext;
35
import org.slf4j.LoggerFactory;
36
37
// Basic console configuration
38
LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
39
BasicConfigurator.configure(context);
40
41
// Alternative for default context
42
BasicConfigurator.configureDefaultContext();
43
```
44
45
### Configurator SPI
46
47
Service Provider Interface for custom configuration implementations.
48
49
```java { .api }
50
/**
51
* SPI for programmatic configuration of Logback
52
*/
53
public interface Configurator extends ContextAware {
54
/**
55
* Execution status for configurator chain
56
*/
57
enum ExecutionStatus {
58
NEUTRAL, // Let caller decide
59
INVOKE_NEXT_IF_ANY, // Continue to next configurator
60
DO_NOT_INVOKE_NEXT_IF_ANY // Stop configurator chain
61
}
62
63
/**
64
* Configure the logger context
65
* @param loggerContext the context to configure
66
* @return execution status indicating whether to continue chain
67
*/
68
ExecutionStatus configure(LoggerContext loggerContext);
69
}
70
71
/**
72
* Annotation for configurator ranking
73
*/
74
@Target(ElementType.TYPE)
75
@Retention(RetentionPolicy.RUNTIME)
76
public @interface ConfiguratorRank {
77
int value() default 0;
78
}
79
```
80
81
**Usage Examples:**
82
83
```java
84
import ch.qos.logback.classic.spi.Configurator;
85
import ch.qos.logback.classic.LoggerContext;
86
87
@ConfiguratorRank(100)
88
public class CustomConfigurator implements Configurator {
89
90
@Override
91
public ExecutionStatus configure(LoggerContext loggerContext) {
92
// Custom configuration logic
93
Logger rootLogger = loggerContext.getLogger(Logger.ROOT_LOGGER_NAME);
94
95
ConsoleAppender<ILoggingEvent> appender = new ConsoleAppender<>();
96
appender.setContext(loggerContext);
97
appender.setName("console");
98
99
PatternLayoutEncoder encoder = new PatternLayoutEncoder();
100
encoder.setContext(loggerContext);
101
encoder.setPattern("%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n");
102
encoder.start();
103
104
appender.setEncoder(encoder);
105
appender.start();
106
107
rootLogger.addAppender(appender);
108
rootLogger.setLevel(Level.INFO);
109
110
return ExecutionStatus.INVOKE_NEXT_IF_ANY;
111
}
112
113
@Override
114
public void setContext(Context context) {
115
// Implementation
116
}
117
118
@Override
119
public Context getContext() {
120
return null; // Implementation
121
}
122
}
123
```
124
125
### Context Configuration
126
127
Advanced context configuration and management capabilities.
128
129
```java { .api }
130
/**
131
* Context selector for choosing logger contexts in different environments
132
*/
133
public interface ContextSelector {
134
LoggerContext getLoggerContext();
135
LoggerContext getLoggerContext(String name);
136
LoggerContext getDefaultLoggerContext();
137
LoggerContext detachLoggerContext(String loggerContextName);
138
List<String> getContextNames();
139
}
140
141
/**
142
* Default context selector implementation
143
*/
144
public class DefaultContextSelector implements ContextSelector {
145
private LoggerContext defaultLoggerContext;
146
147
public LoggerContext getLoggerContext();
148
public LoggerContext getLoggerContext(String name);
149
public LoggerContext getDefaultLoggerContext();
150
public LoggerContext detachLoggerContext(String loggerContextName);
151
public List<String> getContextNames();
152
}
153
154
/**
155
* JNDI-based context selector for enterprise environments
156
*/
157
public class ContextJNDISelector implements ContextSelector {
158
// JNDI-based context selection logic
159
}
160
```
161
162
### XML Configuration Framework
163
164
Joran framework components for XML-based configuration processing.
165
166
```java { .api }
167
/**
168
* Main configuration interpreter for XML files
169
*/
170
public class JoranConfigurator extends GenericConfigurator {
171
/**
172
* Configure from XML file
173
* @param file the configuration file
174
*/
175
public void doConfigure(File file) throws JoranException;
176
177
/**
178
* Configure from URL
179
* @param url the configuration URL
180
*/
181
public void doConfigure(URL url) throws JoranException;
182
183
/**
184
* Configure from input stream
185
* @param inputStream the configuration stream
186
*/
187
public void doConfigure(InputStream inputStream) throws JoranException;
188
}
189
190
/**
191
* Context initializer handling automatic configuration
192
*/
193
public class ContextInitializer {
194
public static final String AUTOCONFIG_FILE = "logback.xml";
195
public static final String TEST_AUTOCONFIG_FILE = "logback-test.xml";
196
public static final String CONFIG_FILE_PROPERTY = "logback.configurationFile";
197
198
public void autoConfig() throws JoranException;
199
public void configureByResource(URL url) throws JoranException;
200
public URL findURLOfDefaultConfigurationFile(boolean updateStatus);
201
}
202
```
203
204
**Usage Examples:**
205
206
```java
207
import ch.qos.logback.classic.joran.JoranConfigurator;
208
import ch.qos.logback.classic.util.ContextInitializer;
209
import ch.qos.logback.core.joran.spi.JoranException;
210
211
// Manual XML configuration
212
LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
213
JoranConfigurator configurator = new JoranConfigurator();
214
configurator.setContext(context);
215
216
try {
217
context.reset();
218
configurator.doConfigure(new File("logback-config.xml"));
219
} catch (JoranException e) {
220
// Handle configuration error
221
}
222
223
// Automatic configuration
224
ContextInitializer ci = new ContextInitializer(context);
225
try {
226
ci.autoConfig();
227
} catch (JoranException e) {
228
// Handle configuration error
229
}
230
```
231
232
### Model-Based Configuration
233
234
Configuration model objects for programmatic configuration building.
235
236
```java { .api }
237
/**
238
* Configuration model for loggers
239
*/
240
public class LoggerModel extends ComponentModel {
241
String name;
242
String level;
243
Boolean additivity;
244
245
public String getName();
246
public void setName(String name);
247
public String getLevel();
248
public void setLevel(String level);
249
public Boolean getAdditivity();
250
public void setAdditivity(Boolean additivity);
251
}
252
253
/**
254
* Configuration model for appenders
255
*/
256
public class AppenderModel extends ComponentModel {
257
String name;
258
String className;
259
260
public String getName();
261
public void setName(String name);
262
public String getClassName();
263
public void setClassName(String className);
264
}
265
266
/**
267
* Root configuration model
268
*/
269
public class ConfigurationModel extends Model {
270
Boolean debug;
271
Duration scanPeriod;
272
Boolean packagingData;
273
274
public Boolean getDebug();
275
public void setDebug(Boolean debug);
276
public Duration getScanPeriod();
277
public void setScanPeriod(Duration scanPeriod);
278
public Boolean getPackagingData();
279
public void setPackagingData(Boolean packagingData);
280
}
281
```
282
283
### Utility Classes
284
285
Configuration utility classes and helpers.
286
287
```java { .api }
288
/**
289
* Utilities for logger name operations
290
*/
291
public class LoggerNameUtil {
292
public static int getFirstSeparatorIndexOf(String name);
293
public static boolean startsWithSeparator(String name);
294
public static boolean endsWithSeparator(String name);
295
public static String getPackageName(String loggerName);
296
}
297
298
/**
299
* Context initialization utilities
300
*/
301
public class ContextInitializer {
302
public static final String AUTOCONFIG_FILE = "logback.xml";
303
public static final String TEST_AUTOCONFIG_FILE = "logback-test.xml";
304
305
public ContextInitializer(LoggerContext loggerContext);
306
public void autoConfig() throws JoranException;
307
public void configureByResource(URL url) throws JoranException;
308
public URL findURLOfDefaultConfigurationFile(boolean updateStatus);
309
public void multiplicityWarning(String resourceName, ClassLoader classLoader);
310
}
311
```
312
313
## Configuration Examples
314
315
### Programmatic Configuration
316
317
```java
318
import ch.qos.logback.classic.*;
319
import ch.qos.logback.classic.encoder.PatternLayoutEncoder;
320
import ch.qos.logback.core.ConsoleAppender;
321
322
LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
323
324
// Create console appender
325
ConsoleAppender<ILoggingEvent> appender = new ConsoleAppender<>();
326
appender.setContext(context);
327
appender.setName("console");
328
329
// Create encoder
330
PatternLayoutEncoder encoder = new PatternLayoutEncoder();
331
encoder.setContext(context);
332
encoder.setPattern("%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n");
333
encoder.start();
334
335
appender.setEncoder(encoder);
336
appender.start();
337
338
// Configure root logger
339
Logger rootLogger = context.getLogger(Logger.ROOT_LOGGER_NAME);
340
rootLogger.addAppender(appender);
341
rootLogger.setLevel(Level.INFO);
342
343
// Configure specific logger
344
Logger logger = context.getLogger("com.example.app");
345
logger.setLevel(Level.DEBUG);
346
logger.setAdditive(false); // Don't inherit appenders from parent
347
```
348
349
### XML Configuration Structure
350
351
The XML configuration uses a hierarchical structure with the following key elements:
352
353
- `<configuration>` - Root element
354
- `<appender>` - Output destination configuration
355
- `<encoder>` or `<layout>` - Message formatting
356
- `<logger>` - Logger-specific configuration
357
- `<root>` - Root logger configuration
358
- `<filter>` - Event filtering rules
359
360
Configuration files are automatically discovered in this order:
361
1. `logback-test.xml` (if in test classpath)
362
2. `logback.xml` (if in classpath)
363
3. Service provider configured via `ServiceLoader`
364
4. `BasicConfigurator` as fallback