compare Framework Comparison
Logging in Java layers Log Levels & Configuration
Applications settings Best Practices
Best Practices and Framework Comparison
storage File Logging & Maintenance
Major Advantages of Logging over [Link]
layers Log Levels pattern Pattern Control
Control verbosity with TRACE, DEBUG, INFO, WARN, ERROR Customize log message format with timestamps, thread info,
levels and more
tune Flexible Configuration Logging vs [Link]
Configure output format, destinations, and behavior without
Logging Framework [Link]
code changes
✓ Configurable log levels ✗ Always prints
storage Multiple Outputs
✓ Performance optimized ✗ No optimization
Log to console, files, databases, or external systems
simultaneously
✓ Multiple output ✗ Console only
destinations
✓ Contextual information ✗ Manual formatting
Logging Frameworks Comparison
layers SLF4J history Log4j / Log4j2 speed Logback
check_circle Logging abstraction layer check_circle Legacy framework (Log4j) / Modern check_circle Modern, faster logging framework
replacement (Log4j2)
check_circle Write code independently of specific check_circle More flexible than Log4j
implementation check_circle Log4j2 addresses performance and
security concerns check_circle Native implementation of SLF4J API
check_circle Switch implementations without
check_circle Auto-reload configuration without
changing code check_circle Widely used in enterprise applications
restart
check_circle Parameterized logging for performance check_circle Plugin architecture for extensibility
When to use
When to use When to use SLF4J + Logback is the common and
Use as facade with Logback or Log4j2 Use Log4j2 if you prefer it or have powerful combination for modern Java
for maximum flexibility legacy systems using Log4j apps
Framework Diagram
[Link]
When to Use Which Framework
RECOMMENDED
layers history
SLF4J + Logback Log4j 2
star Common & powerful combination for modern Java security Addresses security concerns of original Log4j
apps
extension Plugin architecture for extensibility
speed Native implementation of SLF4J API
auto_fix_high Asynchronous logging for better performance
settings Auto-reload configuration without restart
Best for: Best for:
New projects, Spring Boot applications, performance-critical Legacy systems, projects with existing Log4j dependencies,
systems enterprise environments
Framework Architecture Diagram link
Visual representation of how SLF4J acts as a facade layer over various logging implementations [Link]/[Link]
Creating a Logger Class
code Traditional Approach code Lombok @Slf4j Annotation
import [Link]; import import [Link].slf4j.Slf4j; import
[Link]; public class [Link]; @Slf4j
UserService { // Create logger instance // Creates logger field automatically @Service
private static final Logger logger = public class PaymentService { public Payment
[Link]([Link]); processPayment(PaymentRequest request) { //
public User getUserById(String id) { Logger field is automatically created by Lombok
[Link]("Fetching user with ID: {}", [Link]("Processing payment: {}",
id); // Business logic return user; } } [Link]()); try { // Payment processing
logic [Link]("Payment validation
successful"); return payment; } catch (Exception
e) { [Link]("Payment processing failed", e);
throw new PaymentException(e); } } }
info SLF4J Architecture
layers SLF4J acts as a facade layer over various logging
implementations
SLF4J Wrapper Implementation
swap_horiz LoggerFactory binds to the underlying logging framework
at runtime Application Code SLF4J Implementation
Logger logger = API Logback/Log4j2/etc.
settings Allows switching implementations without changing [Link](...) arrow_forward Logger arrow_forward
application code Interface
ERROR lightbulb When to Use Each Level
error Critical errors that require immediate attention
error ERROR: When an exception occurs or critical failure
warning WARN: For warnings, API taking too long, or deprecated usage
WARN
warning Potentially harmful situations or warnings
info INFO: Written in PROD, important application events
bug_report DEBUG: Used in Non-PROD, helpful for troubleshooting
timeline TRACE: Very detailed information, method entry/exit points
INFO
info Informational messages highlighting application progress // Example of using different log levels try {
[Link]("Processing payment for user: {}",
userId); if (responseTime > threshold) {
DEBUG [Link]("API response time exceeded
bug_report Detailed information for debugging purposes threshold: {}ms", responseTime); }
[Link]("Payment validation successful for
amount: {}", amount); [Link]("Entering
payment processing method with parameters: {}",
TRACE
timeline Most detailed information, typically for development
params); } catch (Exception e) {
[Link]("Payment processing failed for
user: {}", userId, e); }
sort Log Level Hierarchy
E W I D T
arrow_forward arrow_forward arrow_forward arrow_forward
ERROR WARN INFO DEBUG TRACE
When set to a specific level, logs of that level and higher will be
displayed
Log Levels
Configuring Log Levels
settings Root Level Logging code XML Configuration ([Link])
Applies to all jars/code in the project
<!-- More flexible configuration -->
<configuration> <appender name="STDOUT"
class="[Link]">
description Property File code XML Configuration
<encoder> <pattern>%d{HH:mm:[Link]}
Simple configuration for More flexible and powerful
basic needs [%thread] %-5level %logger{36} -
%msg%n</pattern> </encoder> </appender> <!--
Root logger --> <root level="INFO">
<appender-ref ref="STDOUT" /> </root> <!--
Package-specific logger --> <logger
# [Link] name="[Link]"
[Link]=INFO level="TRACE" /> <!-- Framework logger -->
[Link]=TRACE <logger name="[Link]"
level="DEBUG" /> </configuration>
auto_awesome Custom patterns and formatters
storage Multiple appenders (console, file, etc.)
Log Level Hierarchy
tune Conditional logging based on environment
ROOT Package Class autorenew Auto-reload configuration without restart
INFO arrow_forward DEBUG arrow_forward TRACE
Logback Configuration
code [Link] Configuration ROOT Package
settings Logger folder Logger
Default for the Specific to a
<configuration> <!-- Appender for console output -->
application package
<appender name="STDOUT"
Applies to all Overrides ROOT
class="[Link]"> <encoder> packages unless level for that
<pattern>%d{HH:mm:[Link]} [%thread] %-5level %logger{36} - overridden package
%msg%n</pattern> </encoder> </appender> <!-- File appender
with rolling policy --> <appender name="FILE"
class="[Link]"> Logger Hierarchy Example
<file>logs/[Link]</file> <rollingPolicy
class="[Link]"> ROOT: INFO
<fileNamePattern>logs/application.%d{yyyy-MM-
dd}.log</fileNamePattern> <maxHistory>7</maxHistory> arrow_downward
</rollingPolicy> <encoder> <pattern>%d{yyyy-MM-dd
HH:mm:[Link]} [%thread] %-5level %logger{36} - [Link]:
%msg%n</pattern> </encoder> </appender> <!-- ROOT logger TRACE
(default for the application) --> <root level="INFO">
<appender-ref ref="STDOUT" /> <appender-ref ref="FILE" /> arrow_downward
</root> <!-- Package-specific logger --> <logger
name="[Link]" level="TRACE" /> <!-- [Link]:
Framework logger --> <logger DEBUG
name="[Link]" level="DEBUG" />
</configuration>
autorenew Auto-reload
Configuration changes without restart
layers Inheritance
Child loggers inherit from parent
extension Extensibility
Custom appenders and filters
Log Patterns and Conversion Patterns
format_align_left Conversion Patterns
Pattern Meaning Example Output
%d Date/time of the log event 2025-07-31 23:45:15,123
%d{HH:mm:ss} Custom time format 23:45:15
%thread Name of the thread main, http-nio-8080-exec-1
%level Log level INFO, DEBUG, ERROR
%-5level Log level (left-aligned, 5 characters) INFO , DEBUG, ERROR
%logger Logger name (fully qualified class name) [Link]
%logger{36} Logger name shortened to 36 characters [Link]
%msg The actual log message User logged in
%n New line (line break) -
%M Method name where log was called getUserById
%class Fully qualified class name [Link]
%file Source file name [Link]
%line Line number in the source file 42
%X{key} Mapped Diagnostic Context (MDC) value userId=abc123
%highlight(...) Color highlighting for terminal logs INFO, ERROR in colored output
Environment-Specific Log Levels
settings_applications Configuration Strategy sync_alt Configuration Precedence
Keep XML as INFO and configure environment-specific levels in properties files
1 [Link] provides base configuration
2 [Link] overrides XML settings
developer_board Development precision_manufacturing Staging
Enable detailed logging for debugging Moderate logging for testing Environment-specific properties (e.g., application-
3
[Link])
[Link]=DEBUG [Link]=INFO
[Link]=TRACE [Link]=DEBUG
4 Command-line arguments take highest precedence
cloud Production bug_report Troubleshooting # Example of dynamic log level configuration
[Link]=INFO
Minimal logging for performance Temporary detailed logging
[Link]=INFO #
[Link]=WARN Override in environment-specific file #
[Link]=INFO [Link]=TRACE [Link]
[Link]=TRACE #
Command-line override (highest precedence) #
java -jar [Link] --
[Link]=DEBUG
autorenew No application restart required when changing log levels via
Actuator endpoints
security Secure production systems by restricting access to log level
configuration
File Logging and Basic Commands
description File Configuration code VI Editor Basics
Essential VI commands for viewing and editing log files
folder File path from [Link] using @ placeholder
settings Configure in [Link]
open_in_new Opening Files navigation Navigation
${LOG_PATH:-logs}/[Link] ${LOG_PATH:- G - Go to end of file
logs}/application.%d{yyyy-MM-dd}.log 7 gg - Go to beginning
vi logs/[Link] /pattern - Search forward
vim logs/[Link] ?pattern - Search backward
terminal Tail Command search Tail with Grep
Shows the last part of a file and Filter logs for specific patterns while
continuously displays new content monitoring visibility Viewing Modes exit_to_app Exiting VI
:q - Quit
tail -f logs/[Link] | less logs/[Link] :w - Save
tail -f logs/[Link] grep "ERROR" more logs/[Link] :wq - Save and quit
2025-07-31 14:23:45.123 INFO 2025-07-31 14:23:45.123 ERROR cat logs/[Link] :q! - Force quit without saving
[http-nio-8080-exec-1] [http-nio-8080-exec-1]
[Link] - [Link] - Payment
Processing payment... failed
refresh Rolling Behavior
Log files are rotated based on time and size to prevent them from growing indefinitely
# Daily log files with 7-day retention
# [Link] (current day)
# [Link] (yesterday)
# [Link] (2 days ago)
Log Rotation and Maintenance
autorenew Rolling Behavior & Version Control cloud Log Storage & Analysis
<rollingPolicy Kibana Integration
class="[Link]"> 1 Daily logs sent to Kibana with 3-
<fileNamePattern>logs/application.%d{yyyy-MM- month maintenance
dd}.log</fileNamePattern> <maxHistory>7</maxHistory>
<totalSizeCap>1GB</totalSizeCap> </rollingPolicy>
AWS S3 Storage
2 Long-term archival in S3 bucket for
compliance
today Daily Log Settings storage Local Storage
Automatic daily rotation with 7-day Limited disk space with 7-day
Log Analysis
retention on local machine retention
3 Centralized monitoring and alerting
in Kibana
check_circle Automatic rotation at midnight check_circle Fast access to recent logs
check_circle Compressed archived logs check_circle Automatic cleanup of old logs
Log Flow Architecture
computer analytics cloud
Applicationarrow_forward Kibana arrow_forward AWS S3
Local 3 Long-
Logs Months term
security Security compliance with log retention
policies
search Advanced search and visualization in
Kibana