0
# Logging Framework Integration
1
2
Automatic logger field generation for major Java logging frameworks with configurable topics and field names. These annotations eliminate boilerplate logger declarations and provide seamless integration with popular logging libraries.
3
4
## Capabilities
5
6
### @Slf4j Annotation
7
8
Generates SLF4J logger field for the Simple Logging Facade for Java, the most widely used logging abstraction.
9
10
```java { .api }
11
/**
12
* Generates a private static final SLF4J Logger field named 'log'.
13
* Uses org.slf4j.LoggerFactory.getLogger() for logger creation.
14
*/
15
@Target(ElementType.TYPE)
16
@interface Slf4j {
17
/**
18
* Custom logger category/name instead of using class name
19
* @return Logger category (default: uses annotated class name)
20
*/
21
String topic() default "";
22
}
23
```
24
25
**Usage Examples:**
26
27
```java
28
import lombok.extern.slf4j.Slf4j;
29
30
@Slf4j
31
public class UserService {
32
33
public void createUser(String username) {
34
log.info("Creating user: {}", username);
35
36
try {
37
// User creation logic
38
log.debug("User creation successful for: {}", username);
39
} catch (Exception e) {
40
log.error("Failed to create user: {}", username, e);
41
throw new ServiceException("User creation failed", e);
42
}
43
}
44
45
public void processUsers(List<User> users) {
46
log.info("Processing {} users", users.size());
47
48
users.forEach(user -> {
49
log.trace("Processing user: {}", user.getId());
50
processUser(user);
51
});
52
53
log.info("Completed processing all users");
54
}
55
}
56
57
// Generated field:
58
// private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(UserService.class);
59
```
60
61
Custom topic example:
62
```java
63
@Slf4j(topic = "AUDIT")
64
public class AuditService {
65
66
public void auditUserAction(String userId, String action) {
67
log.info("User {} performed action: {}", userId, action);
68
}
69
}
70
71
// Generated field:
72
// private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger("AUDIT");
73
```
74
75
### @XSlf4j Annotation
76
77
Generates extended SLF4J logger field with additional logging methods and fluent API support.
78
79
```java { .api }
80
/**
81
* Generates a private static final extended SLF4J Logger field named 'log'.
82
* Provides additional logging methods beyond standard SLF4J Logger.
83
*/
84
@Target(ElementType.TYPE)
85
@interface XSlf4j {
86
/**
87
* Custom logger category/name instead of using class name
88
* @return Logger category (default: uses annotated class name)
89
*/
90
String topic() default "";
91
}
92
```
93
94
**Usage Examples:**
95
96
```java
97
import lombok.extern.slf4j.XSlf4j;
98
99
@XSlf4j
100
public class ExtendedLoggingService {
101
102
public void processRequest(String requestId, Map<String, Object> data) {
103
// Extended SLF4J provides fluent API and additional methods
104
log.atInfo()
105
.addKeyValue("requestId", requestId)
106
.addKeyValue("dataSize", data.size())
107
.log("Processing request");
108
109
// Standard SLF4J methods also available
110
log.debug("Request data: {}", data);
111
112
try {
113
processData(data);
114
115
log.atInfo()
116
.addKeyValue("requestId", requestId)
117
.addKeyValue("status", "success")
118
.log("Request processed successfully");
119
120
} catch (Exception e) {
121
log.atError()
122
.addKeyValue("requestId", requestId)
123
.addKeyValue("error", e.getMessage())
124
.setCause(e)
125
.log("Request processing failed");
126
}
127
}
128
}
129
130
// Generated field:
131
// private static final org.slf4j.ext.XLogger log = org.slf4j.ext.XLoggerFactory.getXLogger(ExtendedLoggingService.class);
132
```
133
134
### @Log Annotation
135
136
Generates Java Util Logging (JUL) logger field using the standard Java logging framework.
137
138
```java { .api }
139
/**
140
* Generates a private static final java.util.logging.Logger field named 'log'.
141
* Uses java.util.logging.Logger.getLogger() for logger creation.
142
*/
143
@Target(ElementType.TYPE)
144
@interface Log {
145
/**
146
* Custom logger category/name instead of using class name
147
* @return Logger category (default: uses annotated class name)
148
*/
149
String topic() default "";
150
}
151
```
152
153
**Usage Examples:**
154
155
```java
156
import lombok.extern.java.Log;
157
import java.util.logging.Level;
158
159
@Log
160
public class JavaUtilLoggingService {
161
162
public void performOperation(String operationId) {
163
log.info("Starting operation: " + operationId);
164
165
try {
166
// Operation logic
167
log.log(Level.FINE, "Operation {0} completed successfully", operationId);
168
169
} catch (Exception e) {
170
log.log(Level.SEVERE, "Operation failed: " + operationId, e);
171
throw new RuntimeException("Operation failed", e);
172
}
173
}
174
175
public void configureLogging() {
176
log.setLevel(Level.INFO);
177
log.addHandler(new ConsoleHandler());
178
}
179
}
180
181
// Generated field:
182
// private static final java.util.logging.Logger log = java.util.logging.Logger.getLogger(JavaUtilLoggingService.class.getName());
183
```
184
185
### @Log4j2 Annotation
186
187
Generates Log4j 2.x logger field for the Apache Log4j 2 logging framework.
188
189
```java { .api }
190
/**
191
* Generates a private static final Log4j 2 Logger field named 'log'.
192
* Uses org.apache.logging.log4j.LogManager.getLogger() for logger creation.
193
*/
194
@Target(ElementType.TYPE)
195
@interface Log4j2 {
196
/**
197
* Custom logger category/name instead of using class name
198
* @return Logger category (default: uses annotated class name)
199
*/
200
String topic() default "";
201
}
202
```
203
204
**Usage Examples:**
205
206
```java
207
import lombok.extern.log4j.Log4j2;
208
import org.apache.logging.log4j.Marker;
209
import org.apache.logging.log4j.MarkerManager;
210
211
@Log4j2
212
public class Log4j2Service {
213
private static final Marker BUSINESS_MARKER = MarkerManager.getMarker("BUSINESS");
214
215
public void processBusinessEvent(String eventId, Object eventData) {
216
log.info(BUSINESS_MARKER, "Processing business event: {}", eventId);
217
218
// Log4j2 supports lambda expressions for lazy evaluation
219
log.debug("Event data: {}", () -> expensiveToStringOperation(eventData));
220
221
try {
222
handleEvent(eventData);
223
log.info(BUSINESS_MARKER, "Business event {} processed successfully", eventId);
224
225
} catch (Exception e) {
226
log.error("Failed to process business event: {}", eventId, e);
227
228
// Log4j2 fluent API
229
log.atError()
230
.withMarker(BUSINESS_MARKER)
231
.withThrowable(e)
232
.log("Critical business event failure: {}", eventId);
233
}
234
}
235
}
236
237
// Generated field:
238
// private static final org.apache.logging.log4j.Logger log = org.apache.logging.log4j.LogManager.getLogger(Log4j2Service.class);
239
```
240
241
### @Log4j Annotation
242
243
Generates Log4j 1.x logger field for legacy Log4j applications.
244
245
```java { .api }
246
/**
247
* Generates a private static final Log4j 1.x Logger field named 'log'.
248
* Uses org.apache.log4j.Logger.getLogger() for logger creation.
249
*/
250
@Target(ElementType.TYPE)
251
@interface Log4j {
252
/**
253
* Custom logger category/name instead of using class name
254
* @return Logger category (default: uses annotated class name)
255
*/
256
String topic() default "";
257
}
258
```
259
260
**Usage Examples:**
261
262
```java
263
import lombok.extern.log4j.Log4j;
264
import org.apache.log4j.Level;
265
import org.apache.log4j.NDC;
266
267
@Log4j
268
public class LegacyLog4jService {
269
270
public void processLegacySystem(String systemId) {
271
NDC.push(systemId);
272
273
try {
274
log.info("Processing legacy system: " + systemId);
275
276
if (log.isDebugEnabled()) {
277
log.debug("System configuration: " + getSystemConfig(systemId));
278
}
279
280
// Process system
281
log.info("Legacy system processing completed");
282
283
} catch (Exception e) {
284
log.error("Legacy system processing failed", e);
285
log.fatal("Critical error in system: " + systemId);
286
287
} finally {
288
NDC.pop();
289
}
290
}
291
}
292
293
// Generated field:
294
// private static final org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(LegacyLog4jService.class);
295
```
296
297
### @CommonsLog Annotation
298
299
Generates Apache Commons Logging logger field for applications using JCL.
300
301
```java { .api }
302
/**
303
* Generates a private static final Apache Commons Log field named 'log'.
304
* Uses org.apache.commons.logging.LogFactory.getLog() for logger creation.
305
*/
306
@Target(ElementType.TYPE)
307
@interface CommonsLog {
308
/**
309
* Custom logger category/name instead of using class name
310
* @return Logger category (default: uses annotated class name)
311
*/
312
String topic() default "";
313
}
314
```
315
316
**Usage Examples:**
317
318
```java
319
import lombok.extern.apachecommons.CommonsLog;
320
321
@CommonsLog
322
public class CommonsLoggingService {
323
324
public void executeTask(String taskId) {
325
log.info("Executing task: " + taskId);
326
327
if (log.isDebugEnabled()) {
328
log.debug("Task configuration loaded for: " + taskId);
329
}
330
331
try {
332
performTask(taskId);
333
334
if (log.isTraceEnabled()) {
335
log.trace("Task execution details for: " + taskId);
336
}
337
338
log.info("Task completed successfully: " + taskId);
339
340
} catch (Exception e) {
341
log.error("Task execution failed: " + taskId, e);
342
343
if (log.isFatalEnabled()) {
344
log.fatal("Critical task failure: " + taskId);
345
}
346
}
347
}
348
}
349
350
// Generated field:
351
// private static final org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory.getLog(CommonsLoggingService.class);
352
```
353
354
### @JBossLog Annotation
355
356
Generates JBoss Logging framework logger field for applications using JBoss infrastructure.
357
358
```java { .api }
359
/**
360
* Generates a private static final JBoss Logger field named 'log'.
361
* Uses org.jboss.logging.Logger.getLogger() for logger creation.
362
*/
363
@Target(ElementType.TYPE)
364
@interface JBossLog {
365
/**
366
* Custom logger category/name instead of using class name
367
* @return Logger category (default: uses annotated class name)
368
*/
369
String topic() default "";
370
}
371
```
372
373
**Usage Examples:**
374
375
```java
376
import lombok.extern.jbosslog.JBossLog;
377
import org.jboss.logging.Logger.Level;
378
379
@JBossLog
380
public class JBossLoggingService {
381
382
public void processJBossComponent(String componentId) {
383
log.infof("Processing JBoss component: %s", componentId);
384
385
try {
386
// JBoss logging supports format strings
387
log.debugf("Component %s configuration loaded", componentId);
388
389
performComponentProcessing(componentId);
390
391
log.infof("JBoss component %s processed successfully", componentId);
392
393
} catch (Exception e) {
394
// JBoss logging with exception
395
log.errorf(e, "Failed to process JBoss component: %s", componentId);
396
397
// Internationalization support
398
log.error(Messages.COMPONENT_PROCESSING_FAILED, componentId);
399
}
400
}
401
402
public void logWithLevel(String message, Level level) {
403
log.logf(level, "Custom level logging: %s", message);
404
}
405
}
406
407
// Generated field:
408
// private static final org.jboss.logging.Logger log = org.jboss.logging.Logger.getLogger(JBossLoggingService.class);
409
```
410
411
### @Flogger Annotation
412
413
Generates Google Flogger logger field for applications using Google's fluent logging API.
414
415
```java { .api }
416
/**
417
* Generates a private static final Flogger Logger field named 'logger'.
418
* Uses com.google.common.flogger.FluentLogger.forEnclosingClass() for logger creation.
419
*/
420
@Target(ElementType.TYPE)
421
@interface Flogger {
422
/**
423
* Custom logger category/name instead of using class name
424
* @return Logger category (default: uses annotated class name)
425
*/
426
String topic() default "";
427
}
428
```
429
430
**Usage Examples:**
431
432
```java
433
import lombok.extern.flogger.Flogger;
434
import java.util.concurrent.TimeUnit;
435
436
@Flogger
437
public class FloggerService {
438
439
public void processWithFlogger(String itemId, Map<String, Object> metadata) {
440
// Flogger's fluent API
441
logger.atInfo().log("Processing item: %s", itemId);
442
443
// Conditional logging with lazy evaluation
444
logger.atDebug()
445
.every(100) // Log every 100th occurrence
446
.log("Debug info for item: %s", itemId);
447
448
try {
449
long startTime = System.nanoTime();
450
451
processItem(itemId, metadata);
452
453
// Performance logging with time measurement
454
logger.atInfo()
455
.withCause(null)
456
.atMostEvery(1, TimeUnit.SECONDS)
457
.log("Item processed in %d ms: %s",
458
TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime),
459
itemId);
460
461
} catch (Exception e) {
462
// Rich exception logging
463
logger.atSevere()
464
.withCause(e)
465
.withStackTrace(StackSize.FULL)
466
.log("Failed to process item: %s", itemId);
467
}
468
}
469
470
public void demonstrateRateLimiting() {
471
for (int i = 0; i < 1000; i++) {
472
// Rate-limited logging
473
logger.atWarning()
474
.atMostEvery(5, TimeUnit.SECONDS)
475
.log("Rate limited warning: %d", i);
476
}
477
}
478
}
479
480
// Generated field:
481
// private static final com.google.common.flogger.FluentLogger logger = com.google.common.flogger.FluentLogger.forEnclosingClass();
482
```
483
484
### @CustomLog Annotation
485
486
Generates custom logger field using user-defined logging implementation configured via lombok.config.
487
488
```java { .api }
489
/**
490
* Generates a logger field using custom logging configuration.
491
* Logging implementation is defined in lombok.config file.
492
*/
493
@Target(ElementType.TYPE)
494
@interface CustomLog {
495
/**
496
* Custom logger category/name instead of using class name
497
* @return Logger category (default: uses annotated class name)
498
*/
499
String topic() default "";
500
}
501
```
502
503
**Configuration and Usage:**
504
505
```properties
506
# lombok.config file
507
lombok.log.custom.declaration = my.logging.Logger LOGGER = my.logging.LoggerFactory.getLogger(TYPE)
508
lombok.log.fieldName = LOGGER
509
```
510
511
```java
512
import lombok.CustomLog;
513
514
@CustomLog
515
public class CustomLoggingService {
516
517
public void useCustomLogger(String operation) {
518
// Uses the custom logger defined in lombok.config
519
LOGGER.info("Performing custom operation: " + operation);
520
521
try {
522
performOperation(operation);
523
LOGGER.debug("Custom operation completed successfully");
524
525
} catch (Exception e) {
526
LOGGER.error("Custom operation failed", e);
527
}
528
}
529
}
530
531
// Generated field based on lombok.config:
532
// private static final my.logging.Logger LOGGER = my.logging.LoggerFactory.getLogger(CustomLoggingService.class);
533
```
534
535
### Framework Comparison and Selection
536
537
```java
538
// SLF4J - Most popular, provides abstraction
539
@Slf4j
540
public class Slf4jExample {
541
public void method() {
542
log.info("Message with {} parameter", param); // Parameterized messages
543
}
544
}
545
546
// Log4j2 - High performance, rich features
547
@Log4j2
548
public class Log4j2Example {
549
public void method() {
550
log.info("Message: {}", () -> expensiveOperation()); // Lazy evaluation
551
}
552
}
553
554
// Java Util Logging - Built into JDK
555
@Log
556
public class JulExample {
557
public void method() {
558
log.info("Standard JUL logging");
559
}
560
}
561
562
// Commons Logging - Legacy support
563
@CommonsLog
564
public class CommonsExample {
565
public void method() {
566
log.info("Commons logging for legacy systems");
567
}
568
}
569
570
// Flogger - Google's fluent API
571
@Flogger
572
public class FloggerExample {
573
public void method() {
574
logger.atInfo().every(100).log("Rate-limited message");
575
}
576
}
577
```
578
579
## Type Definitions
580
581
```java { .api }
582
/**
583
* All logging annotations share the same structure
584
*/
585
@interface LoggingAnnotation {
586
/**
587
* Custom logger category/topic name
588
* @return Logger category (default: class name)
589
*/
590
String topic() default "";
591
}
592
```