15 Essential Logging Practices Every Java Developer Should Follow

This article presents fifteen practical guidelines for effective Java logging, covering log levels, parameter tracing, formatting, conditional logging, performance‑friendly APIs, asynchronous output, proper exception handling, and log file organization to help developers quickly locate issues and maintain clean, efficient logs.

Su San Talks Tech
Su San Talks Tech
Su San Talks Tech
15 Essential Logging Practices Every Java Developer Should Follow

Introduction

Hello, I am Programmer Tianluo. Logs are a powerful tool for quickly locating problems, as well as for shifting blame and responsibility. Good logging is essential, so let’s discuss fifteen useful logging tips.

1. Choose the appropriate log level

Common log levels are error, warn, info, debug, and trace. In daily development, select the proper level and avoid overusing info.

error : serious errors affecting normal business, requires operational monitoring.

warn : warnings with minor impact, needs developer attention.

info : records key information for troubleshooting, such as timestamps and parameters.

debug : runtime data in critical logic for debugging.

trace : most detailed information, usually logged to files only.

2. Log method input and output parameters

Print only effective logs that help locate problems quickly, such as method entry parameters and exit return values (e.g., userId, bizSeq).

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. Choose a suitable log format

An ideal log format includes timestamp (millisecond precision), log level, thread name, etc. Example Logback configuration:

<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

When encountering if/else or switch, log at the first line of each branch to identify which path was taken.

if(user.isVip()){
    log.info("User is VIP, Id:{}, start VIP logic", user.getUserId());
    // VIP logic
} else {
    log.info("User is non‑VIP, Id:{}, start non‑VIP logic", user.getUserId());
    // non‑VIP logic
}

5. Guard low‑level logs with level checks

For trace/debug logs, check if the level is enabled before constructing the message.

User user = new User(666L, "公众号", "捡田螺的小男孩");
if(log.isDebugEnabled()){
    log.debug("userId is: {}", user.getId());
}

6. Use SLF4J API instead of Log4j/Logback directly

SLF4J provides a façade that unifies logging across frameworks and allows easy replacement of the underlying implementation.

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

private static final Logger logger = LoggerFactory.getLogger(TianLuoBoy.class);

7. Use placeholder {} instead of string concatenation

Using {} placeholders avoids the performance cost of string concatenation.

logger.info("Processing trade with id: {} and symbol: {}", id, symbol);

8. Use asynchronous logging

Asynchronous logging improves I/O performance; configure Logback with AsyncAppender.

<appender name="FILE_ASYNC" class="ch.qos.logback.classic.AsyncAppender">
    <appender-ref ref="ASYNC"/>
</appender>

9. Do not use e.printStackTrace()

Instead, log the exception with the logger.

try{
    // business logic
} catch(Exception e){
    log.error("Your program encountered an exception", e);
}

10. Log the full exception, not just the message

Include the exception object to capture the complete stack trace.

try{
    // business logic
} catch(Exception e){
    LOG.error("Your program has an exception", e);
}

11. Do not enable debug in production

Debug logs can quickly fill disk space and affect system stability.

12. Avoid logging and then rethrowing the same exception

Logging the exception and rethrowing it leads to duplicate stack traces.

log.error("IO exception", e);
throw new MyException(e);

13. Avoid duplicate logs

Do not log the same information multiple times; set additivity=false in log4j.xml if using Log4j.

<logger name="com.taobao.dubbo.config" additivity="false">

14. Separate log files

Separate different log types (e.g., access.log, error.log) or module‑specific logs for easier analysis.

15. Log more details for core modules

For complex or critical code, add detailed comments and richer logs to facilitate troubleshooting.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

DebuggingJavabest practicesslf4j
Su San Talks Tech
Written by

Su San Talks Tech

Su San, former staff at several leading tech companies, is a top creator on Juejin and a premium creator on CSDN, and runs the free coding practice site www.susan.net.cn.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.