Logging Rules

Logging is a debugging tool, especially useful when someone needs to understand what already happened or when a debugger cannot be attached to a running instance of the program.

Some rules I've found for better logging:

  1. First, excessive logging can quickly dilute the value of logs. Logs can be used as a development tool, but in production, logs should only contain information about significant events. The most valuable log statements usually involve an unexpected code path or error.

  2. The location in the code base where the log statement was made should be easily identifiable. In other words, if an error is logged, it is immensely useful if you can quickly find the corresponding lines of code which actually logged the error.

  3. Log statements should be brief. For instance, while a log such as Error when creating new post for blog system due to user action. may be nice to read, when there are hundreds of logs with the same statement, it is useless data which must still be processed.

  4. Logging statements should have context. For instance, if the log statement was related to a specific database row, perhaps the row identifier is logged. More importantly, the log line should be easily parsable. Having a log line like Create post error. errorCode=%d browser=%s ipAddress=%s provides the required information while making it easy to search. Logging storage systems can easily ingest the error and separate out the contextual information. If you needed to look for all errors related to an ipAddress (like authentication errors and post creation errors), then a query using ipAddress=... is much easier to make rather than a long query for each possible logged error string.