Mastering Log Practices: Essential Guidelines for Reliable Java Applications

This article explains what logs are, why they are crucial for debugging, monitoring and auditing, when to record them, the fundamental principles and level conventions, and provides concrete best‑practice recommendations and code examples to help Java developers implement robust, secure, and efficient logging.

Alibaba Cloud Developer
Alibaba Cloud Developer
Alibaba Cloud Developer
Mastering Log Practices: Essential Guidelines for Reliable Java Applications

1. Overview

Logging is an art; log information is one of the main tools developers use to troubleshoot production issues, yet many developers overlook proper logging standards. A good log acts like insurance—unused during normal operation but invaluable when problems arise.

1.1 What is a log?

According to Wikipedia, a log is one or more files automatically created and maintained by a server that contain a list of its performed activities.

1.2 Why record logs?

Well‑crafted logs provide precise system records that help locate error details and root causes. In Java applications, logs capture important business parameters and exceptions, and together with log‑collection systems (ELK, DTM) they form a monitoring framework.

Debugging: Record variables or logic flow to trace program execution.

Problem localization: Quickly pinpoint issues when exceptions occur, especially in production where direct debugging is impossible.

Monitoring & audit: Formatted logs feed monitoring tools (e.g., AntMonitor) to create multi‑dimensional views of system health and user behavior.

1.3 When to record logs?

During initialization or entry points: Log startup parameters and service status.

When the language signals an exception: Use WARN or ERROR levels appropriately.

When business flow deviates from expectations: Log abnormal parameters, error codes, etc.

Key actions in core business logic: Record INFO‑level logs for critical operations.

Third‑party remote calls: Log request and response parameters for traceability.

2. Basic Standards

2.1 Logging Principles

Isolation: Logging must not affect normal system operation.

Security: Logging code must not introduce vulnerabilities.

Data safety: Never output confidential information (e.g., personal contacts, ID numbers, tokens).

Monitorability: Logs should be consumable by monitoring and analysis tools.

Traceability: Log messages must be meaningful and readable for troubleshooting.

2.2 Log Level Specification

Four common levels are used in daily development, each suited to different scenarios:

DEBUG: Detailed debugging information; used during development and testing.

INFO: Key system information such as initialization parameters, state changes, and core business actions.

WARN: Predictable, planned warnings (e.g., null arguments, invalid parameters).

ERROR: Unpredictable errors or exceptions that significantly impact the system.

2.3 Common Log Formats

Summary Log: A formatted log for monitoring and offline analysis, typically containing:

Timestamp

Trace/ RPC IDs

Thread name

Interface and method names

Execution duration

Success flag (Y/N)

Error code

System context (caller name, IP, timestamp, load test flag)

2022-12-12 06:05:05,129 [0b26053315407142451016402xxxxx 0.3 - /// - ] INFO [SofaBizProcessor-4-thread-333] - [(interfaceName,methodName,1ms,Y,SUCCESS)(appName,ip,timestamp,Y)]

Detailed Log: Supplements the summary log with business parameters for deeper troubleshooting.

2022-12-12 06:05:05,129 [0b26053315407142451016402xxxxx 0.3 - /// - ] INFO [SofaBizProcessor-4-thread-333] - [(interfaceName,methodName,1ms,Y,SUCCESS)(appName,ip,timestamp,Y)(param1,param2)(xxxx)]

3. Logging Best Practices

3.1 Mandatory Rules

Logging code must never fail and block the business flow.

Avoid System.out.println(); use a proper logging framework.

Do not call Log4j/Logback APIs directly; use a façade like SLF4J or JCL.

Declare logger objects as private static final.

Guard TRACE/DEBUG/INFO logs with level‑check conditions to avoid unnecessary string concatenation.

Never use e.printStackTrace(); log the exception with the logging API.

Always include the full exception object when logging errors.

Avoid converting objects to JSON strings directly in logs; use toString() or a safe builder.

Do not log meaningless messages without business context or trace IDs.

Do not log INFO messages inside tight loops.

Avoid duplicate log entries for the same event.

Never expose sensitive data in logs.

Keep a single log line under 200 KB.

3.2 Recommendations

Prefer English in log messages to avoid encoding issues.

Record method entry and exit logs for important methods.

In conditional branches (if/else, switch), log the first line of each branch.

Log only necessary parameters, not entire objects, unless the full context is required.

By following these guidelines, developers can create reliable, secure, and maintainable logging that greatly simplifies troubleshooting and monitoring of Java backend services.

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.

BackendJavamonitoringlogginglog levels
Alibaba Cloud Developer
Written by

Alibaba Cloud Developer

Alibaba's official tech channel, featuring all of its technology innovations.

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.