Skip to content

Instantly share code, notes, and snippets.

@ericwastaken
Created July 7, 2018 20:28
Show Gist options
  • Save ericwastaken/11d0230f4f7dd57ef4907cd6250d985f to your computer and use it in GitHub Desktop.
Save ericwastaken/11d0230f4f7dd57ef4907cd6250d985f to your computer and use it in GitHub Desktop.
log4js singleton pattern
/**
* Creates and returns a reference to a shared instance of log4js. Only a single instance is created
* regardless of how many references are made.
*
* To set your desired log level, change the following line to suit your needs.
* - `const config = { logLevel: 'debug' };`
*
* In another module or file that you wish to log, do the following:
* - `const SharedLog = require('./path/to/SharedLog.js');`
* - `const logger = SharedLog.getInstance().logger;`
* - `logger.debug('whatever you want to log')`
* - of course, you can use:
* - logger.debug
* - logger.error
* - logger.XXXX - where XXXX is any of the log levels supported!
* - to use the custom log 'dberror':
* - `logger.log('dberror', 'whatever you want to log');`
*
* Note that the logger (regardless of which one you use) takes variadic arguments. You have to pass at least
* one argument, or as many as you wish, including passing objects.
*
* The logger below also demonstrates the use of a file appender. Any logs sent to 'dberror' will be
* written to a file called 'run.log'. Ser the log4js documentation for more details on file appenders,
* including log file rotation and more.
*
* More about the Log4js framework here: https://stritti.github.io/log4js/docu/users-guide.html
* And about the specific NodeJS implementation here: https://log4js-node.github.io/log4js-node/index.html
*
* This work is licensed under the MIT License as follows:
*
* Copyright 2018 E.A.Soto <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
* to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions
* of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
* TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*
*/
// In your package.json, you need to have a dependency to 'log4js'
const log4js = require('log4js');
// Set logLevel to any of: off, fatal, error, warn, info, debug, trace, all
// In our case, we can also use dberror which will log to a db errors file!
const config = { logLevel: 'debug' };
let SharedLog = (function() {
// Instance stores a reference to the Singleton
let _sharedLog;
let _logger;
/**
* Class instance initializer. This is not something you call externally, but is instead
* used internally by the getInstance() method.
*
* @return {{logger: Logger | *}}
*/
function init() {
// We don't have a shared log instance yet, so let's create it and store it
_sharedLog = this;
// Configure the logger
log4js.configure({
levels: {
dberror: { value: log4js.levels.ERROR.level + 5, colour: 'magenta' },
},
appenders: {
console: {
type: 'stdout',
layout: { type: 'colored' },
level: 'trace',
},
// File appenders support log rotation and more. See the log4js documentation for that.
file: {
type: 'file',
// rename your log file here to whatever you want
filename: 'run.log',
compress: false,
},
dberrorstofile: {
type: 'logLevelFilter',
appender: 'file',
level: 'dberror',
},
},
categories: {
default: { appenders: ['dberrorstofile', 'console'], level: 'off' },
},
});
// Create an instance as configured
_logger = log4js.getLogger();
// Configure the Log Level
_logger.level = config.logLevel;
return {
// Public methods and variables
// public method: function (someParam) {
// console.log(someParam);
// },
logger: _logger,
};
}
return {
/**
* This is the method used externally which returns an instance of SharedLog.
* Inside SharedLog, we can then access '.logger' which is our log4js instance.
* See the comments in the header for this class on how to reference this.
* @return {*}
*/
getInstance: function() {
// Get the Singleton instance if one exists
// or create one if it doesn't
if (!_sharedLog) {
_sharedLog = init();
}
return _sharedLog;
},
};
})();
module.exports = SharedLog;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment