🏳️10 Best Practices for Logging in Node.js

If you're developing a Node.js application, logging is an essential part of maintaining and debugging your code. Proper logging helps you identify errors, diagnose issues

If you're developing a Node.js application, logging is an essential part of maintaining and debugging your code. Proper logging helps you identify errors, diagnose issues, and gain insights into how your application is performing in production.

Here are 10 tips for effective Node.js logging:

1. Use a logging library

Rather than writing your own logging code, it's best to use a logging library like Winston or Bunyan. These libraries offer a range of features and allow you to easily configure logging output.

Winston is a popular logging framework that provides a simple and consistent API for logging in Node.js. With Winston, you can easily log messages with different log levels and formats, and direct them to different transport options, such as console, file, or a remote service.

Using a logging framework can save you time and effort in setting up logging functionality, and provides you with a standardized approach to logging that makes it easier to manage your logs

2. Log relevant informations

When logging, make sure to include relevant information like the timestamp, severity level, and context of the log message.

By using different log levels, you can categorize your logs based on their importance and severity. For example, you could use the 'error' level for critical errors that require immediate attention, and the 'debug' level for more detailed messages that can help you diagnose issues

3. Choose a logging level

Determine the appropriate logging level for each log message based on its severity. Use levels like "error," "warning," "info," and "debug" to categorize your log messages.

Using log levels helps you organize and filter your logs, and enables you to focus on the most important messages. It also allows you to adjust the level of detail in your logs depending on your needs

Avoid doing this:

{"message": "Payment failed"}

Without log severity levels, it would be difficult to set up an automated alerting system that notifies you when the application produces a log entry that demands attention.

{"level": "error", "message": "Payment failed"}

That's better, Using log levels helps you organize and filter your logs, and enables you to focus on the most important messages. It also allows you to adjust the level of detail in your logs depending on your needs.

4. Structured logs

A structured log uses a specific format to log information in a way that is easy to parse and analyze. One common format is JSON, which allows you to include key-value pairs to represent your log messages.

Avoid this:

{"level": "error", "message": "Route /user/:id 404"}

Better keep it structured this way:

{
   "level": "error",
   "message": "Route /user/:id 404",
   "status": 404, 
   "route": "/user/:id"
}

5. Include Timestamps

Timestamps provide a valuable context for your logs and make it easier to track down issues or understand the timing of specific events. Be sure to use a consistent timestamp format to avoid confusion

{
   "timestamp": "2020-01-10T14:12:19.345Z",
   "level": "error",
   "message": "Route /user/:id 404",
   "status": 404, 
   "route": "/user/:id"
}

Avoid using format other than ISO-8601.

Frameworks like Bunyan, Winston or Pino output a timestamp by default without additional configuration.

6. Avoid logging sensitive data

Logging sensitive data can put your application and users at risk. Be sure to review your logs and remove any sensitive information before storing or sharing them. If you need to log sensitive data for debugging purposes, consider using a secure logging framework or encrypting the logs.

Avoid this:

{
  "timestamp": "2020-01-10T14:12:19.345Z",
  "level": "error",
  "message": "Transaction failed"
  "metaData": {
    "id": "12345",
    "name": "John Wick",
    "email": "[email protected]",
    "phone": "1234567890",
    "other": "sensitive Data"
  }
}

Pino has a really good feature called Redaction to redact your sensitive data from your logs. We recommend to pay more attention to logs when reviewing Merge Requests as this may help to protect your clients.

{
  "timestamp": "2020-01-10T14:12:19.345Z",
  "level": "error",
  "message": "Transaction failed"
  "metaData": {
    "id": "12345"
  }
}

7. Log enough context to your logs

Include context information in your log messages to provide additional context to your logs. This can include information like the user ID, request ID, correlation ID, or transaction ID, etc.

Example of 404 in Express.js:

{
   "timestamp": "2020-01-10T14:12:19.345Z",
   "level": "error",
   "message": "url not found",
   "metaData": {
      "status": 404, 
      "url": "/user/s/12345",
      "method": "get",
      "body": null,
      "params": {
         "id": "12345"
      },
      "query": null,
      "body": null,
      "headers": {
         "Authorization": "bearer A.B.C",
         "referrer": "example.com"
      },
   }
}

The more context your add to your log the more useful they are, remember to not to rely on the redaction techniques demonstrated above, use JSON or key value data.

It could be useful as well to log the request and response data for each incoming HTTP request. This can help you diagnose issues related to specific requests.

8. Add logs to every piece of you App

Logging is an essential part of programming because it helps developers identify errors, diagnose issues, and gain insights into how an application is performing in production. When developing an application, it's not uncommon to encounter bugs or issues that require investigation.

Without proper logging, it can be difficult to identify the source of an issue or understand how an application is behaving in production. Logging provides a way to capture relevant information about an application's behavior, such as errors, performance metrics, and user interactions, in a structured and searchable format. This information can then be used to debug issues, improve performance, and gain insights into how an application is being used. Overall, logging is a critical tool for ensuring the reliability, maintainability, and performance of software applications.

That's why we recommend to add logs in every piece of code. including global events such as uncaughtException, or unhandledrejection, 404 or 500. and in every Try Catch bloc.

// <= handle 404 errors here
app.use(function(req, res, next) {
  logger.error(err, {
    errorType: '404',
    url: req.originalUrl,
    method: req.method,
    body: req.body,
    params: req.params,
    query: req.query,
    headers: req.headers,
  }); // <= Log here
  res.status(404).send("Sorry, that route doesn't exist.");
});

// <= handle 500 errors here
app.use(function(err, req, res, next) {
  // Send what you see fit for debugging
  logger.error(err, {
    errorType: '5XX',
    url: req.originalUrl,
    method: req.method,
    body: req.body,
    params: req.params,
    query: req.query,
    headers: req.headers,
  }); // <= Log here

  res.status(500).send('Internal Server Error!'); 
});

process.on('uncaughtException', function (err) {
  logger.error(err, 'Uncaught Exception'); // <= your log here
  process.exit(1);
});

process.on('unhandledrejection', function (err) {
  logger.error(err, 'Uncaught Exception'); // <= your log here
  process.exit(1);
});

try {
  logger.debug('Usefull debug message'); // <= your log here
  sendEmail()
  logger.debug('Another usefull debug message'); // <= your log here
} catch () {
  logger.error(err, 'Sending Email Failed'); // <= your log here
}

9. Use log rotation

Log rotation helps prevent log files from becoming too large, which can slow down your application and cause performance issues or crashes in your application. Set up log rotation with a policy that works for your application and its logging requirements.

10. Centralize logs

Storing your logs in a central location is important for a few reasons. First, it helps to consolidate your logs in one place, making it easier to access and analyze them. Instead of having logs spread across different servers and applications, a central location can provide a more complete view of your system's activity.

Secondly, centralizing your logs can make it easier to troubleshoot issues when they arise. By having all your logs in one place, you can quickly identify patterns or errors that may be causing problems. This can save time and effort when trying to diagnose and resolve issues.

Finally, a central location can help with compliance and security requirements. Having a centralized logging system can ensure that all logs are properly stored and maintained, making it easier to meet regulatory requirements or respond to security incidents.

Summary

LogsHQ.io can help companies save time and do all the above by offering a centralized logging platform with real-time alerting, advanced analytics, and powerful search capabilities. Here are some ways that LogsHQ can help:

  1. LogsHQ.io, you can easily set up structured logging and view your logs in a structured and organized way.

  2. LogsHQ.io allows you to customize the data you log, so you can focus on what's most important.

  3. LogsHQ.io allows you to customize the data you log, so you can focus on what's most important.

  4. LogsHQ.io provide you with powerful search capabilities, so you can easily trace requests through your application.

  5. LogsHQ.io supports different log levels, so you can easily categorize your logs and set up alerts based on log level

  6. LogsHQ.io allows you to view stack traces for errors, so you can quickly identify the source of the issue, by providing you with all informations your needs such as the stack trace, the number of occurrences and the specific line of code responsible for the error.

  7. LogsHQ.io supports log rotation for your, so you can easily manage your logs without any configuration from your side.

  8. LogsHQ.io provides centralized log management, so you can easily view and search all your logs in one place.

  9. LogsHQ.io provides real-time alerting and notifications, so you can set up alerts based on log level or search queries.

  10. LogsHQ.io provides log visualization tools, so you can easily visualize your logs and gain insights into your application's behavior.

Overall, LogsHQ can save companies time by providing a centralized location for logs, real-time alerting, advanced analytics, powerful search, and compliance and security features. This can help companies troubleshoot issues more efficiently, minimize downtime, and meet regulatory requirements.

Last updated