The code:
You would then import it as:
const { format } = require("date-fns");
/**
* logger is a small tool to centralize the logging of the application
* @params {String} src - this will be prefixed before each message. It can be any string
* that would be significant when you read them in the logs (often in this code base it's the name
* of the file from where the log is sent)
*/
const logger = (src) => {
return {
/**simply displays the message in the console
* @param {String} msg - the message to be displayed
* @return - nothing
*/
info: (msg) => {
const now = format(new Date(), "dd/MM/yyyy HH:mm");
console.log(`${now} info - ${msg} (${src})`);
},
/** displays the message in the console with a warning prefix
* @param {String} msg - the message to be displayed
* @return - nothing
*/
warn: (msg) => {
const now = format(new Date(), "dd/MM/yyyy HH:mm");
console.warn(`${now} warning - ${msg} (${src})`);
},
/** displays the message in the console with an error prefix
* @todo send the error to slack in production environment
* @param {String} msg - the message to be displayed
* @return - nothing
*/
err: (error) => {
const now = format(new Date(), "dd/MM/yyyy HH:mm");
// in production, send to slack/email
console.error(`${now} ERROR - ${error.message || error} (${src})`);
},
};
};
module.exports = logger;
`const log = require("../logger.js")(__filename)`
in every file you want to use it, and there you go :)
Be careful, in a production environment it is unwise to use the console the object. If you use this code, be sure to create some conditional statements for changing the behavior in production.
Hope it can be useful to someone!
Comments
Post a Comment