Skip to content

Instantly share code, notes, and snippets.

@leegee
Created June 23, 2016 07:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leegee/7d4fb9eb9e8a960e1e41d40245725287 to your computer and use it in GitHub Desktop.
Save leegee/7d4fb9eb9e8a960e1e41d40245725287 to your computer and use it in GitHub Desktop.
log4js base
// base.js
function Base(options) {
var category;
// https://github.com/v8/v8/wiki/Stack-Trace-API
try {
category = ((new Error).stack.split('\n'))[2].match(/^\s+at\sBase\.(\w+)/)[1];
}
catch (e) {
try {
category = ((new Error).stack.split('\n'))[1].match(/^\s+at\s(\w+)\.Base/)[1];
}
catch (e) {
throw new Error(
'Could not set logging category from stack:\n' + (new Error).stack
);
}
}
/** @field {Logger} logger - An instance of {@link Logger}, with category set to reflect the invocant. */
this.logger = require('./logger').getLogger(category);
}
// logger.js
'use strict';
const log4js = require('log4js');
module.exports.configure = function (pathOrConfig) {
if (process.env.LOG_EXC) {
let exc = process.env.LOG_EXC.replace(/\s+/, '');
if (exc.length > 0) {
if (typeof pathOrConfig === 'string') {
let configJson = require('fs').readFileSync(pathOrConfig);
pathOrConfig = JSON.parse(configJson);
}
pathOrConfig.appenders.forEach((appender) => {
if (appender.type === 'categoryFilter') {
appender.exclude = appender.exclude || [];
exc.split(/,/).forEach((i) => {
appender.exclude.push(i);
});
}
});
}
}
log4js.configure(pathOrConfig);
return module.exports.getLogger();
};
module.exports.getLogger = function () {
logger = log4js.getLogger(_logger);
if (typeof logger.setLevel === 'function') {
let logLevel = process.env.LOG_LEVEL || 'TRACE';
logger.setLevel(logLevel.toUpperCase());
}
return logger;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment