15 Best Practices for Effective Log Printing in Java Applications
This article presents fifteen practical guidelines for logging in Java, covering proper log levels, parameter logging, formatting, conditional logging, log level guards, SLF4J usage, placeholder syntax, asynchronous output, exception handling, production debug policies, avoiding duplicate logs, file separation, and detailed logging for core modules.
Logging is a crucial tool for quickly locating problems and managing accountability; this guide offers fifteen actionable recommendations for effective log printing.
1. Choose appropriate log levels – use error, warn, info, debug, and trace wisely, avoiding unnecessary info logs.
2. Log method entry and exit parameters – record key inputs (e.g., userId) and outputs to aid rapid issue identification.
public String testLogMethod(Document doc, Mode mode){
log.debug("method enter param:{}", userId);
String id = "666";
log.debug("method exit param:{}", id);
return id;
}3. Use a consistent log format – include timestamp, level, thread name, etc. Example Logback pattern:
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} %-5level [%thread][%logger{0}] %m%n</pattern>
</encoder>
</appender>4. Log at the start of each conditional branch – print a log in the first line of if/else or switch blocks to identify the executed path.
if(user.isVip()){
log.info("User is VIP, Id:{}, processing VIP logic", user.getUserId());
// VIP logic
} else {
log.info("User is non‑VIP, Id:{}, processing non‑VIP logic", user.getUserId());
// non‑VIP logic
}5. Guard low‑level logs with level checks – wrap trace/debug statements with if (log.isDebugEnabled()) to avoid unnecessary string concatenation.
if (log.isDebugEnabled()) {
log.debug("userId is: {}", user.getId());
}6. Prefer SLF4J API – use the SLF4J façade for flexibility and easy underlying framework replacement.
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
private static final Logger logger = LoggerFactory.getLogger(TianLuoBoy.class);7. Use placeholder {} instead of string concatenation – improves performance and readability.
logger.info("Processing trade with id: {} and symbol: {}", id, symbol);8. Employ asynchronous logging – configure Logback’s AsyncAppender to boost I/O performance.
<appender name="FILE_ASYNC" class="ch.qos.logback.classic.AsyncAppender">
<appender-ref ref="ASYNC"/>
</appender>9. Avoid e.printStackTrace() – it mixes stack traces with business logs and can exhaust memory.
try {
// business code
} catch (Exception e) {
log.error("An exception occurred", e);
}10. Log full exception information – pass the exception object to the logger rather than only its message.
11. Disable debug logging in production – excessive debug logs can fill disks and degrade system stability.
12. Do not log and then re‑throw the same exception – this results in duplicate stack traces.
13. Prevent duplicate log entries – consolidate messages and set additivity="false" in Log4j configuration when appropriate.
<logger name="com.taobao.dubbo.config" additivity="false">
...
</logger>14. Separate log files by type or module – e.g., distinct files for access logs and error logs to simplify analysis.
15. Provide detailed logs for core or complex modules – richer logging helps pinpoint failures in critical code paths.
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.
Full-Stack Internet Architecture
Introducing full-stack Internet architecture technologies centered on Java
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.
