123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145 |
- 'use strict';
- const debug = require('debug')('log4js:main');
- const fs = require('fs');
- const deepClone = require('rfdc')({ proto: true });
- const configuration = require('./configuration');
- const layouts = require('./layouts');
- const levels = require('./levels');
- const appenders = require('./appenders');
- const categories = require('./categories');
- const Logger = require('./logger');
- const clustering = require('./clustering');
- const connectLogger = require('./connect-logger');
- let enabled = false;
- function sendLogEventToAppender(logEvent) {
- if (!enabled) return;
- debug('Received log event ', logEvent);
- const categoryAppenders = categories.appendersForCategory(logEvent.categoryName);
- categoryAppenders.forEach((appender) => {
- appender(logEvent);
- });
- }
- function loadConfigurationFile(filename) {
- if (filename) {
- debug(`Loading configuration from ${filename}`);
- return JSON.parse(fs.readFileSync(filename, 'utf8'));
- }
- return filename;
- }
- function configure(configurationFileOrObject) {
- let configObject = configurationFileOrObject;
- if (typeof configObject === 'string') {
- configObject = loadConfigurationFile(configurationFileOrObject);
- }
- debug(`Configuration is ${configObject}`);
- configuration.configure(deepClone(configObject));
- clustering.onMessage(sendLogEventToAppender);
- enabled = true;
- return log4js;
- }
- function shutdown(cb) {
- debug('Shutdown called. Disabling all log writing.');
-
-
- enabled = false;
-
- const appendersToCheck = Array.from(appenders.values());
- const shutdownFunctions = appendersToCheck.reduceRight((accum, next) => (next.shutdown ? accum + 1 : accum), 0);
- let completed = 0;
- let error;
- debug(`Found ${shutdownFunctions} appenders with shutdown functions.`);
- function complete(err) {
- error = error || err;
- completed += 1;
- debug(`Appender shutdowns complete: ${completed} / ${shutdownFunctions}`);
- if (completed >= shutdownFunctions) {
- debug('All shutdown functions completed.');
- cb(error);
- }
- }
- if (shutdownFunctions === 0) {
- debug('No appenders with shutdown functions found.');
- return cb();
- }
- appendersToCheck.filter(a => a.shutdown).forEach(a => a.shutdown(complete));
- return null;
- }
- function getLogger(category) {
- if (!enabled) {
- configure(process.env.LOG4JS_CONFIG || {
- appenders: { out: { type: 'stdout' } },
- categories: { default: { appenders: ['out'], level: 'OFF' } }
- });
- }
- return new Logger(category || 'default');
- }
- const log4js = {
- getLogger,
- configure,
- shutdown,
- connectLogger,
- levels,
- addLayout: layouts.addLayout
- };
- module.exports = log4js;
|