Mastering Log Practices: Levels, Formats, and Performance Tips
This article explains why proper logging is essential for software maintenance, outlines the purposes of logs, details best‑practice requirements such as readability, performance impact, disk usage and timeliness, and provides a comprehensive guide to Log4j components, log levels, their hierarchy, and practical code examples for each level.
Introduction
Writing logs in a program is crucial but often overlooked; good logs greatly reduce maintenance effort.
Developers under time pressure may neglect logging, yet establishing solid logging habits early and allocating time for it is essential.
Roles of Logs
Logs serve several needs:
Audit user actions (sometimes required by regulators).
Quickly locate the root cause of problems.
Trace program execution flow.
Track data changes.
Support statistics and performance analysis.
Collect runtime environment data.
When an exception occurs, logs help determine what happened, what the user did, environmental factors, data changes, and whether the issue repeats, enabling developers to reproduce and fix the problem.
Requirements for Writing Logs
Because logging improves future efficiency, logs should follow standards:
Readability: Logs must be clear to both the author and other developers.
Avoid noisy symbols like "++++++++++" or "===========".
Separate logs into different files when appropriate and use English to prevent garbled characters.
Performance: Logging consumes I/O; limit log output, especially inside large loops, and check log level before constructing messages (e.g., if (logger.isDebugEnabled()) { ... }).
Disk Space: Use log rotation and periodic cleanup; excessive log size can fill disks and hinder troubleshooting.
Timeliness: Retain logs for a reasonable period to allow retrospective analysis.
Log Levels
In production environments, logs are usually kept at INFO or higher, ensuring sufficient information for decisions.
Common Log4j levels (from most to least severe): TRACE, DEBUG, INFO, WARN, ERROR, FATAL.
Log4j Components
Loggers: Control which logging statements are enabled and apply level filters.
Appenders: Define where logs are written (console, file, etc.).
Layouts: Format the appearance of log messages.
Log Level Definitions
TRACE: Very fine‑grained events, usually function entry/exit; rarely used.
DEBUG: Detailed information useful during development and debugging.
INFO: High‑level messages about normal operation; suitable for production but should not be overused.
WARN: Indicates potential issues that do not stop execution.
ERROR: Errors that affect functionality but allow the program to continue.
FATAL: Severe errors causing the application to abort.
Log Level Hierarchy
ALL < TRACE < DEBUG < INFO < WARN < ERROR < FATAL < OFFLog4j recommends using the four levels DEBUG, INFO, WARN, and ERROR for most scenarios.
Log Level Examples
TRACE Example
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("- ===========间隔超过分钟再次发送电流电压值");INFO Example
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);DEBUG Example
DRV_LOG_DEBUG("- 输出报警情况:电网编号:%d,报警数量:%d,报警内容:%s.", datas.data1.chn, datas.data1.alarm_num, datas.data1.alarms);
... (additional similar DEBUG statements) ...
DRV_LOG_DEBUG("- GetChannelExtInfo channelId=%s", channelId.c_str());
DRV_LOG_DEBUG("- nChan = %d, szInfo = %s", nChan, szInfo);WARN Example
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 statements) ...ERROR Example
DRV_LOG_ERROR("Init DwSDK filded;<errCode=%d>", 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<errCode=%d>", iGetResult);
DRV_LOG_ERROR("SetEventCallBack should be called first");
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());Formatting Guidelines
A typical log entry should include date, time, level, code location, message, and optionally an error code.
Example of a formatted log line:
2018-05-22 15:35:53.850 TRACE TDWZLog [0x00001b10] <36> <TDWZProtocol::Init>, TDWZProtocol::InitThe format 0x%08x prints an integer in hexadecimal, padded to eight digits (e.g., printf("0x%08x", 0x1234); outputs 0x00001234).
Conclusion
Adhering to these logging standards improves traceability, debugging efficiency, and system performance while preventing common pitfalls such as excessive disk usage or unreadable log output.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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!
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.
