0
# Marker-Based Logging
1
2
Enhanced logging with markers for categorization, filtering, and contextual organization of log events. Markers provide a way to tag log events with additional metadata for advanced filtering and routing.
3
4
## Capabilities
5
6
### Marker Creation and Management
7
8
Create and manage markers using the MarkerFactory.
9
10
```java { .api }
11
/**
12
* Get or create a marker with the given name
13
* @param name The marker name
14
* @return Marker instance
15
* @throws IllegalArgumentException if name is null
16
*/
17
Marker getMarker(String name);
18
19
/**
20
* Check if a marker with the given name exists
21
* @param name The marker name
22
* @return true if marker exists
23
*/
24
boolean exists(String name);
25
26
/**
27
* Detach marker (not supported - always returns false)
28
* @param name The marker name
29
* @return false (Log4j does not support detached markers)
30
*/
31
boolean detachMarker(String name);
32
33
/**
34
* Get detached marker (returns attached marker with warning)
35
* @param name The marker name
36
* @return The marker (attached, not detached)
37
*/
38
Marker getDetachedMarker(String name);
39
```
40
41
**Usage Examples:**
42
43
```java
44
import org.slf4j.Marker;
45
import org.slf4j.MarkerFactory;
46
47
// Create/get markers
48
Marker securityMarker = MarkerFactory.getMarker("SECURITY");
49
Marker auditMarker = MarkerFactory.getMarker("AUDIT");
50
Marker performanceMarker = MarkerFactory.getMarker("PERFORMANCE");
51
52
// Check if marker exists
53
if (MarkerFactory.exists("SECURITY")) {
54
// marker already exists
55
}
56
```
57
58
### Marker Properties and Hierarchy
59
60
Work with marker properties and hierarchical relationships.
61
62
```java { .api }
63
/**
64
* Get the marker name
65
* @return The marker name
66
*/
67
String getName();
68
69
/**
70
* Add a child marker (creates parent-child relationship)
71
* @param reference The child marker to add
72
* @throws IllegalArgumentException if reference is null
73
*/
74
void add(Marker reference);
75
76
/**
77
* Remove a child marker
78
* @param reference The child marker to remove
79
* @return true if the marker was removed
80
*/
81
boolean remove(Marker reference);
82
83
/**
84
* Check if this marker has child markers
85
* @return true if marker has children
86
*/
87
boolean hasChildren();
88
89
/**
90
* Check if this marker has parent references
91
* @return true if marker has references
92
*/
93
boolean hasReferences();
94
95
/**
96
* Get iterator over child markers
97
* @return Iterator over child markers
98
*/
99
Iterator<Marker> iterator();
100
101
/**
102
* Check if this marker contains another marker (hierarchically)
103
* @param other The marker to check for
104
* @return true if this marker contains the other marker
105
*/
106
boolean contains(Marker other);
107
108
/**
109
* Check if this marker contains a marker with the given name
110
* @param name The marker name to check for
111
* @return true if this marker contains a marker with the given name
112
*/
113
boolean contains(String name);
114
```
115
116
**Usage Examples:**
117
118
```java
119
// Create hierarchical markers
120
Marker securityMarker = MarkerFactory.getMarker("SECURITY");
121
Marker authMarker = MarkerFactory.getMarker("AUTH");
122
Marker authFailureMarker = MarkerFactory.getMarker("AUTH_FAILURE");
123
124
// Build hierarchy
125
securityMarker.add(authMarker);
126
authMarker.add(authFailureMarker);
127
128
// Check hierarchy
129
if (securityMarker.contains("AUTH_FAILURE")) {
130
// AUTH_FAILURE is contained within SECURITY hierarchy
131
}
132
133
// Iterate over children
134
for (Iterator<Marker> it = securityMarker.iterator(); it.hasNext(); ) {
135
Marker child = it.next();
136
logger.debug("Child marker: {}", child.getName());
137
}
138
```
139
140
### Trace Level with Markers
141
142
Trace-level logging with marker support.
143
144
```java { .api }
145
void trace(Marker marker, String msg);
146
void trace(Marker marker, String format, Object arg);
147
void trace(Marker marker, String format, Object arg1, Object arg2);
148
void trace(Marker marker, String format, Object... arguments);
149
void trace(Marker marker, String msg, Throwable t);
150
boolean isTraceEnabled(Marker marker);
151
```
152
153
**Usage Examples:**
154
155
```java
156
Marker performanceMarker = MarkerFactory.getMarker("PERFORMANCE");
157
158
logger.trace(performanceMarker, "Method execution started");
159
logger.trace(performanceMarker, "Processing {} items", itemCount);
160
161
if (logger.isTraceEnabled(performanceMarker)) {
162
logger.trace(performanceMarker, "Detailed timing: {}", getDetailedTiming());
163
}
164
```
165
166
### Debug Level with Markers
167
168
Debug-level logging with marker support.
169
170
```java { .api }
171
void debug(Marker marker, String msg);
172
void debug(Marker marker, String format, Object arg);
173
void debug(Marker marker, String format, Object arg1, Object arg2);
174
void debug(Marker marker, String format, Object... arguments);
175
void debug(Marker marker, String msg, Throwable t);
176
boolean isDebugEnabled(Marker marker);
177
```
178
179
**Usage Examples:**
180
181
```java
182
Marker databaseMarker = MarkerFactory.getMarker("DATABASE");
183
184
logger.debug(databaseMarker, "Executing query");
185
logger.debug(databaseMarker, "Query executed in {} ms", executionTime);
186
logger.debug(databaseMarker, "Connection pool stats: active={}, idle={}", active, idle);
187
```
188
189
### Info Level with Markers
190
191
Info-level logging with marker support.
192
193
```java { .api }
194
void info(Marker marker, String msg);
195
void info(Marker marker, String format, Object arg);
196
void info(Marker marker, String format, Object arg1, Object arg2);
197
void info(Marker marker, String format, Object... arguments);
198
void info(Marker marker, String msg, Throwable t);
199
boolean isInfoEnabled(Marker marker);
200
```
201
202
**Usage Examples:**
203
204
```java
205
Marker auditMarker = MarkerFactory.getMarker("AUDIT");
206
207
logger.info(auditMarker, "User action recorded");
208
logger.info(auditMarker, "User {} performed action {}", userId, action);
209
logger.info(auditMarker, "Resource {} accessed by {} at {}", resource, user, timestamp);
210
```
211
212
### Warn Level with Markers
213
214
Warning-level logging with marker support.
215
216
```java { .api }
217
void warn(Marker marker, String msg);
218
void warn(Marker marker, String format, Object arg);
219
void warn(Marker marker, String format, Object arg1, Object arg2);
220
void warn(Marker marker, String format, Object... arguments);
221
void warn(Marker marker, String msg, Throwable t);
222
boolean isWarnEnabled(Marker marker);
223
```
224
225
**Usage Examples:**
226
227
```java
228
Marker securityMarker = MarkerFactory.getMarker("SECURITY");
229
230
logger.warn(securityMarker, "Suspicious activity detected");
231
logger.warn(securityMarker, "Failed login attempt from {}", ipAddress);
232
logger.warn(securityMarker, "Rate limit exceeded for user {} from {}", userId, ipAddress);
233
```
234
235
### Error Level with Markers
236
237
Error-level logging with marker support.
238
239
```java { .api }
240
void error(Marker marker, String msg);
241
void error(Marker marker, String format, Object arg);
242
void error(Marker marker, String format, Object arg1, Object arg2);
243
void error(Marker marker, String format, Object... arguments);
244
void error(Marker marker, String msg, Throwable t);
245
boolean isErrorEnabled(Marker marker);
246
```
247
248
**Usage Examples:**
249
250
```java
251
Marker systemMarker = MarkerFactory.getMarker("SYSTEM");
252
253
logger.error(systemMarker, "Critical system failure");
254
logger.error(systemMarker, "Service {} is unavailable", serviceName);
255
logger.error(systemMarker, "Payment processing failed for transaction {}", transactionId, exception);
256
```
257
258
## Common Marker Patterns
259
260
### Security and Audit Markers
261
262
```java
263
// Security-related markers
264
Marker SECURITY = MarkerFactory.getMarker("SECURITY");
265
Marker AUTH = MarkerFactory.getMarker("AUTH");
266
Marker AUTHORIZATION = MarkerFactory.getMarker("AUTHORIZATION");
267
Marker AUDIT = MarkerFactory.getMarker("AUDIT");
268
269
// Build security hierarchy
270
SECURITY.add(AUTH);
271
SECURITY.add(AUTHORIZATION);
272
273
// Usage
274
logger.warn(AUTH, "Invalid login attempt for user {}", username);
275
logger.info(AUDIT, "User {} accessed resource {}", userId, resourceId);
276
```
277
278
### Performance Monitoring Markers
279
280
```java
281
Marker PERFORMANCE = MarkerFactory.getMarker("PERFORMANCE");
282
Marker SLOW_QUERY = MarkerFactory.getMarker("SLOW_QUERY");
283
Marker MEMORY_WARNING = MarkerFactory.getMarker("MEMORY_WARNING");
284
285
PERFORMANCE.add(SLOW_QUERY);
286
PERFORMANCE.add(MEMORY_WARNING);
287
288
// Usage
289
logger.warn(SLOW_QUERY, "Query took {} ms: {}", duration, query);
290
logger.warn(MEMORY_WARNING, "Memory usage at {}%", memoryPercent);
291
```
292
293
### Business Domain Markers
294
295
```java
296
Marker ORDER_PROCESSING = MarkerFactory.getMarker("ORDER_PROCESSING");
297
Marker PAYMENT = MarkerFactory.getMarker("PAYMENT");
298
Marker INVENTORY = MarkerFactory.getMarker("INVENTORY");
299
300
// Usage in business logic
301
logger.info(ORDER_PROCESSING, "Order {} created for customer {}", orderId, customerId);
302
logger.error(PAYMENT, "Payment failed for order {}", orderId, paymentException);
303
logger.warn(INVENTORY, "Low stock alert for product {}", productId);
304
```
305
306
## Advanced Marker Usage
307
308
### Converting External Markers
309
310
The implementation can convert markers from other SLF4J implementations.
311
312
```java { .api }
313
/**
314
* Convert an existing SLF4J marker to Log4j-compatible marker
315
* @param marker The SLF4J marker to convert
316
* @return Log4j-compatible marker
317
*/
318
Marker getMarker(Marker marker);
319
```
320
321
### Marker Lifecycle Management
322
323
```java
324
// Marker creation is thread-safe and cached
325
Marker marker1 = MarkerFactory.getMarker("TEST");
326
Marker marker2 = MarkerFactory.getMarker("TEST");
327
// marker1 == marker2 (same instance)
328
329
// Markers persist for the lifetime of the application
330
// No explicit cleanup required
331
```
332
333
### Integration with Log4j Configuration
334
335
Markers can be used in Log4j configuration for filtering and routing:
336
337
```xml
338
<!-- log4j2.xml example -->
339
<Configuration>
340
<Appenders>
341
<File name="SecurityLog" fileName="security.log">
342
<MarkerFilter marker="SECURITY" onMatch="ACCEPT" onMismatch="DENY"/>
343
</File>
344
<File name="AuditLog" fileName="audit.log">
345
<MarkerFilter marker="AUDIT" onMatch="ACCEPT" onMismatch="DENY"/>
346
</File>
347
</Appenders>
348
<Loggers>
349
<Root level="info">
350
<AppenderRef ref="SecurityLog"/>
351
<AppenderRef ref="AuditLog"/>
352
</Root>
353
</Loggers>
354
</Configuration>
355
```