Master Java Logging: Framework Choices, Best Practices, and Real-World Tips
This guide explains why System.out.println is unsuitable for production, compares Java logging frameworks such as Log4j2, Logback and SLF4J, shows how to integrate them with code and Lombok, and provides comprehensive best‑practice recommendations on log levels, formatting, volume control, rolling policies, asynchronous logging and log aggregation.
1. Choosing a Logging Framework
Many developers start with System.out.println, but it is synchronous, slow, and cannot control log level or output format. Professional Java logging frameworks such as Apache Log4j, Log4j 2, and Spring Boot’s default Logback solve these problems. SLF4J is not a concrete logger; it is a façade that lets you switch the underlying implementation without changing code.
2. Using a Logging Framework
Typical usage involves obtaining a Logger instance and calling methods like logger.info. The classic approach uses LoggerFactory.getLogger(MyClass.class):
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MyService {
private static final Logger logger = LoggerFactory.getLogger(MyService.class);
public void doSomething() {
logger.info("执行了一些操作");
}
}To avoid hard‑coding the class name, you can use this.getClass():
public class MyService {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
public void doSomething() {
logger.info("执行了一些操作");
}
}Lombok’s @Slf4j annotation generates a log field automatically, reducing boilerplate:
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class MyService {
public void doSomething() {
log.info("执行了一些操作");
}
}Logback, Log4j 2 and other frameworks are configured via XML files such as logback.xml or logback-spring.xml. These files define appenders, patterns, rolling policies, etc.
3. Logging Best Practices
3.1 Choose Appropriate Log Levels
TRACE : Very fine‑grained debugging information.
DEBUG : Internal state and variable values.
INFO : Key business events and system state.
WARN : Potential issues that do not stop execution.
ERROR : Errors that need attention.
FATAL : Critical failures that may halt the system.
Use DEBUG/INFO/WARN/ERROR in practice. Development environments should enable low‑level logs (DEBUG) for detailed troubleshooting, while production should limit output to INFO or WARN to reduce noise and overhead.
3.2 Record Log Information Correctly
Prefer parameterised logging to avoid string concatenation overhead and null‑pointer risks:
// Not recommended
logger.debug("用户ID:" + userId + " 登录成功。");
// Recommended
logger.debug("用户ID:{} 登录成功。", userId);When logging exceptions, include contextual data and the stack trace:
try {
// business logic
} catch (Exception e) {
logger.error("处理用户ID:{} 时发生异常:", userId, e);
}3.3 Control Log Volume
Avoid logging inside tight loops; batch logs or guard with level checks:
if (logger.isDebugEnabled()) {
logger.debug("复杂对象信息:{}", expensiveToComputeObject());
}Example of logging every 1000 records:
if (index % 1000 == 0) {
logger.info("已处理 {} 条记录", index);
}Alternatively, accumulate messages in a StringBuilder and log once after processing:
StringBuilder logBuilder = new StringBuilder("处理结果:");
for (Item item : items) {
try {
processItem(item);
logBuilder.append(String.format("成功[ID=%s], ", item.getId()));
} catch (Exception e) {
logBuilder.append(String.format("失败[ID=%s, 原因=%s], ", item.getId(), e.getMessage()));
}
}
logger.info(logBuilder.toString());3.4 Log at the Right Time and Content
Record logs at critical business points (login, order processing, payment). Log method entry/exit with important parameters and return values. Never log sensitive data such as passwords.
3.5 Log Management
Configure rolling policies to prevent log files from exhausting disk space.
Size‑based rolling (e.g., 10 MB):
<rollingPolicy class="ch.qos.logback.core.rolling.SizeBasedRollingPolicy">
<maxFileSize>10MB</maxFileSize>
</rollingPolicy>Time‑based rolling (daily):
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>logs/app-%d{yyyy-MM-dd}.log</fileNamePattern>
</rollingPolicy>Retain a limited history (e.g., 30 days):
<maxHistory>30</maxHistory>Compress old logs to save space:
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>logs/app-%d{yyyy-MM-dd}.log.gz</fileNamePattern>
</rollingPolicy>A simple shell script can clean logs older than 90 days:
# 每月清理一次超过 90 天的日志文件
find /var/log/myapp/ -type f -mtime +90 -exec rm {} \;3.6 Unified Log Format
Use a consistent pattern to make logs easy to parse and search. Example pattern:
%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%nJSON encoding (via Logstash encoder) can further standardise structure and include MDC fields such as requestId and userId.
<encoder class="net.logstash.logback.encoder.LoggingEventCompositeJsonEncoder"/>Example of adding MDC context in code:
MDC.put("requestId", "666");
MDC.put("userId", "yupi");
logger.info("用户请求处理完成");
MDC.clear();3.7 Asynchronous Logging
Configure Logback’s async appender to offload I/O from the main thread:
<appender name="ASYNC" class="ch.qos.logback.classic.AsyncAppender">
<queueSize>500</queueSize>
<discardingThreshold>0</discardingThreshold>
<neverBlock>true</neverBlock>
<appender-ref ref="CONSOLE"/>
<appender-ref ref="FILE"/>
</appender>3.8 Integrating Log Collection Systems
For large‑scale deployments, centralised solutions like the ELK stack (Elasticsearch, Logstash, Kibana) enable powerful search and analysis, but they add operational overhead; small teams may postpone adopting them.
Log is written for your future self and teammates, not just the machine.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
dbaplus Community
Enterprise-level professional community for Database, BigData, and AIOps. Daily original articles, weekly online tech talks, monthly offline salons, and quarterly XCOPS&DAMS conferences—delivered by industry experts.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
