Skip to content

Instantly share code, notes, and snippets.

@rohit267
Last active December 28, 2021 05:41
Show Gist options
  • Save rohit267/27a80e0ad9ab61fb39d0fcd08ab2f0c4 to your computer and use it in GitHub Desktop.
Save rohit267/27a80e0ad9ab61fb39d0fcd08ab2f0c4 to your computer and use it in GitHub Desktop.
Easy Nodejs custom logger with saveToFile support
import chalk from 'chalk';
import moment from 'moment';
import fs from 'fs-extra';
import path from 'path';
/*
* Easy custom logger to save logs in date wise file in DD-MM-YYYY.txt.
* dependencies: chalk, moment, fs-extra
* Author: Rohit Mahto
* Github: https://github.com/rohit267
*/
/*
* Usage :
* npm i chalk moment fs-extra
*
* for just colorful console print:
* import { logger } from 'Logger';
*
* with saveToFile:
* import Logger from 'Logger';
* const logger = new Logger({saveToFile: true, logsFolderPath:'your/logs/folder' });
* logger.info('Some Info', jsonObject);
* logger.warn('Some warning', jsonObject);
* logger.error('Some error', jsonObject);
* logger.success('Some success', jsonObject);
*
* Note: logsFolderPath is required only when saveToFile is true.
*/
export default class Logger {
constructor({ saveToFile, logsFolderPath }) {
this.saveToFile = saveToFile;
if (this.saveToFile) {
if (!logsFolderPath) throw new Error('logsFolderPath is required when saveToFile is true');
this.logsFolderPath = path.resolve(logsFolderPath);
}
/**
*
* @returns {String} current time in format DD-MM-YYYY HH:MM:SS
*/
this._getTime = () => {
return moment().format('DD/MM/YYYY HH:mm:ss:SSS ZZ');
};
/**
*
* @param {String} mTime
* @param {String} type
* @param {String} message
* Writes to the log file.
*/
this._writeLogFile = (mTime, type, message, json) => {
if (this.saveToFile) {
try {
let stringMessage = `${mTime} ${type}: ${message}${json && this._checkIfJson(json) ? '\n' + JSON.stringify(json, null, 2) : json ? '\n' + json : ''}`;
fs.ensureDir(this.logsFolderPath);
fs.appendFile(path.resolve(this.logsFolderPath, `${moment().format('DD-MM-YYYY')}.txt`), stringMessage + '\n');
} catch (e) {
console.log(this.error(`Error writing log file: ${e}`));
}
}
};
/**
*
* @param {Object/JSON} json
* Check if json is object or not
* @returns true or false
*/
this._checkIfJson = (json) => {
//return true if json is object
return typeof json === 'object' && json !== null;
};
}
/**
*
* @param {String} message
* @param {Object/JSON} json
*/
info(message, json) {
const mTime = this._getTime();
console.log(
chalk.magenta(mTime) + ' ' + chalk.blue('INFO: ') + message,
json && this._checkIfJson(json) ? '\n' + JSON.stringify(json, null, 2) : json ? '\n' + json : ''
);
this._writeLogFile(mTime, 'INFO', message, json);
}
/**
*
* @param {String} message
* @param {Object/JSON} json
*/
error(message, json) {
const mTime = this._getTime();
console.log(
chalk.magenta(mTime) + ' ' + chalk.red('ERROR: ') + message,
json && this._checkIfJson(json) ? '\n' + JSON.stringify(json, null, 2) : json ? '\n' + json : ''
);
this._writeLogFile(mTime, 'ERROR', message);
}
/**
*
* @param {String} message
* @param {Object/JSON} json
*/
warn(message, json) {
const mTime = this._getTime();
console.log(
chalk.magenta(mTime) + ' ' + chalk.yellow('WARN: ') + message,
json && this._checkIfJson(json) ? '\n' + JSON.stringify(json, null, 2) : json ? '\n' + json : ''
);
this._writeLogFile(mTime, 'WARN', message);
}
/**
*
* @param {String} message
* @param {Object/JSON} json
*/
success(message, json) {
const mTime = this._getTime();
console.log(
chalk.magenta(mTime) + ' ' + chalk.green('SUCCESS: ') + message,
json && this._checkIfJson(json) ? '\n' + JSON.stringify(json, null, 2) : json ? '\n' + json : ''
);
this._writeLogFile(mTime, 'SUCCESS', message);
}
}
export const logger = new Logger({
saveToFile: false,
// logsFolderPath: path.resolve(process.cwd(), 'logs'),
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment