Best Practices for Java Logging and Custom Logback Appender

This article explains Java logging fundamentals, the four standard log levels, practical best‑practice guidelines, and how to implement a custom Logback appender that injects a request ID for better traceability in distributed systems using ELK and Kafka.

Code Ape Tech Column
Code Ape Tech Column
Code Ape Tech Column
Best Practices for Java Logging and Custom Logback Appender

In Java, the common log levels are DEBUG, INFO, WARN, and ERROR; developers typically enable DEBUG in development and INFO in production, using popular frameworks such as Log4j or Logback.

The ultimate goal of logging is to enable rapid problem location and resolution, so the article presents several best‑practice recommendations for each level, including printing request/response data, method inputs and outputs, and contextual information for WARN and ERROR logs.

When applications run on multiple machines, locating logs becomes difficult. The article briefly describes the classic ELK architecture (Kafka → Logstash → Elasticsearch → Kibana) and stresses the importance of correlating logs across instances using a unified identifier such as a request ID.

To automatically add a request ID to every log entry, a custom Logback appender can be created. The steps are:

Extend AppenderBase and implement the start() method to initialize a Kafka producer.

Override the append() method, retrieve the original log message from the ILoggingEvent, prepend the request ID (usually stored in a ThreadLocal or TransmittableThreadLocal set by an HTTP filter), and forward the enriched message to Kafka.

This approach ensures that all logs contain a consistent request identifier, making it easy to filter and analyze logs for a specific transaction across a distributed environment.

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.

logbacklog4j
Code Ape Tech Column
Written by

Code Ape Tech Column

Former Ant Group P8 engineer, pure technologist, sharing full‑stack Java, job interview and career advice through a column. Site: java-family.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.