Best Practices for Writing Application Logs and Understanding Log Levels
This article explains why logging is essential for software maintenance, outlines the purposes, readability, performance, disk‑space and timeliness considerations, describes Log4j components and log‑level hierarchy, and provides concrete code examples for TRACE, DEBUG, INFO, WARN and ERROR logging.
Writing logs in a program is crucial for reducing maintenance effort, yet developers often neglect it due to time pressure.
Developers should cultivate good logging habits from the start and allocate sufficient time for it.
1.1 Purpose of Logs
Audit logs for user actions, sometimes required by regulators.
Quickly locate the root cause of problems.
Trace program execution flow.
Track data changes.
Collect statistics and performance data.
Gather runtime environment information.
After a program goes live, logs help determine what happened, what the user did, environmental impact, data changes, and whether the issue repeats, enabling developers to reproduce and fix the problem.
1.2 Requirements for Writing Logs
1.2.1 Readability
Logs should be clear to both the author and other developers; avoid cluttering with decorative symbols like ++++++++++ , ========== , ---------- . Use English to prevent garbled characters.
1.2.2 Performance
Logging consumes I/O resources; limit log output, especially inside large loops, and check log level (e.g., isDebugEnabled() ) before logging.
1.2.3 Disk Space
Log files can fill disk space; use rotating logs and clean old files. Large log files (GBs) make searching for useful information difficult.
1.2.4 Timeliness
Retain logs for a reasonable period to allow retrospective analysis.
1.2.5 Log Levels
Production environments usually log at INFO level or higher; ensure sufficient information is still available.
1.2.6 Log Content
Include business‑related descriptions and avoid sensitive data such as usernames or passwords; keep encoding consistent, preferably English.
1.2.7 Log Format
A typical log entry contains date, time, level, code location, message, and error code.
2 Log Levels and Their Meaning
Log4j, an Apache open‑source logging framework, allows configuring output destinations, formats, and levels without code changes.
2.1 Log4j Components
2.1.1 Logger
Controls which logging statements are enabled and applies level filtering.
2.1.2 Appenders
Specify where logs are written (console, file, GUI, etc.).
2.1.3 Layout
Define the visual format of log messages.
2.2 Log Levels
Log4j defines six levels: TRACE , DEBUG , INFO , WARN , ERROR , and FATAL . Only messages with a level equal to or higher than the configured threshold are output.
2.2.1 TRACE
Very fine‑grained informational events, usually function call tracing; rarely used.
2.2.2 DEBUG
Fine‑grained debugging information useful during development.
2.2.3 INFO
Highlights important runtime events; suitable for production but should not be overused.
2.2.4 WARN
Indicates potential issues that do not stop execution, such as default parameter usage.
2.2.5 ERROR
Reports errors that do not halt the system; often includes error codes.
2.2.6 FATAL
Serious errors causing application termination; requires a restart.
The level hierarchy is ALL < TRACE < DEBUG < INFO < WARN < ERROR < FATAL < OFF . Commonly only DEBUG , INFO , WARN , and ERROR are used.
3 Log Formatting Examples
Below are practical examples of log macros for different levels.
3.1 TRACE Examples
DRV_LOG_TRACE("Connect Execute start");
DRV_LOG_TRACE("Connect Execute finish");
DRV_LOG_TRACE("DisConnect func");
DRV_LOG_TRACE("Execute DisConnect function succeed.");
DRV_LOG_TRACE("Enter UploadEvent Func");
DRV_LOG_TRACE("extInfo = %s", Extension);
DRV_LOG_TRACE("Send a Msg ");
DRV_LOG_TRACE("- Connect Execute start");
DRV_LOG_TRACE("- Connect Execute finish");
DRV_LOG_TRACE("- Enter GetAlarmEventPro func");
DRV_LOG_TRACE("- Receive an info");
DRV_LOG_TRACE("- End Get AlarmEventPro Func");
DRV_LOG_TRACE("- DisConnect func");
DRV_LOG_TRACE("- Execute DisConnect function succeed.");
DRV_LOG_TRACE("- Enter UploadEvent Func");
DRV_LOG_TRACE("- Leave UploadEvent Func");
DRV_LOG_TRACE("- ============电网报警触发");
DRV_LOG_TRACE("- ============开始发送电流电压值");
DRV_LOG_TRACE("- ============间隔超过分钟再次发送电流电压值");3.2 INFO Examples
DRV_LOG_INFO("- UpdataEvent nchal= %d,EventID = %d.", iChannelNo, nEventType);
DRV_LOG_INFO("- do not support doControl");
DRV_LOG_INFO("- channelId = %s, nStatusType = %d", channelId.c_str(), nStatusType);3.3 DEBUG Examples
DRV_LOG_DEBUG("- 输出报警情况:电网编号:%d,报警数量:%d,报警内容:%s.", datas.data1.chn, datas.data1.alarm_num, datas.data1.alarms);
... (additional DEBUG examples omitted for brevity) ...
DRV_LOG_DEBUG("- nChan = %d, szInfo = %s", nChan, szInfo);3.4 WARN Examples
DRV_LOG_WARN("[0x%08x] - invaild event msg,discard it", DRV_INVALID_ARG);
DRV_LOG_WARN("[0x%08x] - Can't find channel by channelId");
DRV_LOG_WARN("[0x%08x] - [DWSdk.errorcode=0x%08x]Connect device failed", DRV_CONNECT_FAILED, sdkErrCode);
... (additional WARN examples omitted) ...
DRV_LOG_WARN("[0x%08x] - SetEventCallBack should be called first", DRV_ERROR);3.5 ERROR Examples
DRV_LOG_ERROR("Init DwSDK filded;
", initRet);
DRV_LOG_ERROR("Connect device failed");
DRV_LOG_ERROR("Create thread failed");
DRV_LOG_ERROR("dw_start_receive failed");
DRV_LOG_ERROR("Communicate failed, socket recv error");
DRV_LOG_ERROR("other error
", iGetResult);
DRV_LOG_ERROR("SetEventCallBack should be called first");
... (additional ERROR examples omitted) ...
DRV_LOG_ERROR("[0x%08x] - [DWSdk.errorcode=0x%08x]Init DwSDK filded", DRV_INIT_FAILED, initRet);
DRV_LOG_ERROR("- [HPR.errorcode=0x%08x]Create thread failed", HPR_GetLastError());The format specifier 0x%08x prints an integer in hexadecimal with a leading 0x and pads to eight digits, e.g., printf("0x%08x", 0x1234); outputs 0x00001234 .
Architecture Digest
Focusing on Java backend development, covering application architecture from top-tier internet companies (high availability, high performance, high stability), big data, machine learning, Java architecture, and other popular fields.
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.