0
# Apache Log4j Core
1
2
Apache Log4j Core is the reference implementation of the Log4j 2 logging framework, providing a comprehensive and industrial-grade logging solution for Java applications. It serves as the central logging engine that handles log event processing, routing, and output formatting across diverse environments with extensive configurability and high-performance capabilities.
3
4
## Package Information
5
6
- **Package Name**: log4j-core
7
- **Package Type**: maven
8
- **Group ID**: org.apache.logging.log4j
9
- **Language**: Java
10
- **Installation**: Add to Maven dependencies:
11
```xml
12
<dependency>
13
<groupId>org.apache.logging.log4j</groupId>
14
<artifactId>log4j-core</artifactId>
15
<version>2.25.1</version>
16
</dependency>
17
```
18
19
## Core Imports
20
21
```java
22
import org.apache.logging.log4j.LogManager;
23
import org.apache.logging.log4j.Logger;
24
import org.apache.logging.log4j.Level;
25
import org.apache.logging.log4j.Marker;
26
import org.apache.logging.log4j.MarkerManager;
27
import org.apache.logging.log4j.ThreadContext;
28
```
29
30
For core implementation (advanced usage):
31
```java
32
import org.apache.logging.log4j.core.LoggerContext;
33
import org.apache.logging.log4j.core.config.Configuration;
34
import org.apache.logging.log4j.core.config.Configurator;
35
import org.apache.logging.log4j.core.Appender;
36
import org.apache.logging.log4j.core.Layout;
37
import org.apache.logging.log4j.core.Filter;
38
```
39
40
## Basic Usage
41
42
```java
43
import org.apache.logging.log4j.LogManager;
44
import org.apache.logging.log4j.Logger;
45
import org.apache.logging.log4j.Level;
46
import org.apache.logging.log4j.Marker;
47
import org.apache.logging.log4j.MarkerManager;
48
import org.apache.logging.log4j.ThreadContext;
49
50
// Get loggers (most common usage)
51
Logger logger = LogManager.getLogger(MyClass.class);
52
Logger rootLogger = LogManager.getRootLogger();
53
Logger namedLogger = LogManager.getLogger("com.example.MyLogger");
54
55
// Basic logging with different levels
56
logger.trace("Detailed trace information");
57
logger.debug("Debug information: {}", debugValue);
58
logger.info("Application started successfully");
59
logger.warn("This is a warning message");
60
logger.error("Error occurred: {}", errorMessage, exception);
61
logger.fatal("Critical system failure", criticalException);
62
63
// Using markers for categorization
64
Marker sqlMarker = MarkerManager.getMarker("SQL");
65
Marker securityMarker = MarkerManager.getMarker("SECURITY");
66
logger.info(sqlMarker, "Database query executed: {}", query);
67
logger.warn(securityMarker, "Failed login attempt from {}", ipAddress);
68
69
// Thread context (MDC/NDC) for request tracking
70
ThreadContext.put("userId", "12345");
71
ThreadContext.put("sessionId", "abc-def-ghi");
72
ThreadContext.push("operation-name");
73
logger.info("Processing user request");
74
ThreadContext.clearAll();
75
76
// Programmatic configuration (advanced)
77
import org.apache.logging.log4j.core.config.Configurator;
78
Configurator.setRootLevel(Level.INFO);
79
Configurator.setLevel("com.example", Level.DEBUG);
80
```
81
82
## Architecture
83
84
Apache Log4j Core is built around several key architectural components:
85
86
- **LoggerContext**: Central management hub for all loggers and configuration
87
- **Configuration System**: Multi-format configuration support (XML, JSON, YAML, Properties)
88
- **Appender Framework**: Output destination system with 15+ built-in appenders
89
- **Layout System**: Message formatting with 10+ built-in layouts
90
- **Filter Chain**: Fine-grained event filtering with 15+ built-in filters
91
- **Plugin Architecture**: Extensible system for custom components with annotation-based registration
92
- **Async Framework**: High-performance asynchronous logging using LMAX Disruptor
93
- **Builder API**: Fluent programmatic configuration interface
94
95
## Capabilities
96
97
### Logger Management
98
99
Central entry point for obtaining and managing loggers throughout the application.
100
101
```java { .api }
102
/**
103
* LogManager - Static factory for obtaining loggers
104
*/
105
public static Logger getLogger();
106
public static Logger getLogger(Class<?> clazz);
107
public static Logger getLogger(String name);
108
public static Logger getRootLogger();
109
public static LoggerContext getContext();
110
public static LoggerContext getContext(boolean currentContext);
111
public static LoggerContext getContext(ClassLoader loader, boolean currentContext, URI configLocation);
112
113
/**
114
* Logger - Primary logging interface for applications
115
*/
116
public interface Logger {
117
// Basic logging methods for all levels
118
void trace(String message);
119
void trace(String message, Object... params);
120
void trace(String message, Throwable throwable);
121
void trace(Marker marker, String message);
122
void trace(Marker marker, String message, Object... params);
123
void trace(Marker marker, String message, Throwable throwable);
124
125
void debug(String message);
126
void debug(String message, Object... params);
127
void debug(String message, Throwable throwable);
128
void debug(Marker marker, String message);
129
void debug(Marker marker, String message, Object... params);
130
void debug(Marker marker, String message, Throwable throwable);
131
132
void info(String message);
133
void info(String message, Object... params);
134
void info(String message, Throwable throwable);
135
void info(Marker marker, String message);
136
void info(Marker marker, String message, Object... params);
137
void info(Marker marker, String message, Throwable throwable);
138
139
void warn(String message);
140
void warn(String message, Object... params);
141
void warn(String message, Throwable throwable);
142
void warn(Marker marker, String message);
143
void warn(Marker marker, String message, Object... params);
144
void warn(Marker marker, String message, Throwable throwable);
145
146
void error(String message);
147
void error(String message, Object... params);
148
void error(String message, Throwable throwable);
149
void error(Marker marker, String message);
150
void error(Marker marker, String message, Object... params);
151
void error(Marker marker, String message, Throwable throwable);
152
153
void fatal(String message);
154
void fatal(String message, Object... params);
155
void fatal(String message, Throwable throwable);
156
void fatal(Marker marker, String message);
157
void fatal(Marker marker, String message, Object... params);
158
void fatal(Marker marker, String message, Throwable throwable);
159
160
// Level checking methods
161
boolean isTraceEnabled();
162
boolean isDebugEnabled();
163
boolean isInfoEnabled();
164
boolean isWarnEnabled();
165
boolean isErrorEnabled();
166
boolean isFatalEnabled();
167
boolean isEnabled(Level level);
168
boolean isEnabled(Level level, Marker marker);
169
170
// Logger properties
171
String getName();
172
Level getLevel();
173
}
174
```
175
176
### Thread Context Management
177
178
Thread-local context management for Mapped Diagnostic Context (MDC) and Nested Diagnostic Context (NDC).
179
180
```java { .api }
181
/**
182
* ThreadContext - Thread-local diagnostic context management
183
*/
184
public static void put(String key, String value);
185
public static String get(String key);
186
public static void remove(String key);
187
public static void removeAll(Iterable<String> keys);
188
public static void clearMap();
189
public static void clearAll();
190
public static boolean containsKey(String key);
191
public static Map<String, String> getContext();
192
public static Map<String, String> getImmutableContext();
193
public static boolean isEmpty();
194
195
// Nested Diagnostic Context (NDC) operations
196
public static void push(String message);
197
public static void push(String message, Object... args);
198
public static String pop();
199
public static String peek();
200
public static void trim(int maxDepth);
201
public static ContextStack getImmutableStack();
202
public static int getDepth();
203
public static void clearStack();
204
```
205
206
### Marker System
207
208
Hierarchical markers for categorizing and filtering log events.
209
210
```java { .api }
211
/**
212
* MarkerManager - Factory for creating and managing markers
213
*/
214
public static Marker getMarker(String name);
215
public static Marker getMarker(String name, Marker parent);
216
public static Marker getMarker(String name, Marker... parents);
217
public static boolean exists(String name);
218
public static void clear();
219
220
/**
221
* Marker - Hierarchical event categorization
222
*/
223
public interface Marker {
224
String getName();
225
Marker[] getParents();
226
boolean hasParents();
227
boolean isInstanceOf(Marker marker);
228
boolean isInstanceOf(String name);
229
Marker addParents(Marker... markers);
230
boolean remove(Marker marker);
231
Marker setParents(Marker... markers);
232
}
233
```
234
235
### Message System
236
237
Message creation and formatting system for parameterized and structured logging.
238
239
```java { .api }
240
/**
241
* MessageFactory - Factory for creating Message instances
242
*/
243
public interface MessageFactory {
244
Message newMessage(Object message);
245
Message newMessage(String message);
246
Message newMessage(String message, Object... params);
247
}
248
249
/**
250
* Message - Base interface for all log messages
251
*/
252
public interface Message {
253
String getFormattedMessage();
254
String getFormat();
255
Object[] getParameters();
256
Throwable getThrowable();
257
}
258
259
/**
260
* ParameterizedMessage - Efficient parameterized message implementation
261
*/
262
public class ParameterizedMessage implements Message {
263
public ParameterizedMessage(String messagePattern, Object[] arguments);
264
public ParameterizedMessage(String messagePattern, Object... arguments);
265
public ParameterizedMessage(String messagePattern, Object arg);
266
public ParameterizedMessage(String messagePattern, Object arg1, Object arg2);
267
// Additional constructors for performance optimization
268
}
269
270
/**
271
* FormattedMessage - Printf-style formatted messages
272
*/
273
public class FormattedMessage implements Message {
274
public FormattedMessage(String messagePattern, Object... arguments);
275
public FormattedMessage(Locale locale, String messagePattern, Object... arguments);
276
}
277
278
/**
279
* ObjectMessage - Simple object-based messages
280
*/
281
public class ObjectMessage implements Message {
282
public ObjectMessage(Object obj);
283
}
284
```
285
286
### Core Logging Context
287
288
Central management of loggers, configuration, and lifecycle operations. Essential for any logging setup and dynamic configuration changes.
289
290
```java { .api }
291
public static LoggerContext getContext();
292
public static LoggerContext getContext(boolean currentContext);
293
public static LoggerContext getContext(ClassLoader loader, boolean currentContext, URI configLocation);
294
295
public void start();
296
public void start(Configuration config);
297
public boolean stop(long timeout, TimeUnit timeUnit);
298
public Logger getLogger(String name);
299
public Configuration getConfiguration();
300
public Configuration setConfiguration(Configuration config);
301
```
302
303
[Core Context Management](./core-context.md)
304
305
### Appender System
306
307
Output destination framework for routing log events to various targets including files, databases, network sockets, and message queues.
308
309
```java { .api }
310
public interface Appender extends LifeCycle {
311
void append(LogEvent event);
312
String getName();
313
Layout<? extends Serializable> getLayout();
314
boolean ignoreExceptions();
315
ErrorHandler getHandler();
316
}
317
```
318
319
[Appenders](./appenders.md)
320
321
### Layout System
322
323
Message formatting system that converts log events into structured output formats including pattern-based, JSON, XML, and custom formats.
324
325
```java { .api }
326
public interface Layout<T extends Serializable> extends Encodable {
327
byte[] getHeader();
328
byte[] getFooter();
329
byte[] toByteArray(LogEvent event);
330
T toSerializable(LogEvent event);
331
String getContentType();
332
}
333
```
334
335
[Layouts](./layouts.md)
336
337
### Filter Framework
338
339
Event filtering system for fine-grained control over which log events are processed, with support for level-based, marker-based, and custom filtering.
340
341
```java { .api }
342
public interface Filter {
343
enum Result { ACCEPT, NEUTRAL, DENY }
344
345
Result getOnMatch();
346
Result getOnMismatch();
347
Result filter(Logger logger, Level level, Marker marker, String msg, Object... params);
348
Result filter(LogEvent event);
349
}
350
```
351
352
[Filters](./filters.md)
353
354
### Configuration Management
355
356
Multi-format configuration system supporting XML, JSON, YAML, and Properties files, plus programmatic configuration through builder API.
357
358
```java { .api }
359
public interface Configuration {
360
String getName();
361
LoggerConfig getLoggerConfig(String name);
362
Map<String, Appender> getAppenders();
363
LoggerConfig getRootLogger();
364
List<String> getPluginPackages();
365
}
366
```
367
368
[Configuration](./configuration.md)
369
370
### Variable Substitution Lookups
371
372
Dynamic variable substitution system for configuration files, supporting environment variables, system properties, context data, and custom lookup implementations.
373
374
```java { .api }
375
/**
376
* Core lookup interface for variable substitution
377
*/
378
public interface StrLookup {
379
String lookup(String key);
380
String lookup(LogEvent event, String key);
381
}
382
383
// Built-in lookup implementations
384
public class SystemPropertiesLookup implements StrLookup;
385
public class EnvironmentLookup implements StrLookup;
386
public class ContextMapLookup implements StrLookup;
387
public class DateLookup implements StrLookup;
388
public class JavaLookup implements StrLookup;
389
```
390
391
[Variable Lookups](./lookups.md)
392
393
### Asynchronous Logging
394
395
High-performance asynchronous logging system using LMAX Disruptor for maximum throughput with minimal latency impact on application threads.
396
397
```java { .api }
398
public class AsyncLogger extends Logger {
399
// Inherits all Logger methods with async implementation
400
}
401
402
public interface AsyncQueueFullPolicy {
403
EventRoute getRoute(long backgroundThreadId, Level level);
404
}
405
```
406
407
[Async Logging](./async-logging.md)
408
409
### Plugin Architecture
410
411
Extensible plugin system allowing custom appenders, layouts, filters, and other components through annotation-based registration and factory methods.
412
413
```java { .api }
414
@Plugin(name = "MyPlugin", category = Core.CATEGORY_NAME, elementType = "appender")
415
public class MyAppender extends AbstractAppender {
416
@PluginFactory
417
public static MyAppender createAppender(
418
@PluginAttribute("name") String name,
419
@PluginElement("Layout") Layout<? extends Serializable> layout) {
420
// Factory implementation
421
}
422
}
423
```
424
425
[Plugin System](./plugins.md)
426
427
## Types
428
429
```java { .api }
430
public enum Level {
431
OFF(0), FATAL(100), ERROR(200), WARN(300), INFO(400), DEBUG(500), TRACE(600), ALL(Integer.MAX_VALUE);
432
433
public boolean isMoreSpecificThan(Level level);
434
public boolean isLessSpecificThan(Level level);
435
}
436
437
public interface LogEvent {
438
Level getLevel();
439
String getLoggerName();
440
Message getMessage();
441
long getTimeMillis();
442
Marker getMarker();
443
String getThreadName();
444
StackTraceElement getSource();
445
Throwable getThrown();
446
}
447
448
public interface LifeCycle {
449
enum State { INITIALIZING, INITIALIZED, STARTING, STARTED, STOPPING, STOPPED }
450
451
State getState();
452
void initialize();
453
void start();
454
void stop();
455
boolean isStarted();
456
boolean isStopped();
457
}
458
```