Skip to main content

Logger

Goal

The goal of the Logger is to log events that occur on the backend of An Scéalaí. This is helpful for fixing bugs and spotting when errors occur, as well as for providing generic information on how the system is running.

Current Setup

The logger.js file can be found at AnScealai/api/logger.js. The Logger initialised in this file is required throughout the backend in order to log certain activities. This Logger is an instance of the Winston1 logger module, one of the most commonly used loggers for Node.js. For development and debugging purposes, using the console module (console.log()) is a great way to log any information on both the stdout and stderr. However, if we want to access these logs later, or provide more organised and detailed information, Winston allows us to store these logs in additional locations, along with other custom properties, which makes the logger easier to manage and more insightful.

The Winston logger records messages categorised into particular levels. The levels used in An Scéalaí are as follows, with 0 being the most important message and 7 being the least important:

  • Emergency: 0
  • Alert: 1
  • Critical: 2
  • Error: 3
  • Warning: 4
  • Notice: 5
  • Info: 6
  • Debug: 7

The logger logs these messages along with an error level. These levels can be used to determine where the logger stores these messages as they occur. These different locations are called transports. Our logger currently configures three transports: two in files and one in MongoDB. All logs of any type are stored in the logs/combined.log file as well as the log collection in MongoDB. Any logs marked with the error level are additionally stored in the file logs/error.log. More details on configuring the Winston logger can be found in this tutorial .

Usage

The logger.js file first initialises some variables for later reference, such as the date format to use and the file paths for the logger to output any messages. The winston.format.printf() function is used to set the format for any logging to occur in the console window.

The file then defines the transports array, which contains the information for where to send the message logs. This array contains configurations for logging messages to the console and the two files in the /logs folder. Finally, the different message levels are configured in the levels array. The winston.createLogger() function uses the transports and levels array to initialise the logger.

Finally, the file initialises a new transport for logging the message to MongoDB. It uses the winston.transports.MongoDB() module to define the database and collection for storing the data. It then adds this transport mode to the initialised logger.

This logger is then exported using the module.exports = logger command, where it can be imported and used in other files on the backend.


Footnotes

  1. Winston Logger: https://www.npmjs.com/package/winston