Mastering Log Practices: From Basics to Advanced Guidelines
This article explains what logging is, why it matters, when to log, the principles and level conventions, common log formats, and a comprehensive set of mandatory and recommended best‑practice rules for writing robust, secure, and maintainable backend logs.
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.
1. What is logging?
According to Wikipedia, a log is one or more files automatically created and maintained by a server that contain a list of its activities. A well‑structured log file provides precise system records that help developers locate the details and root cause of errors. In Java applications, logs record important logical parameters and exceptions, often collected by systems such as ELK or DTM for monitoring.
2. Why log?
Logs provide accurate system records that facilitate root‑cause analysis. Their main purposes are:
Debugging: record variables or code paths to trace program flow and diagnose logic problems.
Problem localization: quickly pinpoint issues when exceptions or failures occur, especially in production where direct debugging is impossible.
Monitoring & audit: formatted logs can be fed into monitoring systems (e.g., AntMonitor) to track system health and user behavior for business dashboards.
3. When to log?
Key scenarios for logging include:
Code initialization or entry points : log startup parameters and service initialization status (INFO level).
Language‑thrown exceptions : log high‑severity exceptions with appropriate WARN or ERROR levels.
Business flow deviations : log mismatches between expected and actual outcomes, such as invalid external parameters or out‑of‑range return codes.
Core business actions : log critical operations performed by primary system roles (INFO level).
Third‑party remote calls : log request and response parameters for micro‑service interactions to aid troubleshooting.
Basic Standards
Logging Principles
Isolation: logging must not affect normal system operation.
Security: logging must not introduce logical bugs or vulnerabilities.
Data safety: never output confidential or sensitive information (e.g., phone numbers, ID cards, tokens).
Monitorability: logs should be consumable by monitoring and analysis tools.
Traceability: log messages must be meaningful and readable for daily troubleshooting.
Log Level Guidelines
Four common log levels are used in daily development:
DEBUG
Outputs detailed debugging information, suitable for development and testing. Include parameters, return values, and other fine‑grained data to aid analysis of issues.
INFO
Records key system information during normal operation, such as initialization parameters, business state changes, and core processing steps. After release, set the environment to INFO and verify that logs provide sufficient context for issue investigation.
WARN
Outputs anticipated, planned‑for warnings, such as null input parameters or conditions that do not meet method requirements. Include enough detail for later analysis.
ERROR
Used for unpredictable problems like exceptions (network failures, database connection loss, OOM, etc.). When logging ERROR, include method arguments, object states, and the full exception stack trace.
Choosing WARN vs. ERROR
Determine the severity based on impact: WARN for recoverable or expected issues, ERROR for critical failures that require immediate attention.
Common Log Formats
Summary Log
A formatted standard log used for monitoring configuration and offline analysis. Typical fields include call time, traceId/rpcId, thread name, interface name, method name, latency, success flag, error code, and system context information.
<code>2022-12-12 06:05:05,129 [0b26053315407142451016402xxxxx 0.3 - /// -] INFO [SofaBizProcessor-4-thread-333] - [(interfaceName,methodName,1ms,Y,SUCCESS)(appName,ip,timestamp,Y)]</code>Detailed Log
Supplementary to the summary log, it adds request and response parameters for deeper troubleshooting.
<code>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)(result)]</code>Business Execution Log
Logs generated during business logic execution without a fixed format. Use them sparingly and ensure each log adds clear business context, includes relevant parameters, and can be distinguished from other logs.
Suggested format:
[scene][meaning] key‑value pairs <code>[scene_bind_feature][feature_exists]功能已经存在[tagSource='MIF_TAG',tagValue='123']</code>Log Best Practices
Mandatory Rules
Logging code must never fail or block the business flow.
Do not use
System.out.println()for logging.
Avoid calling logging framework APIs (Log4j, Logback) directly; use façade APIs such as SLF4J or JCL.
Declare logger objects as
private static final.
Guard trace/debug/info logs with level‑check guards (e.g.,
if (logger.isDebugEnabled())).
Never use
e.printStackTrace(); log the exception via the logging framework.
Always log the full exception object, not just its message.
Avoid serializing objects to JSON inside log statements; prefer
toString()or a concise builder.
Do not log meaningless messages without business context or trace IDs.
Avoid INFO‑level logs inside tight loops.
Prevent duplicate logging of the same event at multiple layers.
Never output sensitive information.
Keep each log line under 200 KB.
Recommended Practices
Prefer English in log messages to avoid encoding issues.
Record method entry and exit logs for important methods.
Log the first line of each conditional branch (if/else/switch) to trace execution paths.
Log only necessary parameters rather than dumping entire objects, unless the full context is required.
Alipay Experience Technology
Exploring ultimate user experience and best engineering practices
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.