15 Essential Logging Practices Every Java Backend Engineer Should Follow

Effective logging is crucial for debugging and accountability; this guide presents fifteen practical recommendations—from selecting appropriate log levels and formatting to using SLF4J, asynchronous output, and avoiding common pitfalls—designed to help Java developers write clear, performant, and maintainable logs.

Java Backend Technology
Java Backend Technology
Java Backend Technology
15 Essential Logging Practices Every Java Backend Engineer Should Follow

1. Choose appropriate log level

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

error : serious errors that affect normal business and require operational monitoring.

warn : warnings that have little impact on business but need developer attention.

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

debug : runtime data for debugging critical logic.

trace : most detailed information, usually written only to log files.

2. Log method input and output parameters

Print only the logs that help quickly locate problems. Effective logs are a powerful tool for accountability.

Typical example:

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 suitable log format

An ideal log format should include at least the current timestamp (usually millisecond precision), log level, thread name, etc. In Logback you can configure it as follows:

<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 each branch of conditional statements

When encountering if...else... or switch, print a log at the first line of each branch so you can determine which path was taken during troubleshooting.

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

5. Guard low‑level logs with level checks

For trace/debug logs you must check whether the level is enabled before constructing the message.

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

If the configured level is warn, the above debug statement will not be printed, but the string concatenation (and possible toString() calls) would still be executed, wasting resources.

6. Use SLF4J API instead of direct Log4j/Logback APIs

SLF4J is a façade that unifies logging across frameworks, making it easy to switch the underlying implementation without code changes.

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

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

7. Use parameter placeholders {} instead of string concatenation

Anti‑example (performance loss):

logger.info("Processing trade with id: " + id + " and symbol: " + symbol);

Correct usage:

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

8. Prefer asynchronous logging

Logs are eventually written to files or other streams, which have I/O performance requirements. Asynchronous logging can significantly improve I/O performance.

Unless there is a special requirement, use asynchronous logging. In Logback you can configure it simply with AsyncAppender.

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

9. Avoid e.printStackTrace()

Anti‑example:

try{
    // business code
} catch(Exception e){
    e.printStackTrace();
}

Correct example:

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

10. Log full exception information

Anti‑example 1 (no stack trace):

LOG.error('your program has an exception');

Anti‑example 2 (only message):

LOG.error('your program has an exception', e.getMessage());

Correct example (log the exception object):

LOG.error('your program has an exception', e);

11. Do not enable debug in production

Enabling debug in production can generate massive amounts of log data, quickly filling disk space and affecting system stability.

12. Do not log and rethrow the same exception

Logging the exception and then rethrowing it causes the stack trace to be printed twice, confusing the logs.

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

13. Avoid duplicate logs

Redundant logs waste disk space. If a log line already conveys the information, do not repeat it.

For Log4j, set additivity=false in log4j.xml to prevent duplicate logging.

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

14. Separate log files

Separate different types of logs (e.g., access.log, error.log) or logs per business module to simplify troubleshooting and data analysis.

15. Log more comprehensively for core modules

For complex or critical code paths, add detailed comments and richer logs to make troubleshooting easier.

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.

performancelogginglogbackslf4j
Java Backend Technology
Written by

Java Backend Technology

Focus on Java-related technologies: SSM, Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading. Occasionally cover DevOps tools like Jenkins, Nexus, Docker, and ELK. Also share technical insights from time to time, committed to Java full-stack development!

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.