repo_name
stringclasses
28 values
pr_number
int64
8
3.71k
pr_title
stringlengths
3
107
pr_description
stringlengths
0
60.1k
author
stringlengths
4
19
date_created
unknown
date_merged
unknown
previous_commit
stringlengths
40
40
pr_commit
stringlengths
40
40
query
stringlengths
5
60.1k
filepath
stringlengths
7
167
before_content
stringlengths
0
103M
after_content
stringlengths
0
103M
label
int64
-1
1
log4js-node/log4js-node
1,386
add maxLength to recording - closes #1385
gabriel-cloud
"2023-05-19T22:07:06"
"2023-06-07T01:27:16"
26dcec62f9677dceba57de8cd717ff91447781c7
c5d71e9212ed374122dfd783d2518379d5beca13
add maxLength to recording - closes #1385.
./docs/recording.md
# Recording Appender This appender stores the log events in memory. It is mainly useful for testing (see the tests for the category filter, for instance). ## Configuration - `type` - `recording` There is no other configuration for this appender. ## Usage The array that stores log events is shared across all recording appender instances, and is accessible from the recording module. `require('<LOG4JS LIB DIR>/appenders/recording')` returns a module with the following functions exported: - `replay` - returns `Array<LogEvent>` - get all the events recorded. - `playback` - synonym for `replay` - `reset` - clears the array of events recorded. - `erase` - synonyms for `reset` ## Example ```javascript const recording = require("log4js/lib/appenders/recording"); const log4js = require("log4js"); log4js.configure({ appenders: { vcr: { type: "recording" } }, categories: { default: { appenders: ["vcr"], level: "info" } }, }); const logger = log4js.getLogger(); logger.info("some log event"); const events = recording.replay(); // events is an array of LogEvent objects. recording.erase(); // clear the appender's array. ```
# Recording Appender This appender stores the log events in memory. It is mainly useful for testing (see the tests for the category filter, for instance). ## Configuration - `type` - `recording` - `maxLength` - `integer` (optional, defaults to undefined) - the maximum array length for the recording. If not specified, the array will grow until cleared There is no other configuration for this appender. ## Usage The array that stores log events is shared across all recording appender instances, and is accessible from the recording module. `require('<LOG4JS LIB DIR>/appenders/recording')` returns a module with the following functions exported: - `replay` - returns `Array<LogEvent>` - get all the events recorded. - `playback` - synonym for `replay` - `reset` - clears the array of events recorded. - `erase` - synonyms for `reset` ## Example ```javascript const recording = require("log4js/lib/appenders/recording"); const log4js = require("log4js"); log4js.configure({ appenders: { vcr: { type: "recording" } }, categories: { default: { appenders: ["vcr"], level: "info" } }, }); const logger = log4js.getLogger(); logger.info("some log event"); const events = recording.replay(); // events is an array of LogEvent objects. recording.erase(); // clear the appender's array. ```
1
log4js-node/log4js-node
1,386
add maxLength to recording - closes #1385
gabriel-cloud
"2023-05-19T22:07:06"
"2023-06-07T01:27:16"
26dcec62f9677dceba57de8cd717ff91447781c7
c5d71e9212ed374122dfd783d2518379d5beca13
add maxLength to recording - closes #1385.
./lib/appenders/recording.js
const debug = require('debug')('log4js:recording'); const recordedEvents = []; function configure() { return function (logEvent) { debug( `received logEvent, number of events now ${recordedEvents.length + 1}` ); debug('log event was ', logEvent); recordedEvents.push(logEvent); }; } function replay() { return recordedEvents.slice(); } function reset() { recordedEvents.length = 0; } module.exports = { configure, replay, playback: replay, reset, erase: reset, };
const debug = require('debug')('log4js:recording'); const recordedEvents = []; function configure(config) { return function (logEvent) { debug( `received logEvent, number of events now ${recordedEvents.length + 1}` ); debug('log event was ', logEvent); if (config.maxLength && recordedEvents.length >= config.maxLength) { recordedEvents.shift(); } recordedEvents.push(logEvent); }; } function replay() { return recordedEvents.slice(); } function reset() { recordedEvents.length = 0; } module.exports = { configure, replay, playback: replay, reset, erase: reset, };
1
log4js-node/log4js-node
1,386
add maxLength to recording - closes #1385
gabriel-cloud
"2023-05-19T22:07:06"
"2023-06-07T01:27:16"
26dcec62f9677dceba57de8cd717ff91447781c7
c5d71e9212ed374122dfd783d2518379d5beca13
add maxLength to recording - closes #1385.
./test/tap/recordingAppender-test.js
const { test } = require('tap'); const log4js = require('../../lib/log4js'); test('recording appender', (t) => { log4js.configure({ appenders: { rec: { type: 'recording' } }, categories: { default: { appenders: ['rec'], level: 'debug' } }, }); const logger = log4js.getLogger(); logger.level = 'debug'; logger.debug('This will go to the recording!'); logger.debug('Another one'); const recording = log4js.recording(); const loggingEvents = recording.playback(); t.equal(loggingEvents.length, 2, 'There should be 2 recorded events'); t.equal(loggingEvents[0].data[0], 'This will go to the recording!'); t.equal(loggingEvents[1].data[0], 'Another one'); recording.reset(); const loggingEventsPostReset = recording.playback(); t.equal( loggingEventsPostReset.length, 0, 'There should be 0 recorded events' ); t.end(); });
const { test } = require('tap'); const log4js = require('../../lib/log4js'); test('recording appender', (batch) => { batch.test('should store logs in memory until cleared', (t) => { log4js.configure({ appenders: { rec: { type: 'recording' } }, categories: { default: { appenders: ['rec'], level: 'debug' } }, }); const logger = log4js.getLogger(); logger.level = 'debug'; logger.debug('This will go to the recording!'); logger.debug('Another one'); const recording = log4js.recording(); const loggingEvents = recording.playback(); t.equal(loggingEvents.length, 2, 'There should be 2 recorded events'); t.equal(loggingEvents[0].data[0], 'This will go to the recording!'); t.equal(loggingEvents[1].data[0], 'Another one'); recording.reset(); const loggingEventsPostReset = recording.playback(); t.equal( loggingEventsPostReset.length, 0, 'There should be 0 recorded events' ); t.end(); }); batch.test('should store 2 rolling logs in memory until cleared', (t) => { log4js.configure({ appenders: { rec2: { type: 'recording', maxLength: 2 } }, categories: { default: { appenders: ['rec2'], level: 'debug' } }, }); const logger = log4js.getLogger(); logger.level = 'debug'; logger.debug('First log entry'); logger.debug('Second log entry'); const recording = log4js.recording(); t.equal( recording.playback().length, 2, 'There should be 2 recorded events' ); t.equal(recording.playback()[0].data[0], 'First log entry'); t.equal(recording.playback()[1].data[0], 'Second log entry'); logger.debug('Third log entry'); t.equal( recording.playback().length, 2, 'There should still be 2 recording events' ); t.equal(recording.playback()[0].data[0], 'Second log entry'); t.equal(recording.playback()[1].data[0], 'Third log entry'); recording.reset(); const loggingEventsPostReset = recording.playback(); t.equal( loggingEventsPostReset.length, 0, 'There should be 0 recorded events' ); t.end(); }); batch.end(); });
1
log4js-node/log4js-node
1,386
add maxLength to recording - closes #1385
gabriel-cloud
"2023-05-19T22:07:06"
"2023-06-07T01:27:16"
26dcec62f9677dceba57de8cd717ff91447781c7
c5d71e9212ed374122dfd783d2518379d5beca13
add maxLength to recording - closes #1385.
./test/tap/configuration-validation-test.js
const { test } = require('tap'); const util = require('util'); const path = require('path'); const sandbox = require('@log4js-node/sandboxed-module'); const debug = require('debug')('log4js:test.configuration-validation'); const deepFreeze = require('deep-freeze'); const fs = require('fs'); const log4js = require('../../lib/log4js'); const configuration = require('../../lib/configuration'); const removeFiles = async (filenames) => { if (!Array.isArray(filenames)) filenames = [filenames]; const promises = filenames.map((filename) => fs.promises.unlink(filename)); await Promise.allSettled(promises); }; const testAppender = (label, result) => ({ configure(config, layouts, findAppender) { debug( `testAppender(${label}).configure called, with config: ${util.inspect( config )}` ); result.configureCalled = true; result.type = config.type; result.label = label; result.config = config; result.layouts = layouts; result.findAppender = findAppender; return {}; }, }); test('log4js configuration validation', (batch) => { batch.test('should give error if config is just plain silly', (t) => { [null, undefined, '', ' ', []].forEach((config) => { const expectedError = new Error( `Problem with log4js configuration: (${util.inspect( config )}) - must be an object.` ); t.throws(() => configuration.configure(config), expectedError); }); t.end(); }); batch.test('should give error if config is an empty object', (t) => { t.throws( () => log4js.configure({}), '- must have a property "appenders" of type object.' ); t.end(); }); batch.test('should give error if config has no appenders', (t) => { t.throws( () => log4js.configure({ categories: {} }), '- must have a property "appenders" of type object.' ); t.end(); }); batch.test('should give error if config has no categories', (t) => { t.throws( () => log4js.configure({ appenders: { out: { type: 'stdout' } } }), '- must have a property "categories" of type object.' ); t.end(); }); batch.test('should give error if appenders is not an object', (t) => { t.throws( () => log4js.configure({ appenders: [], categories: [] }), '- must have a property "appenders" of type object.' ); t.end(); }); batch.test('should give error if appenders are not all valid', (t) => { t.throws( () => log4js.configure({ appenders: { thing: 'cheese' }, categories: {} }), '- appender "thing" is not valid (must be an object with property "type")' ); t.end(); }); batch.test('should require at least one appender', (t) => { t.throws( () => log4js.configure({ appenders: {}, categories: {} }), '- must define at least one appender.' ); t.end(); }); batch.test('should give error if categories are not all valid', (t) => { t.throws( () => log4js.configure({ appenders: { stdout: { type: 'stdout' } }, categories: { thing: 'cheese' }, }), '- category "thing" is not valid (must be an object with properties "appenders" and "level")' ); t.end(); }); batch.test('should give error if default category not defined', (t) => { t.throws( () => log4js.configure({ appenders: { stdout: { type: 'stdout' } }, categories: { thing: { appenders: ['stdout'], level: 'ERROR' } }, }), '- must define a "default" category.' ); t.end(); }); batch.test('should require at least one category', (t) => { t.throws( () => log4js.configure({ appenders: { stdout: { type: 'stdout' } }, categories: {}, }), '- must define at least one category.' ); t.end(); }); batch.test('should give error if category.appenders is not an array', (t) => { t.throws( () => log4js.configure({ appenders: { stdout: { type: 'stdout' } }, categories: { thing: { appenders: {}, level: 'ERROR' } }, }), '- category "thing" is not valid (appenders must be an array of appender names)' ); t.end(); }); batch.test('should give error if category.appenders is empty', (t) => { t.throws( () => log4js.configure({ appenders: { stdout: { type: 'stdout' } }, categories: { thing: { appenders: [], level: 'ERROR' } }, }), '- category "thing" is not valid (appenders must contain at least one appender name)' ); t.end(); }); batch.test( 'should give error if categories do not refer to valid appenders', (t) => { t.throws( () => log4js.configure({ appenders: { stdout: { type: 'stdout' } }, categories: { thing: { appenders: ['cheese'], level: 'ERROR' } }, }), '- category "thing" is not valid (appender "cheese" is not defined)' ); t.end(); } ); batch.test('should give error if category level is not valid', (t) => { t.throws( () => log4js.configure({ appenders: { stdout: { type: 'stdout' } }, categories: { default: { appenders: ['stdout'], level: 'Biscuits' } }, }), '- category "default" is not valid (level "Biscuits" not recognised; valid levels are ALL, TRACE' ); t.end(); }); batch.test( 'should give error if category enableCallStack is not valid', (t) => { t.throws( () => log4js.configure({ appenders: { stdout: { type: 'stdout' } }, categories: { default: { appenders: ['stdout'], level: 'Debug', enableCallStack: '123', }, }, }), '- category "default" is not valid (enableCallStack must be boolean type)' ); t.end(); } ); batch.test('should give error if appender type cannot be found', (t) => { t.throws( () => log4js.configure({ appenders: { thing: { type: 'cheese' } }, categories: { default: { appenders: ['thing'], level: 'ERROR' } }, }), '- appender "thing" is not valid (type "cheese" could not be found)' ); t.end(); }); batch.test('should create appender instances', (t) => { const thing = {}; const sandboxedLog4js = sandbox.require('../../lib/log4js', { requires: { cheese: testAppender('cheesy', thing), }, ignoreMissing: true, }); sandboxedLog4js.configure({ appenders: { thing: { type: 'cheese' } }, categories: { default: { appenders: ['thing'], level: 'ERROR' } }, }); t.ok(thing.configureCalled); t.equal(thing.type, 'cheese'); t.end(); }); batch.test( 'should use provided appender instance if instance provided', (t) => { const thing = {}; const cheese = testAppender('cheesy', thing); const sandboxedLog4js = sandbox.require('../../lib/log4js', { ignoreMissing: true, }); sandboxedLog4js.configure({ appenders: { thing: { type: cheese } }, categories: { default: { appenders: ['thing'], level: 'ERROR' } }, }); t.ok(thing.configureCalled); t.same(thing.type, cheese); t.end(); } ); batch.test('should not throw error if configure object is freezed', (t) => { const testFile = 'test/tap/freeze-date-file-test'; t.teardown(async () => { await removeFiles(testFile); }); t.doesNotThrow(() => log4js.configure( deepFreeze({ appenders: { dateFile: { type: 'dateFile', filename: testFile, alwaysIncludePattern: false, }, }, categories: { default: { appenders: ['dateFile'], level: log4js.levels.ERROR }, }, }) ) ); log4js.shutdown(() => { t.end(); }); }); batch.test('should load appenders from core first', (t) => { const result = {}; const sandboxedLog4js = sandbox.require('../../lib/log4js', { requires: { './cheese': testAppender('correct', result), cheese: testAppender('wrong', result), }, ignoreMissing: true, }); sandboxedLog4js.configure({ appenders: { thing: { type: 'cheese' } }, categories: { default: { appenders: ['thing'], level: 'ERROR' } }, }); t.ok(result.configureCalled); t.equal(result.type, 'cheese'); t.equal(result.label, 'correct'); t.end(); }); batch.test( 'should load appenders relative to main file if not in core, or node_modules', (t) => { const result = {}; const mainPath = path.dirname(require.main.filename); const sandboxConfig = { ignoreMissing: true, requires: {}, }; sandboxConfig.requires[`${mainPath}/cheese`] = testAppender( 'correct', result ); // add this one, because when we're running coverage the main path is a bit different sandboxConfig.requires[ `${path.join(mainPath, '../../node_modules/nyc/bin/cheese')}` ] = testAppender('correct', result); // in tap v15, the main path is at root of log4js (run `DEBUG=log4js:appenders npm test > /dev/null` to check) sandboxConfig.requires[`${path.join(mainPath, '../../cheese')}`] = testAppender('correct', result); // in node v6, there's an extra layer of node modules for some reason, so add this one to work around it sandboxConfig.requires[ `${path.join( mainPath, '../../node_modules/tap/node_modules/nyc/bin/cheese' )}` ] = testAppender('correct', result); const sandboxedLog4js = sandbox.require( '../../lib/log4js', sandboxConfig ); sandboxedLog4js.configure({ appenders: { thing: { type: 'cheese' } }, categories: { default: { appenders: ['thing'], level: 'ERROR' } }, }); t.ok(result.configureCalled); t.equal(result.type, 'cheese'); t.equal(result.label, 'correct'); t.end(); } ); batch.test( 'should load appenders relative to process.cwd if not found in core, node_modules', (t) => { const result = {}; const fakeProcess = new Proxy(process, { get(target, key) { if (key === 'cwd') { return () => '/var/lib/cheese'; } return target[key]; }, }); // windows file paths are different to unix, so let's make this work for both. const requires = {}; requires[path.join('/var', 'lib', 'cheese', 'cheese')] = testAppender( 'correct', result ); const sandboxedLog4js = sandbox.require('../../lib/log4js', { ignoreMissing: true, requires, globals: { process: fakeProcess, }, }); sandboxedLog4js.configure({ appenders: { thing: { type: 'cheese' } }, categories: { default: { appenders: ['thing'], level: 'ERROR' } }, }); t.ok(result.configureCalled); t.equal(result.type, 'cheese'); t.equal(result.label, 'correct'); t.end(); } ); batch.test('should pass config, layout, findAppender to appenders', (t) => { const result = {}; const sandboxedLog4js = sandbox.require('../../lib/log4js', { ignoreMissing: true, requires: { cheese: testAppender('cheesy', result), notCheese: testAppender('notCheesy', {}), }, }); sandboxedLog4js.configure({ appenders: { thing: { type: 'cheese', foo: 'bar' }, thing2: { type: 'notCheese' }, }, categories: { default: { appenders: ['thing'], level: 'ERROR' } }, }); t.ok(result.configureCalled); t.equal(result.type, 'cheese'); t.equal(result.config.foo, 'bar'); t.type(result.layouts, 'object'); t.type(result.layouts.basicLayout, 'function'); t.type(result.findAppender, 'function'); t.type(result.findAppender('thing2'), 'object'); t.end(); }); batch.test( 'should not give error if level object is used instead of string', (t) => { t.doesNotThrow(() => log4js.configure({ appenders: { thing: { type: 'stdout' } }, categories: { default: { appenders: ['thing'], level: log4js.levels.ERROR }, }, }) ); t.end(); } ); batch.test( 'should not create appender instance if not used in categories', (t) => { const used = {}; const notUsed = {}; const sandboxedLog4js = sandbox.require('../../lib/log4js', { requires: { cat: testAppender('meow', used), dog: testAppender('woof', notUsed), }, ignoreMissing: true, }); sandboxedLog4js.configure({ appenders: { used: { type: 'cat' }, notUsed: { type: 'dog' } }, categories: { default: { appenders: ['used'], level: 'ERROR' } }, }); t.ok(used.configureCalled); t.notOk(notUsed.configureCalled); t.end(); } ); batch.end(); });
const { test } = require('tap'); const util = require('util'); const path = require('path'); const sandbox = require('@log4js-node/sandboxed-module'); const debug = require('debug')('log4js:test.configuration-validation'); const deepFreeze = require('deep-freeze'); const fs = require('fs'); const log4js = require('../../lib/log4js'); const configuration = require('../../lib/configuration'); const removeFiles = async (filenames) => { if (!Array.isArray(filenames)) filenames = [filenames]; const promises = filenames.map((filename) => fs.promises.unlink(filename)); await Promise.allSettled(promises); }; const testAppender = (label, result) => ({ configure(config, layouts, findAppender) { debug( `testAppender(${label}).configure called, with config: ${util.inspect( config )}` ); result.configureCalled = true; result.type = config.type; result.label = label; result.config = config; result.layouts = layouts; result.findAppender = findAppender; return {}; }, }); test('log4js configuration validation', (batch) => { batch.test('should give error if config is just plain silly', (t) => { [null, undefined, '', ' ', []].forEach((config) => { const expectedError = new Error( `Problem with log4js configuration: (${util.inspect( config )}) - must be an object.` ); t.throws(() => configuration.configure(config), expectedError); }); t.end(); }); batch.test('should give error if config is an empty object', (t) => { t.throws( () => log4js.configure({}), '- must have a property "appenders" of type object.' ); t.end(); }); batch.test('should give error if config has no appenders', (t) => { t.throws( () => log4js.configure({ categories: {} }), '- must have a property "appenders" of type object.' ); t.end(); }); batch.test('should give error if config has no categories', (t) => { t.throws( () => log4js.configure({ appenders: { out: { type: 'stdout' } } }), '- must have a property "categories" of type object.' ); t.end(); }); batch.test('should give error if appenders is not an object', (t) => { t.throws( () => log4js.configure({ appenders: [], categories: [] }), '- must have a property "appenders" of type object.' ); t.end(); }); batch.test('should give error if appenders are not all valid', (t) => { t.throws( () => log4js.configure({ appenders: { thing: 'cheese' }, categories: {} }), '- appender "thing" is not valid (must be an object with property "type")' ); t.end(); }); batch.test('should require at least one appender', (t) => { t.throws( () => log4js.configure({ appenders: {}, categories: {} }), '- must define at least one appender.' ); t.end(); }); batch.test('should give error if categories are not all valid', (t) => { t.throws( () => log4js.configure({ appenders: { stdout: { type: 'stdout' } }, categories: { thing: 'cheese' }, }), '- category "thing" is not valid (must be an object with properties "appenders" and "level")' ); t.end(); }); batch.test('should give error if default category not defined', (t) => { t.throws( () => log4js.configure({ appenders: { stdout: { type: 'stdout' } }, categories: { thing: { appenders: ['stdout'], level: 'ERROR' } }, }), '- must define a "default" category.' ); t.end(); }); batch.test('should require at least one category', (t) => { t.throws( () => log4js.configure({ appenders: { stdout: { type: 'stdout' } }, categories: {}, }), '- must define at least one category.' ); t.end(); }); batch.test('should give error if category.appenders is not an array', (t) => { t.throws( () => log4js.configure({ appenders: { stdout: { type: 'stdout' } }, categories: { thing: { appenders: {}, level: 'ERROR' } }, }), '- category "thing" is not valid (appenders must be an array of appender names)' ); t.end(); }); batch.test('should give error if category.appenders is empty', (t) => { t.throws( () => log4js.configure({ appenders: { stdout: { type: 'stdout' } }, categories: { thing: { appenders: [], level: 'ERROR' } }, }), '- category "thing" is not valid (appenders must contain at least one appender name)' ); t.end(); }); batch.test( 'should give error if categories do not refer to valid appenders', (t) => { t.throws( () => log4js.configure({ appenders: { stdout: { type: 'stdout' } }, categories: { thing: { appenders: ['cheese'], level: 'ERROR' } }, }), '- category "thing" is not valid (appender "cheese" is not defined)' ); t.end(); } ); batch.test('should give error if category level is not valid', (t) => { t.throws( () => log4js.configure({ appenders: { stdout: { type: 'stdout' } }, categories: { default: { appenders: ['stdout'], level: 'Biscuits' } }, }), '- category "default" is not valid (level "Biscuits" not recognised; valid levels are ALL, TRACE' ); t.end(); }); batch.test( 'should give error if category enableCallStack is not valid', (t) => { t.throws( () => log4js.configure({ appenders: { stdout: { type: 'stdout' } }, categories: { default: { appenders: ['stdout'], level: 'Debug', enableCallStack: '123', }, }, }), '- category "default" is not valid (enableCallStack must be boolean type)' ); t.end(); } ); batch.test('should give error if appender type cannot be found', (t) => { t.throws( () => log4js.configure({ appenders: { thing: { type: 'cheese' } }, categories: { default: { appenders: ['thing'], level: 'ERROR' } }, }), '- appender "thing" is not valid (type "cheese" could not be found)' ); t.end(); }); batch.test('should create appender instances', (t) => { const thing = {}; const sandboxedLog4js = sandbox.require('../../lib/log4js', { requires: { cheese: testAppender('cheesy', thing), }, ignoreMissing: true, }); sandboxedLog4js.configure({ appenders: { thing: { type: 'cheese' } }, categories: { default: { appenders: ['thing'], level: 'ERROR' } }, }); t.ok(thing.configureCalled); t.equal(thing.type, 'cheese'); t.end(); }); batch.test( 'should use provided appender instance if instance provided', (t) => { const thing = {}; const cheese = testAppender('cheesy', thing); const sandboxedLog4js = sandbox.require('../../lib/log4js', { ignoreMissing: true, }); sandboxedLog4js.configure({ appenders: { thing: { type: cheese } }, categories: { default: { appenders: ['thing'], level: 'ERROR' } }, }); t.ok(thing.configureCalled); t.same(thing.type, cheese); t.end(); } ); batch.test('should not throw error if configure object is freezed', (t) => { const testFile = 'test/tap/freeze-date-file-test'; t.teardown(async () => { await removeFiles(testFile); }); t.doesNotThrow(() => log4js.configure( deepFreeze({ appenders: { dateFile: { type: 'dateFile', filename: testFile, alwaysIncludePattern: false, }, }, categories: { default: { appenders: ['dateFile'], level: log4js.levels.ERROR }, }, }) ) ); log4js.shutdown(() => { t.end(); }); }); batch.test('should load appenders from core first', (t) => { const result = {}; const sandboxedLog4js = sandbox.require('../../lib/log4js', { requires: { './cheese': testAppender('correct', result), cheese: testAppender('wrong', result), }, ignoreMissing: true, }); sandboxedLog4js.configure({ appenders: { thing: { type: 'cheese' } }, categories: { default: { appenders: ['thing'], level: 'ERROR' } }, }); t.ok(result.configureCalled); t.equal(result.type, 'cheese'); t.equal(result.label, 'correct'); t.end(); }); batch.test( 'should load appenders relative to main file if not in core, or node_modules', (t) => { const result = {}; const mainPath = path.dirname(require.main.filename); const sandboxConfig = { ignoreMissing: true, requires: {}, }; sandboxConfig.requires[`${mainPath}/cheese`] = testAppender( 'correct', result ); // add this one, because when we're running coverage the main path is a bit different sandboxConfig.requires[ `${path.join(mainPath, '../../node_modules/nyc/bin/cheese')}` ] = testAppender('correct', result); // in tap v15, the main path is at root of log4js (run `DEBUG=log4js:appenders npm test > /dev/null` to check) sandboxConfig.requires[`${path.join(mainPath, '../../cheese')}`] = testAppender('correct', result); // in node v6, there's an extra layer of node modules for some reason, so add this one to work around it sandboxConfig.requires[ `${path.join( mainPath, '../../node_modules/tap/node_modules/nyc/bin/cheese' )}` ] = testAppender('correct', result); const sandboxedLog4js = sandbox.require( '../../lib/log4js', sandboxConfig ); sandboxedLog4js.configure({ appenders: { thing: { type: 'cheese' } }, categories: { default: { appenders: ['thing'], level: 'ERROR' } }, }); t.ok(result.configureCalled); t.equal(result.type, 'cheese'); t.equal(result.label, 'correct'); t.end(); } ); batch.test( 'should load appenders relative to process.cwd if not found in core, node_modules', (t) => { const result = {}; const fakeProcess = new Proxy(process, { get(target, key) { if (key === 'cwd') { return () => '/var/lib/cheese'; } return target[key]; }, }); // windows file paths are different to unix, so let's make this work for both. const requires = {}; requires[path.join('/var', 'lib', 'cheese', 'cheese')] = testAppender( 'correct', result ); const sandboxedLog4js = sandbox.require('../../lib/log4js', { ignoreMissing: true, requires, globals: { process: fakeProcess, }, }); sandboxedLog4js.configure({ appenders: { thing: { type: 'cheese' } }, categories: { default: { appenders: ['thing'], level: 'ERROR' } }, }); t.ok(result.configureCalled); t.equal(result.type, 'cheese'); t.equal(result.label, 'correct'); t.end(); } ); batch.test('should pass config, layout, findAppender to appenders', (t) => { const result = {}; const sandboxedLog4js = sandbox.require('../../lib/log4js', { ignoreMissing: true, requires: { cheese: testAppender('cheesy', result), notCheese: testAppender('notCheesy', {}), }, }); sandboxedLog4js.configure({ appenders: { thing: { type: 'cheese', foo: 'bar' }, thing2: { type: 'notCheese' }, }, categories: { default: { appenders: ['thing'], level: 'ERROR' } }, }); t.ok(result.configureCalled); t.equal(result.type, 'cheese'); t.equal(result.config.foo, 'bar'); t.type(result.layouts, 'object'); t.type(result.layouts.basicLayout, 'function'); t.type(result.findAppender, 'function'); t.type(result.findAppender('thing2'), 'object'); t.end(); }); batch.test( 'should not give error if level object is used instead of string', (t) => { t.doesNotThrow(() => log4js.configure({ appenders: { thing: { type: 'stdout' } }, categories: { default: { appenders: ['thing'], level: log4js.levels.ERROR }, }, }) ); t.end(); } ); batch.test( 'should not create appender instance if not used in categories', (t) => { const used = {}; const notUsed = {}; const sandboxedLog4js = sandbox.require('../../lib/log4js', { requires: { cat: testAppender('meow', used), dog: testAppender('woof', notUsed), }, ignoreMissing: true, }); sandboxedLog4js.configure({ appenders: { used: { type: 'cat' }, notUsed: { type: 'dog' } }, categories: { default: { appenders: ['used'], level: 'ERROR' } }, }); t.ok(used.configureCalled); t.notOk(notUsed.configureCalled); t.end(); } ); batch.end(); });
-1
log4js-node/log4js-node
1,386
add maxLength to recording - closes #1385
gabriel-cloud
"2023-05-19T22:07:06"
"2023-06-07T01:27:16"
26dcec62f9677dceba57de8cd717ff91447781c7
c5d71e9212ed374122dfd783d2518379d5beca13
add maxLength to recording - closes #1385.
./examples/example.js
'use strict'; const log4js = require('../lib/log4js'); // log the cheese logger messages to a file, and the console ones as well. log4js.configure({ appenders: { cheeseLogs: { type: 'file', filename: 'cheese.log' }, console: { type: 'console' }, }, categories: { cheese: { appenders: ['cheeseLogs'], level: 'error' }, another: { appenders: ['console'], level: 'trace' }, default: { appenders: ['console', 'cheeseLogs'], level: 'trace' }, }, }); // a custom logger outside of the log4js/lib/appenders directory can be accessed like so // log4js.configure({ // appenders: { outside: { type: 'what/you/would/put/in/require', otherArgs: 'blah' } } // ... // }); const logger = log4js.getLogger('cheese'); // only errors and above get logged. const otherLogger = log4js.getLogger(); // this will get coloured output on console, and appear in cheese.log otherLogger.error('AAArgh! Something went wrong', { some: 'otherObject', useful_for: 'debug purposes', }); otherLogger.log('This should appear as info output'); // these will not appear (logging level beneath error) logger.trace('Entering cheese testing'); logger.debug('Got cheese.'); logger.info('Cheese is Gouda.'); logger.log('Something funny about cheese.'); logger.warn('Cheese is quite smelly.'); // these end up only in cheese.log logger.error('Cheese %s is too ripe!', 'gouda'); logger.fatal('Cheese was breeding ground for listeria.'); // these don't end up in cheese.log, but will appear on the console const anotherLogger = log4js.getLogger('another'); anotherLogger.debug('Just checking'); // will also go to console and cheese.log, since that's configured for all categories const pantsLog = log4js.getLogger('pants'); pantsLog.debug('Something for pants');
'use strict'; const log4js = require('../lib/log4js'); // log the cheese logger messages to a file, and the console ones as well. log4js.configure({ appenders: { cheeseLogs: { type: 'file', filename: 'cheese.log' }, console: { type: 'console' }, }, categories: { cheese: { appenders: ['cheeseLogs'], level: 'error' }, another: { appenders: ['console'], level: 'trace' }, default: { appenders: ['console', 'cheeseLogs'], level: 'trace' }, }, }); // a custom logger outside of the log4js/lib/appenders directory can be accessed like so // log4js.configure({ // appenders: { outside: { type: 'what/you/would/put/in/require', otherArgs: 'blah' } } // ... // }); const logger = log4js.getLogger('cheese'); // only errors and above get logged. const otherLogger = log4js.getLogger(); // this will get coloured output on console, and appear in cheese.log otherLogger.error('AAArgh! Something went wrong', { some: 'otherObject', useful_for: 'debug purposes', }); otherLogger.log('This should appear as info output'); // these will not appear (logging level beneath error) logger.trace('Entering cheese testing'); logger.debug('Got cheese.'); logger.info('Cheese is Gouda.'); logger.log('Something funny about cheese.'); logger.warn('Cheese is quite smelly.'); // these end up only in cheese.log logger.error('Cheese %s is too ripe!', 'gouda'); logger.fatal('Cheese was breeding ground for listeria.'); // these don't end up in cheese.log, but will appear on the console const anotherLogger = log4js.getLogger('another'); anotherLogger.debug('Just checking'); // will also go to console and cheese.log, since that's configured for all categories const pantsLog = log4js.getLogger('pants'); pantsLog.debug('Something for pants');
-1
log4js-node/log4js-node
1,386
add maxLength to recording - closes #1385
gabriel-cloud
"2023-05-19T22:07:06"
"2023-06-07T01:27:16"
26dcec62f9677dceba57de8cd717ff91447781c7
c5d71e9212ed374122dfd783d2518379d5beca13
add maxLength to recording - closes #1385.
./test/tap/multi-file-appender-test.js
const process = require('process'); const { test } = require('tap'); const debug = require('debug'); const fs = require('fs'); const sandbox = require('@log4js-node/sandboxed-module'); const log4js = require('../../lib/log4js'); const osDelay = process.platform === 'win32' ? 400 : 200; const removeFiles = async (filenames) => { if (!Array.isArray(filenames)) filenames = [filenames]; const promises = filenames.map((filename) => fs.promises.unlink(filename)); await Promise.allSettled(promises); }; test('multiFile appender', (batch) => { batch.test( 'should write to multiple files based on the loggingEvent property', (t) => { t.teardown(async () => { await removeFiles(['logs/A.log', 'logs/B.log']); }); log4js.configure({ appenders: { multi: { type: 'multiFile', base: 'logs/', property: 'categoryName', extension: '.log', }, }, categories: { default: { appenders: ['multi'], level: 'info' } }, }); const loggerA = log4js.getLogger('A'); const loggerB = log4js.getLogger('B'); loggerA.info('I am in logger A'); loggerB.info('I am in logger B'); log4js.shutdown(() => { t.match(fs.readFileSync('logs/A.log', 'utf-8'), 'I am in logger A'); t.match(fs.readFileSync('logs/B.log', 'utf-8'), 'I am in logger B'); t.end(); }); } ); batch.test( 'should write to multiple files based on loggingEvent.context properties', (t) => { t.teardown(async () => { await removeFiles(['logs/C.log', 'logs/D.log']); }); log4js.configure({ appenders: { multi: { type: 'multiFile', base: 'logs/', property: 'label', extension: '.log', }, }, categories: { default: { appenders: ['multi'], level: 'info' } }, }); const loggerC = log4js.getLogger('cheese'); const loggerD = log4js.getLogger('biscuits'); loggerC.addContext('label', 'C'); loggerD.addContext('label', 'D'); loggerC.info('I am in logger C'); loggerD.info('I am in logger D'); log4js.shutdown(() => { t.match(fs.readFileSync('logs/C.log', 'utf-8'), 'I am in logger C'); t.match(fs.readFileSync('logs/D.log', 'utf-8'), 'I am in logger D'); t.end(); }); } ); batch.test('should close file after timeout', (t) => { /* checking that the file is closed after a timeout is done by looking at the debug logs since detecting file locks with node.js is platform specific. */ const debugWasEnabled = debug.enabled('log4js:multiFile'); const debugLogs = []; const originalWrite = process.stderr.write; process.stderr.write = (string, encoding, fd) => { debugLogs.push(string); if (debugWasEnabled) { originalWrite.apply(process.stderr, [string, encoding, fd]); } }; const originalNamespace = debug.disable(); debug.enable(`${originalNamespace}, log4js:multiFile`); t.teardown(async () => { await new Promise((resolve) => { log4js.shutdown(resolve); }); await removeFiles('logs/C.log'); process.stderr.write = originalWrite; debug.enable(originalNamespace); }); const timeoutMs = 50; log4js.configure({ appenders: { multi: { type: 'multiFile', base: 'logs/', property: 'label', extension: '.log', timeout: timeoutMs, }, }, categories: { default: { appenders: ['multi'], level: 'info' } }, }); const loggerC = log4js.getLogger('cheese'); loggerC.addContext('label', 'C'); loggerC.info('I am in logger C'); setTimeout(() => { t.match( debugLogs[debugLogs.length - 1], `C not used for > ${timeoutMs} ms => close`, '(timeout1) should have closed' ); t.end(); }, timeoutMs * 1 + osDelay); }); batch.test('should close file safely after timeout', (t) => { const error = new Error('fileAppender shutdown error'); const sandboxedLog4js = sandbox.require('../../lib/log4js', { requires: { './appenders/file': { configure(config, layouts) { const fileAppender = require('../../lib/appenders/file').configure( config, layouts ); const originalShutdown = fileAppender.shutdown; fileAppender.shutdown = function (complete) { const onCallback = function () { complete(error); }; originalShutdown(onCallback); }; return fileAppender; }, }, debug, }, }); /* checking that the file is closed after a timeout is done by looking at the debug logs since detecting file locks with node.js is platform specific. */ const debugWasEnabled = debug.enabled('log4js:multiFile'); const debugLogs = []; const originalWrite = process.stderr.write; process.stderr.write = (string, encoding, fd) => { debugLogs.push(string); if (debugWasEnabled) { originalWrite.apply(process.stderr, [string, encoding, fd]); } }; const originalNamespace = debug.disable(); debug.enable(`${originalNamespace}, log4js:multiFile`); t.teardown(async () => { await new Promise((resolve) => { sandboxedLog4js.shutdown(resolve); }); await removeFiles('logs/C.log'); process.stderr.write = originalWrite; debug.enable(originalNamespace); }); const timeoutMs = 50; sandboxedLog4js.configure({ appenders: { multi: { type: 'multiFile', base: 'logs/', property: 'label', extension: '.log', timeout: timeoutMs, }, }, categories: { default: { appenders: ['multi'], level: 'info' } }, }); const loggerC = sandboxedLog4js.getLogger('cheese'); loggerC.addContext('label', 'C'); loggerC.info('I am in logger C'); setTimeout(() => { t.match( debugLogs[debugLogs.length - 2], `C not used for > ${timeoutMs} ms => close`, '(timeout1) should have closed' ); t.match( debugLogs[debugLogs.length - 1], `ignore error on file shutdown: ${error.message}`, 'safely shutdown' ); t.end(); }, timeoutMs * 1 + osDelay); }); batch.test('should close file after extended timeout', (t) => { /* checking that the file is closed after a timeout is done by looking at the debug logs since detecting file locks with node.js is platform specific. */ const debugWasEnabled = debug.enabled('log4js:multiFile'); const debugLogs = []; const originalWrite = process.stderr.write; process.stderr.write = (string, encoding, fd) => { debugLogs.push(string); if (debugWasEnabled) { originalWrite.apply(process.stderr, [string, encoding, fd]); } }; const originalNamespace = debug.disable(); debug.enable(`${originalNamespace}, log4js:multiFile`); t.teardown(async () => { await new Promise((resolve) => { log4js.shutdown(resolve); }); await removeFiles('logs/D.log'); process.stderr.write = originalWrite; debug.enable(originalNamespace); }); const timeoutMs = 1000; log4js.configure({ appenders: { multi: { type: 'multiFile', base: 'logs/', property: 'label', extension: '.log', timeout: timeoutMs, }, }, categories: { default: { appenders: ['multi'], level: 'info' } }, }); const loggerD = log4js.getLogger('cheese'); loggerD.addContext('label', 'D'); loggerD.info('I am in logger D'); setTimeout(() => { loggerD.info('extending activity!'); t.match( debugLogs[debugLogs.length - 1], 'D extending activity', 'should have extended' ); }, timeoutMs / 2); setTimeout(() => { t.notOk( debugLogs.some( (s) => s.indexOf(`D not used for > ${timeoutMs} ms => close`) !== -1 ), '(timeout1) should not have closed' ); }, timeoutMs * 1 + osDelay); setTimeout(() => { t.match( debugLogs[debugLogs.length - 1], `D not used for > ${timeoutMs} ms => close`, '(timeout2) should have closed' ); t.end(); }, timeoutMs * 2 + osDelay); }); batch.test('should clear interval for active timers on shutdown', (t) => { /* checking that the file is closed after a timeout is done by looking at the debug logs since detecting file locks with node.js is platform specific. */ const debugWasEnabled = debug.enabled('log4js:multiFile'); const debugLogs = []; const originalWrite = process.stderr.write; process.stderr.write = (string, encoding, fd) => { debugLogs.push(string); if (debugWasEnabled) { originalWrite.apply(process.stderr, [string, encoding, fd]); } }; const originalNamespace = debug.disable(); debug.enable(`${originalNamespace}, log4js:multiFile`); t.teardown(async () => { await removeFiles('logs/D.log'); process.stderr.write = originalWrite; debug.enable(originalNamespace); }); const timeoutMs = 100; log4js.configure({ appenders: { multi: { type: 'multiFile', base: 'logs/', property: 'label', extension: '.log', timeout: timeoutMs, }, }, categories: { default: { appenders: ['multi'], level: 'info' } }, }); const loggerD = log4js.getLogger('cheese'); loggerD.addContext('label', 'D'); loggerD.info('I am in logger D'); log4js.shutdown(() => { t.notOk( debugLogs.some( (s) => s.indexOf(`D not used for > ${timeoutMs} ms => close`) !== -1 ), 'should not have closed' ); t.ok( debugLogs.some((s) => s.indexOf('clearing timer for D') !== -1), 'should have cleared timers' ); t.match( debugLogs[debugLogs.length - 1], 'calling shutdown for D', 'should have called shutdown' ); t.end(); }); }); batch.test( 'should fail silently if loggingEvent property has no value', (t) => { t.teardown(async () => { await removeFiles('logs/E.log'); }); log4js.configure({ appenders: { multi: { type: 'multiFile', base: 'logs/', property: 'label', extension: '.log', }, }, categories: { default: { appenders: ['multi'], level: 'info' } }, }); const loggerE = log4js.getLogger(); loggerE.addContext('label', 'E'); loggerE.info('I am in logger E'); loggerE.removeContext('label'); loggerE.info('I am not in logger E'); loggerE.addContext('label', null); loggerE.info('I am also not in logger E'); log4js.shutdown(() => { const contents = fs.readFileSync('logs/E.log', 'utf-8'); t.match(contents, 'I am in logger E'); t.notMatch(contents, 'I am not in logger E'); t.notMatch(contents, 'I am also not in logger E'); t.end(); }); } ); batch.test('should pass options to rolling file stream', (t) => { t.teardown(async () => { await removeFiles(['logs/F.log', 'logs/F.log.1', 'logs/F.log.2']); }); log4js.configure({ appenders: { multi: { type: 'multiFile', base: 'logs/', property: 'label', extension: '.log', maxLogSize: 30, backups: 2, layout: { type: 'messagePassThrough' }, }, }, categories: { default: { appenders: ['multi'], level: 'info' } }, }); const loggerF = log4js.getLogger(); loggerF.addContext('label', 'F'); loggerF.info('Being in logger F is the best.'); loggerF.info('I am also in logger F, awesome'); loggerF.info('I am in logger F'); log4js.shutdown(() => { let contents = fs.readFileSync('logs/F.log', 'utf-8'); t.match(contents, 'I am in logger F'); contents = fs.readFileSync('logs/F.log.1', 'utf-8'); t.match(contents, 'I am also in logger F'); contents = fs.readFileSync('logs/F.log.2', 'utf-8'); t.match(contents, 'Being in logger F is the best'); t.end(); }); }); batch.test('should inherit config from category hierarchy', (t) => { t.teardown(async () => { await removeFiles('logs/test.someTest.log'); }); log4js.configure({ appenders: { out: { type: 'stdout' }, test: { type: 'multiFile', base: 'logs/', property: 'categoryName', extension: '.log', }, }, categories: { default: { appenders: ['out'], level: 'info' }, test: { appenders: ['test'], level: 'debug' }, }, }); const testLogger = log4js.getLogger('test.someTest'); testLogger.debug('This should go to the file'); log4js.shutdown(() => { const contents = fs.readFileSync('logs/test.someTest.log', 'utf-8'); t.match(contents, 'This should go to the file'); t.end(); }); }); batch.test('should shutdown safely even if it is not used', (t) => { log4js.configure({ appenders: { out: { type: 'stdout' }, test: { type: 'multiFile', base: 'logs/', property: 'categoryName', extension: '.log', }, }, categories: { default: { appenders: ['out'], level: 'info' }, test: { appenders: ['test'], level: 'debug' }, }, }); log4js.shutdown(() => { t.ok('callback is called'); t.end(); }); }); batch.teardown(async () => { try { const files = fs.readdirSync('logs'); await removeFiles(files.map((filename) => `logs/${filename}`)); fs.rmdirSync('logs'); } catch (e) { // doesn't matter } }); batch.end(); });
const process = require('process'); const { test } = require('tap'); const debug = require('debug'); const fs = require('fs'); const sandbox = require('@log4js-node/sandboxed-module'); const log4js = require('../../lib/log4js'); const osDelay = process.platform === 'win32' ? 400 : 200; const removeFiles = async (filenames) => { if (!Array.isArray(filenames)) filenames = [filenames]; const promises = filenames.map((filename) => fs.promises.unlink(filename)); await Promise.allSettled(promises); }; test('multiFile appender', (batch) => { batch.test( 'should write to multiple files based on the loggingEvent property', (t) => { t.teardown(async () => { await removeFiles(['logs/A.log', 'logs/B.log']); }); log4js.configure({ appenders: { multi: { type: 'multiFile', base: 'logs/', property: 'categoryName', extension: '.log', }, }, categories: { default: { appenders: ['multi'], level: 'info' } }, }); const loggerA = log4js.getLogger('A'); const loggerB = log4js.getLogger('B'); loggerA.info('I am in logger A'); loggerB.info('I am in logger B'); log4js.shutdown(() => { t.match(fs.readFileSync('logs/A.log', 'utf-8'), 'I am in logger A'); t.match(fs.readFileSync('logs/B.log', 'utf-8'), 'I am in logger B'); t.end(); }); } ); batch.test( 'should write to multiple files based on loggingEvent.context properties', (t) => { t.teardown(async () => { await removeFiles(['logs/C.log', 'logs/D.log']); }); log4js.configure({ appenders: { multi: { type: 'multiFile', base: 'logs/', property: 'label', extension: '.log', }, }, categories: { default: { appenders: ['multi'], level: 'info' } }, }); const loggerC = log4js.getLogger('cheese'); const loggerD = log4js.getLogger('biscuits'); loggerC.addContext('label', 'C'); loggerD.addContext('label', 'D'); loggerC.info('I am in logger C'); loggerD.info('I am in logger D'); log4js.shutdown(() => { t.match(fs.readFileSync('logs/C.log', 'utf-8'), 'I am in logger C'); t.match(fs.readFileSync('logs/D.log', 'utf-8'), 'I am in logger D'); t.end(); }); } ); batch.test('should close file after timeout', (t) => { /* checking that the file is closed after a timeout is done by looking at the debug logs since detecting file locks with node.js is platform specific. */ const debugWasEnabled = debug.enabled('log4js:multiFile'); const debugLogs = []; const originalWrite = process.stderr.write; process.stderr.write = (string, encoding, fd) => { debugLogs.push(string); if (debugWasEnabled) { originalWrite.apply(process.stderr, [string, encoding, fd]); } }; const originalNamespace = debug.disable(); debug.enable(`${originalNamespace}, log4js:multiFile`); t.teardown(async () => { await new Promise((resolve) => { log4js.shutdown(resolve); }); await removeFiles('logs/C.log'); process.stderr.write = originalWrite; debug.enable(originalNamespace); }); const timeoutMs = 50; log4js.configure({ appenders: { multi: { type: 'multiFile', base: 'logs/', property: 'label', extension: '.log', timeout: timeoutMs, }, }, categories: { default: { appenders: ['multi'], level: 'info' } }, }); const loggerC = log4js.getLogger('cheese'); loggerC.addContext('label', 'C'); loggerC.info('I am in logger C'); setTimeout(() => { t.match( debugLogs[debugLogs.length - 1], `C not used for > ${timeoutMs} ms => close`, '(timeout1) should have closed' ); t.end(); }, timeoutMs * 1 + osDelay); }); batch.test('should close file safely after timeout', (t) => { const error = new Error('fileAppender shutdown error'); const sandboxedLog4js = sandbox.require('../../lib/log4js', { requires: { './appenders/file': { configure(config, layouts) { const fileAppender = require('../../lib/appenders/file').configure( config, layouts ); const originalShutdown = fileAppender.shutdown; fileAppender.shutdown = function (complete) { const onCallback = function () { complete(error); }; originalShutdown(onCallback); }; return fileAppender; }, }, debug, }, }); /* checking that the file is closed after a timeout is done by looking at the debug logs since detecting file locks with node.js is platform specific. */ const debugWasEnabled = debug.enabled('log4js:multiFile'); const debugLogs = []; const originalWrite = process.stderr.write; process.stderr.write = (string, encoding, fd) => { debugLogs.push(string); if (debugWasEnabled) { originalWrite.apply(process.stderr, [string, encoding, fd]); } }; const originalNamespace = debug.disable(); debug.enable(`${originalNamespace}, log4js:multiFile`); t.teardown(async () => { await new Promise((resolve) => { sandboxedLog4js.shutdown(resolve); }); await removeFiles('logs/C.log'); process.stderr.write = originalWrite; debug.enable(originalNamespace); }); const timeoutMs = 50; sandboxedLog4js.configure({ appenders: { multi: { type: 'multiFile', base: 'logs/', property: 'label', extension: '.log', timeout: timeoutMs, }, }, categories: { default: { appenders: ['multi'], level: 'info' } }, }); const loggerC = sandboxedLog4js.getLogger('cheese'); loggerC.addContext('label', 'C'); loggerC.info('I am in logger C'); setTimeout(() => { t.match( debugLogs[debugLogs.length - 2], `C not used for > ${timeoutMs} ms => close`, '(timeout1) should have closed' ); t.match( debugLogs[debugLogs.length - 1], `ignore error on file shutdown: ${error.message}`, 'safely shutdown' ); t.end(); }, timeoutMs * 1 + osDelay); }); batch.test('should close file after extended timeout', (t) => { /* checking that the file is closed after a timeout is done by looking at the debug logs since detecting file locks with node.js is platform specific. */ const debugWasEnabled = debug.enabled('log4js:multiFile'); const debugLogs = []; const originalWrite = process.stderr.write; process.stderr.write = (string, encoding, fd) => { debugLogs.push(string); if (debugWasEnabled) { originalWrite.apply(process.stderr, [string, encoding, fd]); } }; const originalNamespace = debug.disable(); debug.enable(`${originalNamespace}, log4js:multiFile`); t.teardown(async () => { await new Promise((resolve) => { log4js.shutdown(resolve); }); await removeFiles('logs/D.log'); process.stderr.write = originalWrite; debug.enable(originalNamespace); }); const timeoutMs = 1000; log4js.configure({ appenders: { multi: { type: 'multiFile', base: 'logs/', property: 'label', extension: '.log', timeout: timeoutMs, }, }, categories: { default: { appenders: ['multi'], level: 'info' } }, }); const loggerD = log4js.getLogger('cheese'); loggerD.addContext('label', 'D'); loggerD.info('I am in logger D'); setTimeout(() => { loggerD.info('extending activity!'); t.match( debugLogs[debugLogs.length - 1], 'D extending activity', 'should have extended' ); }, timeoutMs / 2); setTimeout(() => { t.notOk( debugLogs.some( (s) => s.indexOf(`D not used for > ${timeoutMs} ms => close`) !== -1 ), '(timeout1) should not have closed' ); }, timeoutMs * 1 + osDelay); setTimeout(() => { t.match( debugLogs[debugLogs.length - 1], `D not used for > ${timeoutMs} ms => close`, '(timeout2) should have closed' ); t.end(); }, timeoutMs * 2 + osDelay); }); batch.test('should clear interval for active timers on shutdown', (t) => { /* checking that the file is closed after a timeout is done by looking at the debug logs since detecting file locks with node.js is platform specific. */ const debugWasEnabled = debug.enabled('log4js:multiFile'); const debugLogs = []; const originalWrite = process.stderr.write; process.stderr.write = (string, encoding, fd) => { debugLogs.push(string); if (debugWasEnabled) { originalWrite.apply(process.stderr, [string, encoding, fd]); } }; const originalNamespace = debug.disable(); debug.enable(`${originalNamespace}, log4js:multiFile`); t.teardown(async () => { await removeFiles('logs/D.log'); process.stderr.write = originalWrite; debug.enable(originalNamespace); }); const timeoutMs = 100; log4js.configure({ appenders: { multi: { type: 'multiFile', base: 'logs/', property: 'label', extension: '.log', timeout: timeoutMs, }, }, categories: { default: { appenders: ['multi'], level: 'info' } }, }); const loggerD = log4js.getLogger('cheese'); loggerD.addContext('label', 'D'); loggerD.info('I am in logger D'); log4js.shutdown(() => { t.notOk( debugLogs.some( (s) => s.indexOf(`D not used for > ${timeoutMs} ms => close`) !== -1 ), 'should not have closed' ); t.ok( debugLogs.some((s) => s.indexOf('clearing timer for D') !== -1), 'should have cleared timers' ); t.match( debugLogs[debugLogs.length - 1], 'calling shutdown for D', 'should have called shutdown' ); t.end(); }); }); batch.test( 'should fail silently if loggingEvent property has no value', (t) => { t.teardown(async () => { await removeFiles('logs/E.log'); }); log4js.configure({ appenders: { multi: { type: 'multiFile', base: 'logs/', property: 'label', extension: '.log', }, }, categories: { default: { appenders: ['multi'], level: 'info' } }, }); const loggerE = log4js.getLogger(); loggerE.addContext('label', 'E'); loggerE.info('I am in logger E'); loggerE.removeContext('label'); loggerE.info('I am not in logger E'); loggerE.addContext('label', null); loggerE.info('I am also not in logger E'); log4js.shutdown(() => { const contents = fs.readFileSync('logs/E.log', 'utf-8'); t.match(contents, 'I am in logger E'); t.notMatch(contents, 'I am not in logger E'); t.notMatch(contents, 'I am also not in logger E'); t.end(); }); } ); batch.test('should pass options to rolling file stream', (t) => { t.teardown(async () => { await removeFiles(['logs/F.log', 'logs/F.log.1', 'logs/F.log.2']); }); log4js.configure({ appenders: { multi: { type: 'multiFile', base: 'logs/', property: 'label', extension: '.log', maxLogSize: 30, backups: 2, layout: { type: 'messagePassThrough' }, }, }, categories: { default: { appenders: ['multi'], level: 'info' } }, }); const loggerF = log4js.getLogger(); loggerF.addContext('label', 'F'); loggerF.info('Being in logger F is the best.'); loggerF.info('I am also in logger F, awesome'); loggerF.info('I am in logger F'); log4js.shutdown(() => { let contents = fs.readFileSync('logs/F.log', 'utf-8'); t.match(contents, 'I am in logger F'); contents = fs.readFileSync('logs/F.log.1', 'utf-8'); t.match(contents, 'I am also in logger F'); contents = fs.readFileSync('logs/F.log.2', 'utf-8'); t.match(contents, 'Being in logger F is the best'); t.end(); }); }); batch.test('should inherit config from category hierarchy', (t) => { t.teardown(async () => { await removeFiles('logs/test.someTest.log'); }); log4js.configure({ appenders: { out: { type: 'stdout' }, test: { type: 'multiFile', base: 'logs/', property: 'categoryName', extension: '.log', }, }, categories: { default: { appenders: ['out'], level: 'info' }, test: { appenders: ['test'], level: 'debug' }, }, }); const testLogger = log4js.getLogger('test.someTest'); testLogger.debug('This should go to the file'); log4js.shutdown(() => { const contents = fs.readFileSync('logs/test.someTest.log', 'utf-8'); t.match(contents, 'This should go to the file'); t.end(); }); }); batch.test('should shutdown safely even if it is not used', (t) => { log4js.configure({ appenders: { out: { type: 'stdout' }, test: { type: 'multiFile', base: 'logs/', property: 'categoryName', extension: '.log', }, }, categories: { default: { appenders: ['out'], level: 'info' }, test: { appenders: ['test'], level: 'debug' }, }, }); log4js.shutdown(() => { t.ok('callback is called'); t.end(); }); }); batch.teardown(async () => { try { const files = fs.readdirSync('logs'); await removeFiles(files.map((filename) => `logs/${filename}`)); fs.rmdirSync('logs'); } catch (e) { // doesn't matter } }); batch.end(); });
-1
log4js-node/log4js-node
1,386
add maxLength to recording - closes #1385
gabriel-cloud
"2023-05-19T22:07:06"
"2023-06-07T01:27:16"
26dcec62f9677dceba57de8cd717ff91447781c7
c5d71e9212ed374122dfd783d2518379d5beca13
add maxLength to recording - closes #1385.
./lib/levels.js
const configuration = require('./configuration'); const validColours = [ 'white', 'grey', 'black', 'blue', 'cyan', 'green', 'magenta', 'red', 'yellow', ]; class Level { constructor(level, levelStr, colour) { this.level = level; this.levelStr = levelStr; this.colour = colour; } toString() { return this.levelStr; } /** * converts given String to corresponding Level * @param {(Level|string)} sArg -- String value of Level OR Log4js.Level * @param {Level} [defaultLevel] -- default Level, if no String representation * @return {Level} */ static getLevel(sArg, defaultLevel) { if (!sArg) { return defaultLevel; } if (sArg instanceof Level) { return sArg; } // a json-serialised level won't be an instance of Level (see issue #768) if (sArg instanceof Object && sArg.levelStr) { sArg = sArg.levelStr; } return Level[sArg.toString().toUpperCase()] || defaultLevel; } static addLevels(customLevels) { if (customLevels) { const levels = Object.keys(customLevels); levels.forEach((l) => { const levelStr = l.toUpperCase(); Level[levelStr] = new Level( customLevels[l].value, levelStr, customLevels[l].colour ); const existingLevelIndex = Level.levels.findIndex( (lvl) => lvl.levelStr === levelStr ); if (existingLevelIndex > -1) { Level.levels[existingLevelIndex] = Level[levelStr]; } else { Level.levels.push(Level[levelStr]); } }); Level.levels.sort((a, b) => a.level - b.level); } } isLessThanOrEqualTo(otherLevel) { if (typeof otherLevel === 'string') { otherLevel = Level.getLevel(otherLevel); } return this.level <= otherLevel.level; } isGreaterThanOrEqualTo(otherLevel) { if (typeof otherLevel === 'string') { otherLevel = Level.getLevel(otherLevel); } return this.level >= otherLevel.level; } isEqualTo(otherLevel) { if (typeof otherLevel === 'string') { otherLevel = Level.getLevel(otherLevel); } return this.level === otherLevel.level; } } Level.levels = []; Level.addLevels({ ALL: { value: Number.MIN_VALUE, colour: 'grey' }, TRACE: { value: 5000, colour: 'blue' }, DEBUG: { value: 10000, colour: 'cyan' }, INFO: { value: 20000, colour: 'green' }, WARN: { value: 30000, colour: 'yellow' }, ERROR: { value: 40000, colour: 'red' }, FATAL: { value: 50000, colour: 'magenta' }, MARK: { value: 9007199254740992, colour: 'grey' }, // 2^53 OFF: { value: Number.MAX_VALUE, colour: 'grey' }, }); configuration.addListener((config) => { const levelConfig = config.levels; if (levelConfig) { configuration.throwExceptionIf( config, configuration.not(configuration.anObject(levelConfig)), 'levels must be an object' ); const newLevels = Object.keys(levelConfig); newLevels.forEach((l) => { configuration.throwExceptionIf( config, configuration.not(configuration.validIdentifier(l)), `level name "${l}" is not a valid identifier (must start with a letter, only contain A-Z,a-z,0-9,_)` ); configuration.throwExceptionIf( config, configuration.not(configuration.anObject(levelConfig[l])), `level "${l}" must be an object` ); configuration.throwExceptionIf( config, configuration.not(levelConfig[l].value), `level "${l}" must have a 'value' property` ); configuration.throwExceptionIf( config, configuration.not(configuration.anInteger(levelConfig[l].value)), `level "${l}".value must have an integer value` ); configuration.throwExceptionIf( config, configuration.not(levelConfig[l].colour), `level "${l}" must have a 'colour' property` ); configuration.throwExceptionIf( config, configuration.not(validColours.indexOf(levelConfig[l].colour) > -1), `level "${l}".colour must be one of ${validColours.join(', ')}` ); }); } }); configuration.addListener((config) => { Level.addLevels(config.levels); }); module.exports = Level;
const configuration = require('./configuration'); const validColours = [ 'white', 'grey', 'black', 'blue', 'cyan', 'green', 'magenta', 'red', 'yellow', ]; class Level { constructor(level, levelStr, colour) { this.level = level; this.levelStr = levelStr; this.colour = colour; } toString() { return this.levelStr; } /** * converts given String to corresponding Level * @param {(Level|string)} sArg -- String value of Level OR Log4js.Level * @param {Level} [defaultLevel] -- default Level, if no String representation * @return {Level} */ static getLevel(sArg, defaultLevel) { if (!sArg) { return defaultLevel; } if (sArg instanceof Level) { return sArg; } // a json-serialised level won't be an instance of Level (see issue #768) if (sArg instanceof Object && sArg.levelStr) { sArg = sArg.levelStr; } return Level[sArg.toString().toUpperCase()] || defaultLevel; } static addLevels(customLevels) { if (customLevels) { const levels = Object.keys(customLevels); levels.forEach((l) => { const levelStr = l.toUpperCase(); Level[levelStr] = new Level( customLevels[l].value, levelStr, customLevels[l].colour ); const existingLevelIndex = Level.levels.findIndex( (lvl) => lvl.levelStr === levelStr ); if (existingLevelIndex > -1) { Level.levels[existingLevelIndex] = Level[levelStr]; } else { Level.levels.push(Level[levelStr]); } }); Level.levels.sort((a, b) => a.level - b.level); } } isLessThanOrEqualTo(otherLevel) { if (typeof otherLevel === 'string') { otherLevel = Level.getLevel(otherLevel); } return this.level <= otherLevel.level; } isGreaterThanOrEqualTo(otherLevel) { if (typeof otherLevel === 'string') { otherLevel = Level.getLevel(otherLevel); } return this.level >= otherLevel.level; } isEqualTo(otherLevel) { if (typeof otherLevel === 'string') { otherLevel = Level.getLevel(otherLevel); } return this.level === otherLevel.level; } } Level.levels = []; Level.addLevels({ ALL: { value: Number.MIN_VALUE, colour: 'grey' }, TRACE: { value: 5000, colour: 'blue' }, DEBUG: { value: 10000, colour: 'cyan' }, INFO: { value: 20000, colour: 'green' }, WARN: { value: 30000, colour: 'yellow' }, ERROR: { value: 40000, colour: 'red' }, FATAL: { value: 50000, colour: 'magenta' }, MARK: { value: 9007199254740992, colour: 'grey' }, // 2^53 OFF: { value: Number.MAX_VALUE, colour: 'grey' }, }); configuration.addListener((config) => { const levelConfig = config.levels; if (levelConfig) { configuration.throwExceptionIf( config, configuration.not(configuration.anObject(levelConfig)), 'levels must be an object' ); const newLevels = Object.keys(levelConfig); newLevels.forEach((l) => { configuration.throwExceptionIf( config, configuration.not(configuration.validIdentifier(l)), `level name "${l}" is not a valid identifier (must start with a letter, only contain A-Z,a-z,0-9,_)` ); configuration.throwExceptionIf( config, configuration.not(configuration.anObject(levelConfig[l])), `level "${l}" must be an object` ); configuration.throwExceptionIf( config, configuration.not(levelConfig[l].value), `level "${l}" must have a 'value' property` ); configuration.throwExceptionIf( config, configuration.not(configuration.anInteger(levelConfig[l].value)), `level "${l}".value must have an integer value` ); configuration.throwExceptionIf( config, configuration.not(levelConfig[l].colour), `level "${l}" must have a 'colour' property` ); configuration.throwExceptionIf( config, configuration.not(validColours.indexOf(levelConfig[l].colour) > -1), `level "${l}".colour must be one of ${validColours.join(', ')}` ); }); } }); configuration.addListener((config) => { Level.addLevels(config.levels); }); module.exports = Level;
-1
log4js-node/log4js-node
1,386
add maxLength to recording - closes #1385
gabriel-cloud
"2023-05-19T22:07:06"
"2023-06-07T01:27:16"
26dcec62f9677dceba57de8cd717ff91447781c7
c5d71e9212ed374122dfd783d2518379d5beca13
add maxLength to recording - closes #1385.
./examples/logstashHTTP.js
const log4js = require('../lib/log4js'); log4js.configure({ appenders: { console: { type: 'console', }, logstash: { url: 'http://172.17.0.5:9200/_bulk', type: '@log4js-node/logstash-http', logType: 'application', logChannel: 'node', application: 'logstash-log4js', layout: { type: 'pattern', pattern: '%m', }, }, }, categories: { default: { appenders: ['console', 'logstash'], level: 'info' }, }, }); const logger = log4js.getLogger('myLogger'); logger.info('Test log message %s', 'arg1', 'arg2');
const log4js = require('../lib/log4js'); log4js.configure({ appenders: { console: { type: 'console', }, logstash: { url: 'http://172.17.0.5:9200/_bulk', type: '@log4js-node/logstash-http', logType: 'application', logChannel: 'node', application: 'logstash-log4js', layout: { type: 'pattern', pattern: '%m', }, }, }, categories: { default: { appenders: ['console', 'logstash'], level: 'info' }, }, }); const logger = log4js.getLogger('myLogger'); logger.info('Test log message %s', 'arg1', 'arg2');
-1
log4js-node/log4js-node
1,386
add maxLength to recording - closes #1385
gabriel-cloud
"2023-05-19T22:07:06"
"2023-06-07T01:27:16"
26dcec62f9677dceba57de8cd717ff91447781c7
c5d71e9212ed374122dfd783d2518379d5beca13
add maxLength to recording - closes #1385.
./examples/smtp-appender.js
// Note that smtp appender needs nodemailer to work. // If you haven't got nodemailer installed, you'll get cryptic // "cannot find module" errors when using the smtp appender const log4js = require('../lib/log4js'); log4js.configure({ appenders: { out: { type: 'console', }, mail: { type: '@log4js-node/smtp', recipients: 'logfilerecipient@logging.com', sendInterval: 5, transport: 'SMTP', SMTP: { host: 'smtp.gmail.com', secureConnection: true, port: 465, auth: { user: 'someone@gmail', pass: '********************', }, debug: true, }, }, }, categories: { default: { appenders: ['out'], level: 'info' }, mailer: { appenders: ['mail'], level: 'info' }, }, }); const log = log4js.getLogger('test'); const logmailer = log4js.getLogger('mailer'); function doTheLogging(x) { log.info('Logging something %d', x); logmailer.info('Logging something %d', x); } for (let i = 0; i < 500; i += 1) { doTheLogging(i); }
// Note that smtp appender needs nodemailer to work. // If you haven't got nodemailer installed, you'll get cryptic // "cannot find module" errors when using the smtp appender const log4js = require('../lib/log4js'); log4js.configure({ appenders: { out: { type: 'console', }, mail: { type: '@log4js-node/smtp', recipients: 'logfilerecipient@logging.com', sendInterval: 5, transport: 'SMTP', SMTP: { host: 'smtp.gmail.com', secureConnection: true, port: 465, auth: { user: 'someone@gmail', pass: '********************', }, debug: true, }, }, }, categories: { default: { appenders: ['out'], level: 'info' }, mailer: { appenders: ['mail'], level: 'info' }, }, }); const log = log4js.getLogger('test'); const logmailer = log4js.getLogger('mailer'); function doTheLogging(x) { log.info('Logging something %d', x); logmailer.info('Logging something %d', x); } for (let i = 0; i < 500; i += 1) { doTheLogging(i); }
-1
log4js-node/log4js-node
1,386
add maxLength to recording - closes #1385
gabriel-cloud
"2023-05-19T22:07:06"
"2023-06-07T01:27:16"
26dcec62f9677dceba57de8cd717ff91447781c7
c5d71e9212ed374122dfd783d2518379d5beca13
add maxLength to recording - closes #1385.
./docs/appenders.md
# Log4js - Appenders Appenders serialise log events to some form of output. They can write to files, send emails, send data over the network. All appenders have a `type` which determines which appender gets used. For example: ```javascript const log4js = require("log4js"); log4js.configure({ appenders: { out: { type: "stdout" }, app: { type: "file", filename: "application.log" }, }, categories: { default: { appenders: ["out", "app"], level: "debug" }, }, }); ``` This defines two appenders named 'out' and 'app'. 'out' uses the [stdout](stdout.md) appender which writes to standard out. 'app' uses the [file](file.md) appender, configured to write to 'application.log'. ## Core Appenders The following appenders are included with log4js. Some require extra dependencies that are not included as part of log4js (the [smtp](https://github.com/log4js-node/smtp) appender needs [nodemailer](https://www.npmjs.com/package/nodemailer) for example), and these will be noted in the docs for that appender. If you don't use those appenders, then you don't need the extra dependencies. - [categoryFilter](categoryFilter.md) - [console](console.md) - [dateFile](dateFile.md) - [file](file.md) - [fileSync](fileSync.md) - [logLevelFilter](logLevelFilter.md) - [multiFile](multiFile.md) - [multiprocess](multiprocess.md) - [noLogFilter](noLogFilter.md) - [recording](recording.md) - [stderr](stderr.md) - [stdout](stdout.md) - [tcp](tcp.md) - [tcp-server](tcp-server.md) ## Optional Appenders The following appenders are supported by log4js, but are no longer distributed with log4js core from version 3 onwards. - [gelf](https://github.com/log4js-node/gelf) - [hipchat](https://github.com/log4js-node/hipchat) - [logFaces-HTTP](https://github.com/log4js-node/logFaces-HTTP) - [logFaces-UDP](https://github.com/log4js-node/logFaces-UDP) - [loggly](https://github.com/log4js-node/loggly) - [logstashHTTP](https://github.com/log4js-node/logstashHTTP) - [logstashUDP](https://github.com/log4js-node/logstashUDP) - [mailgun](https://github.com/log4js-node/mailgun) - [rabbitmq](https://github.com/log4js-node/rabbitmq) - [redis](https://github.com/log4js-node/redis) - [slack](https://github.com/log4js-node/slack) - [smtp](https://github.com/log4js-node/smtp) For example, if you were previously using the gelf appender (`type: 'gelf'`) then you should add `@log4js-node/gelf` to your dependencies and change the type to `type: '@log4js-node/gelf'`. ## Other Appenders These appenders are maintained by its own authors and may be useful for you: - [udp](https://github.com/iassasin/log4js-udp-appender) ## Custom Appenders Log4js can load appenders from outside the core appenders. The `type` config value is used as a require path if no matching appender can be found. For example, the following configuration will attempt to load an appender from the module 'cheese/appender', passing the rest of the config for the appender to that module: ```javascript log4js.configure({ appenders: { gouda: { type: "cheese/appender", flavour: "tasty" } }, categories: { default: { appenders: ["gouda"], level: "debug" } }, }); ``` Log4js checks the following places (in this order) for appenders based on the type value: 1. The core appenders: `require('./appenders/' + type)` 2. node_modules: `require(type)` 3. relative to the main file of your application: `require(path.dirname(require.main.filename) + '/' + type)` 4. relative to the process' current working directory: `require(process.cwd() + '/' + type)` If you want to write your own appender, read the [documentation](writing-appenders.md) first. ## Advanced configuration If you've got a custom appender of your own, or are using webpack (or some other bundler), you may find it easier to pass in the appender module in the config instead of loading from the node.js require path. Here's an example: ```javascript const myAppenderModule = { configure: (config, layouts, findAppender, levels) => { /* ...your appender config... */ }, }; log4js.configure({ appenders: { custom: { type: myAppenderModule } }, categories: { default: { appenders: ["custom"], level: "debug" } }, }); ```
# Log4js - Appenders Appenders serialise log events to some form of output. They can write to files, send emails, send data over the network. All appenders have a `type` which determines which appender gets used. For example: ```javascript const log4js = require("log4js"); log4js.configure({ appenders: { out: { type: "stdout" }, app: { type: "file", filename: "application.log" }, }, categories: { default: { appenders: ["out", "app"], level: "debug" }, }, }); ``` This defines two appenders named 'out' and 'app'. 'out' uses the [stdout](stdout.md) appender which writes to standard out. 'app' uses the [file](file.md) appender, configured to write to 'application.log'. ## Core Appenders The following appenders are included with log4js. Some require extra dependencies that are not included as part of log4js (the [smtp](https://github.com/log4js-node/smtp) appender needs [nodemailer](https://www.npmjs.com/package/nodemailer) for example), and these will be noted in the docs for that appender. If you don't use those appenders, then you don't need the extra dependencies. - [categoryFilter](categoryFilter.md) - [console](console.md) - [dateFile](dateFile.md) - [file](file.md) - [fileSync](fileSync.md) - [logLevelFilter](logLevelFilter.md) - [multiFile](multiFile.md) - [multiprocess](multiprocess.md) - [noLogFilter](noLogFilter.md) - [recording](recording.md) - [stderr](stderr.md) - [stdout](stdout.md) - [tcp](tcp.md) - [tcp-server](tcp-server.md) ## Optional Appenders The following appenders are supported by log4js, but are no longer distributed with log4js core from version 3 onwards. - [gelf](https://github.com/log4js-node/gelf) - [hipchat](https://github.com/log4js-node/hipchat) - [logFaces-HTTP](https://github.com/log4js-node/logFaces-HTTP) - [logFaces-UDP](https://github.com/log4js-node/logFaces-UDP) - [loggly](https://github.com/log4js-node/loggly) - [logstashHTTP](https://github.com/log4js-node/logstashHTTP) - [logstashUDP](https://github.com/log4js-node/logstashUDP) - [mailgun](https://github.com/log4js-node/mailgun) - [rabbitmq](https://github.com/log4js-node/rabbitmq) - [redis](https://github.com/log4js-node/redis) - [slack](https://github.com/log4js-node/slack) - [smtp](https://github.com/log4js-node/smtp) For example, if you were previously using the gelf appender (`type: 'gelf'`) then you should add `@log4js-node/gelf` to your dependencies and change the type to `type: '@log4js-node/gelf'`. ## Other Appenders These appenders are maintained by its own authors and may be useful for you: - [udp](https://github.com/iassasin/log4js-udp-appender) ## Custom Appenders Log4js can load appenders from outside the core appenders. The `type` config value is used as a require path if no matching appender can be found. For example, the following configuration will attempt to load an appender from the module 'cheese/appender', passing the rest of the config for the appender to that module: ```javascript log4js.configure({ appenders: { gouda: { type: "cheese/appender", flavour: "tasty" } }, categories: { default: { appenders: ["gouda"], level: "debug" } }, }); ``` Log4js checks the following places (in this order) for appenders based on the type value: 1. The core appenders: `require('./appenders/' + type)` 2. node_modules: `require(type)` 3. relative to the main file of your application: `require(path.dirname(require.main.filename) + '/' + type)` 4. relative to the process' current working directory: `require(process.cwd() + '/' + type)` If you want to write your own appender, read the [documentation](writing-appenders.md) first. ## Advanced configuration If you've got a custom appender of your own, or are using webpack (or some other bundler), you may find it easier to pass in the appender module in the config instead of loading from the node.js require path. Here's an example: ```javascript const myAppenderModule = { configure: (config, layouts, findAppender, levels) => { /* ...your appender config... */ }, }; log4js.configure({ appenders: { custom: { type: myAppenderModule } }, categories: { default: { appenders: ["custom"], level: "debug" } }, }); ```
-1
log4js-node/log4js-node
1,386
add maxLength to recording - closes #1385
gabriel-cloud
"2023-05-19T22:07:06"
"2023-06-07T01:27:16"
26dcec62f9677dceba57de8cd717ff91447781c7
c5d71e9212ed374122dfd783d2518379d5beca13
add maxLength to recording - closes #1385.
./lib/appenders/index.js
const path = require('path'); const debug = require('debug')('log4js:appenders'); const configuration = require('../configuration'); const clustering = require('../clustering'); const levels = require('../levels'); const layouts = require('../layouts'); const adapters = require('./adapters'); // pre-load the core appenders so that webpack can find them const coreAppenders = new Map(); coreAppenders.set('console', require('./console')); coreAppenders.set('stdout', require('./stdout')); coreAppenders.set('stderr', require('./stderr')); coreAppenders.set('logLevelFilter', require('./logLevelFilter')); coreAppenders.set('categoryFilter', require('./categoryFilter')); coreAppenders.set('noLogFilter', require('./noLogFilter')); coreAppenders.set('file', require('./file')); coreAppenders.set('dateFile', require('./dateFile')); coreAppenders.set('fileSync', require('./fileSync')); coreAppenders.set('tcp', require('./tcp')); const appenders = new Map(); const tryLoading = (modulePath, config) => { let resolvedPath; try { const modulePathCJS = `${modulePath}.cjs`; resolvedPath = require.resolve(modulePathCJS); debug('Loading module from ', modulePathCJS); } catch (e) { resolvedPath = modulePath; debug('Loading module from ', modulePath); } try { // eslint-disable-next-line global-require, import/no-dynamic-require return require(resolvedPath); } catch (e) { // if the module was found, and we still got an error, then raise it configuration.throwExceptionIf( config, e.code !== 'MODULE_NOT_FOUND', `appender "${modulePath}" could not be loaded (error was: ${e})` ); return undefined; } }; const loadAppenderModule = (type, config) => coreAppenders.get(type) || tryLoading(`./${type}`, config) || tryLoading(type, config) || (require.main && require.main.filename && tryLoading(path.join(path.dirname(require.main.filename), type), config)) || tryLoading(path.join(process.cwd(), type), config); const appendersLoading = new Set(); const getAppender = (name, config) => { if (appenders.has(name)) return appenders.get(name); if (!config.appenders[name]) return false; if (appendersLoading.has(name)) throw new Error(`Dependency loop detected for appender ${name}.`); appendersLoading.add(name); debug(`Creating appender ${name}`); // eslint-disable-next-line no-use-before-define const appender = createAppender(name, config); appendersLoading.delete(name); appenders.set(name, appender); return appender; }; const createAppender = (name, config) => { const appenderConfig = config.appenders[name]; const appenderModule = appenderConfig.type.configure ? appenderConfig.type : loadAppenderModule(appenderConfig.type, config); configuration.throwExceptionIf( config, configuration.not(appenderModule), `appender "${name}" is not valid (type "${appenderConfig.type}" could not be found)` ); if (appenderModule.appender) { process.emitWarning( `Appender ${appenderConfig.type} exports an appender function.`, 'DeprecationWarning', 'log4js-node-DEP0001' ); debug( '[log4js-node-DEP0001]', `DEPRECATION: Appender ${appenderConfig.type} exports an appender function.` ); } if (appenderModule.shutdown) { process.emitWarning( `Appender ${appenderConfig.type} exports a shutdown function.`, 'DeprecationWarning', 'log4js-node-DEP0002' ); debug( '[log4js-node-DEP0002]', `DEPRECATION: Appender ${appenderConfig.type} exports a shutdown function.` ); } debug(`${name}: clustering.isMaster ? ${clustering.isMaster()}`); debug( // eslint-disable-next-line global-require `${name}: appenderModule is ${require('util').inspect(appenderModule)}` ); return clustering.onlyOnMaster( () => { debug( `calling appenderModule.configure for ${name} / ${appenderConfig.type}` ); return appenderModule.configure( adapters.modifyConfig(appenderConfig), layouts, (appender) => getAppender(appender, config), levels ); }, /* istanbul ignore next: fn never gets called by non-master yet needed to pass config validation */ () => {} ); }; const setup = (config) => { appenders.clear(); appendersLoading.clear(); if (!config) { return; } const usedAppenders = []; Object.values(config.categories).forEach((category) => { usedAppenders.push(...category.appenders); }); Object.keys(config.appenders).forEach((name) => { // dodgy hard-coding of special case for tcp-server and multiprocess which may not have // any categories associated with it, but needs to be started up anyway if ( usedAppenders.includes(name) || config.appenders[name].type === 'tcp-server' || config.appenders[name].type === 'multiprocess' ) { getAppender(name, config); } }); }; const init = () => { setup(); }; init(); configuration.addListener((config) => { configuration.throwExceptionIf( config, configuration.not(configuration.anObject(config.appenders)), 'must have a property "appenders" of type object.' ); const appenderNames = Object.keys(config.appenders); configuration.throwExceptionIf( config, configuration.not(appenderNames.length), 'must define at least one appender.' ); appenderNames.forEach((name) => { configuration.throwExceptionIf( config, configuration.not(config.appenders[name].type), `appender "${name}" is not valid (must be an object with property "type")` ); }); }); configuration.addListener(setup); module.exports = appenders; module.exports.init = init;
const path = require('path'); const debug = require('debug')('log4js:appenders'); const configuration = require('../configuration'); const clustering = require('../clustering'); const levels = require('../levels'); const layouts = require('../layouts'); const adapters = require('./adapters'); // pre-load the core appenders so that webpack can find them const coreAppenders = new Map(); coreAppenders.set('console', require('./console')); coreAppenders.set('stdout', require('./stdout')); coreAppenders.set('stderr', require('./stderr')); coreAppenders.set('logLevelFilter', require('./logLevelFilter')); coreAppenders.set('categoryFilter', require('./categoryFilter')); coreAppenders.set('noLogFilter', require('./noLogFilter')); coreAppenders.set('file', require('./file')); coreAppenders.set('dateFile', require('./dateFile')); coreAppenders.set('fileSync', require('./fileSync')); coreAppenders.set('tcp', require('./tcp')); const appenders = new Map(); const tryLoading = (modulePath, config) => { let resolvedPath; try { const modulePathCJS = `${modulePath}.cjs`; resolvedPath = require.resolve(modulePathCJS); debug('Loading module from ', modulePathCJS); } catch (e) { resolvedPath = modulePath; debug('Loading module from ', modulePath); } try { // eslint-disable-next-line global-require, import/no-dynamic-require return require(resolvedPath); } catch (e) { // if the module was found, and we still got an error, then raise it configuration.throwExceptionIf( config, e.code !== 'MODULE_NOT_FOUND', `appender "${modulePath}" could not be loaded (error was: ${e})` ); return undefined; } }; const loadAppenderModule = (type, config) => coreAppenders.get(type) || tryLoading(`./${type}`, config) || tryLoading(type, config) || (require.main && require.main.filename && tryLoading(path.join(path.dirname(require.main.filename), type), config)) || tryLoading(path.join(process.cwd(), type), config); const appendersLoading = new Set(); const getAppender = (name, config) => { if (appenders.has(name)) return appenders.get(name); if (!config.appenders[name]) return false; if (appendersLoading.has(name)) throw new Error(`Dependency loop detected for appender ${name}.`); appendersLoading.add(name); debug(`Creating appender ${name}`); // eslint-disable-next-line no-use-before-define const appender = createAppender(name, config); appendersLoading.delete(name); appenders.set(name, appender); return appender; }; const createAppender = (name, config) => { const appenderConfig = config.appenders[name]; const appenderModule = appenderConfig.type.configure ? appenderConfig.type : loadAppenderModule(appenderConfig.type, config); configuration.throwExceptionIf( config, configuration.not(appenderModule), `appender "${name}" is not valid (type "${appenderConfig.type}" could not be found)` ); if (appenderModule.appender) { process.emitWarning( `Appender ${appenderConfig.type} exports an appender function.`, 'DeprecationWarning', 'log4js-node-DEP0001' ); debug( '[log4js-node-DEP0001]', `DEPRECATION: Appender ${appenderConfig.type} exports an appender function.` ); } if (appenderModule.shutdown) { process.emitWarning( `Appender ${appenderConfig.type} exports a shutdown function.`, 'DeprecationWarning', 'log4js-node-DEP0002' ); debug( '[log4js-node-DEP0002]', `DEPRECATION: Appender ${appenderConfig.type} exports a shutdown function.` ); } debug(`${name}: clustering.isMaster ? ${clustering.isMaster()}`); debug( // eslint-disable-next-line global-require `${name}: appenderModule is ${require('util').inspect(appenderModule)}` ); return clustering.onlyOnMaster( () => { debug( `calling appenderModule.configure for ${name} / ${appenderConfig.type}` ); return appenderModule.configure( adapters.modifyConfig(appenderConfig), layouts, (appender) => getAppender(appender, config), levels ); }, /* istanbul ignore next: fn never gets called by non-master yet needed to pass config validation */ () => {} ); }; const setup = (config) => { appenders.clear(); appendersLoading.clear(); if (!config) { return; } const usedAppenders = []; Object.values(config.categories).forEach((category) => { usedAppenders.push(...category.appenders); }); Object.keys(config.appenders).forEach((name) => { // dodgy hard-coding of special case for tcp-server and multiprocess which may not have // any categories associated with it, but needs to be started up anyway if ( usedAppenders.includes(name) || config.appenders[name].type === 'tcp-server' || config.appenders[name].type === 'multiprocess' ) { getAppender(name, config); } }); }; const init = () => { setup(); }; init(); configuration.addListener((config) => { configuration.throwExceptionIf( config, configuration.not(configuration.anObject(config.appenders)), 'must have a property "appenders" of type object.' ); const appenderNames = Object.keys(config.appenders); configuration.throwExceptionIf( config, configuration.not(appenderNames.length), 'must define at least one appender.' ); appenderNames.forEach((name) => { configuration.throwExceptionIf( config, configuration.not(config.appenders[name].type), `appender "${name}" is not valid (must be an object with property "type")` ); }); }); configuration.addListener(setup); module.exports = appenders; module.exports.init = init;
-1
log4js-node/log4js-node
1,386
add maxLength to recording - closes #1385
gabriel-cloud
"2023-05-19T22:07:06"
"2023-06-07T01:27:16"
26dcec62f9677dceba57de8cd717ff91447781c7
c5d71e9212ed374122dfd783d2518379d5beca13
add maxLength to recording - closes #1385.
./examples/slack-appender.js
// Note that slack appender needs slack-node package to work. const log4js = require('../lib/log4js'); log4js.configure({ appenders: { slack: { type: '@log4js-node/slack', token: 'TOKEN', channel_id: '#CHANNEL', username: 'USERNAME', format: 'text', icon_url: 'ICON_URL', }, }, categories: { default: { appenders: ['slack'], level: 'info' }, }, }); const logger = log4js.getLogger('slack'); logger.warn('Test Warn message'); logger.info('Test Info message'); logger.debug('Test Debug Message'); logger.trace('Test Trace Message'); logger.fatal('Test Fatal Message'); logger.error('Test Error Message');
// Note that slack appender needs slack-node package to work. const log4js = require('../lib/log4js'); log4js.configure({ appenders: { slack: { type: '@log4js-node/slack', token: 'TOKEN', channel_id: '#CHANNEL', username: 'USERNAME', format: 'text', icon_url: 'ICON_URL', }, }, categories: { default: { appenders: ['slack'], level: 'info' }, }, }); const logger = log4js.getLogger('slack'); logger.warn('Test Warn message'); logger.info('Test Info message'); logger.debug('Test Debug Message'); logger.trace('Test Trace Message'); logger.fatal('Test Fatal Message'); logger.error('Test Error Message');
-1
log4js-node/log4js-node
1,386
add maxLength to recording - closes #1385
gabriel-cloud
"2023-05-19T22:07:06"
"2023-06-07T01:27:16"
26dcec62f9677dceba57de8cd717ff91447781c7
c5d71e9212ed374122dfd783d2518379d5beca13
add maxLength to recording - closes #1385.
./lib/appenders/logLevelFilter.js
function logLevelFilter(minLevelString, maxLevelString, appender, levels) { const minLevel = levels.getLevel(minLevelString); const maxLevel = levels.getLevel(maxLevelString, levels.FATAL); return (logEvent) => { const eventLevel = logEvent.level; if ( minLevel.isLessThanOrEqualTo(eventLevel) && maxLevel.isGreaterThanOrEqualTo(eventLevel) ) { appender(logEvent); } }; } function configure(config, layouts, findAppender, levels) { const appender = findAppender(config.appender); return logLevelFilter(config.level, config.maxLevel, appender, levels); } module.exports.configure = configure;
function logLevelFilter(minLevelString, maxLevelString, appender, levels) { const minLevel = levels.getLevel(minLevelString); const maxLevel = levels.getLevel(maxLevelString, levels.FATAL); return (logEvent) => { const eventLevel = logEvent.level; if ( minLevel.isLessThanOrEqualTo(eventLevel) && maxLevel.isGreaterThanOrEqualTo(eventLevel) ) { appender(logEvent); } }; } function configure(config, layouts, findAppender, levels) { const appender = findAppender(config.appender); return logLevelFilter(config.level, config.maxLevel, appender, levels); } module.exports.configure = configure;
-1
log4js-node/log4js-node
1,386
add maxLength to recording - closes #1385
gabriel-cloud
"2023-05-19T22:07:06"
"2023-06-07T01:27:16"
26dcec62f9677dceba57de8cd717ff91447781c7
c5d71e9212ed374122dfd783d2518379d5beca13
add maxLength to recording - closes #1385.
./test/multiprocess-worker.js
if (process.argv.indexOf('start-multiprocess-worker') >= 0) { const log4js = require('../lib/log4js'); const port = parseInt(process.argv[process.argv.length - 1], 10); log4js.configure({ appenders: { multi: { type: 'multiprocess', mode: 'worker', loggerPort: port }, }, categories: { default: { appenders: ['multi'], level: 'debug' } }, }); log4js.getLogger('worker').info('Logging from worker'); log4js.shutdown(() => { process.send('worker is done'); }); }
if (process.argv.indexOf('start-multiprocess-worker') >= 0) { const log4js = require('../lib/log4js'); const port = parseInt(process.argv[process.argv.length - 1], 10); log4js.configure({ appenders: { multi: { type: 'multiprocess', mode: 'worker', loggerPort: port }, }, categories: { default: { appenders: ['multi'], level: 'debug' } }, }); log4js.getLogger('worker').info('Logging from worker'); log4js.shutdown(() => { process.send('worker is done'); }); }
-1
log4js-node/log4js-node
1,386
add maxLength to recording - closes #1385
gabriel-cloud
"2023-05-19T22:07:06"
"2023-06-07T01:27:16"
26dcec62f9677dceba57de8cd717ff91447781c7
c5d71e9212ed374122dfd783d2518379d5beca13
add maxLength to recording - closes #1385.
./test/tap/connect-logger-test.js
/* eslint max-classes-per-file: ["error", 2] */ const { test } = require('tap'); const EE = require('events').EventEmitter; const levels = require('../../lib/levels'); class MockLogger { constructor() { this.level = levels.TRACE; this.messages = []; this.log = function (level, message) { this.messages.push({ level, message }); }; this.isLevelEnabled = function (level) { return level.isGreaterThanOrEqualTo(this.level); }; } } function MockRequest(remoteAddr, method, originalUrl, headers, url, custom) { this.socket = { remoteAddress: remoteAddr }; this.originalUrl = originalUrl; this.url = url; this.method = method; this.httpVersionMajor = '5'; this.httpVersionMinor = '0'; this.headers = headers || {}; if (custom) { for (const key of Object.keys(custom)) { this[key] = custom[key]; } } const self = this; Object.keys(this.headers).forEach((key) => { self.headers[key.toLowerCase()] = self.headers[key]; }); } class MockResponse extends EE { constructor() { super(); this.cachedHeaders = {}; } end() { this.emit('finish'); } setHeader(key, value) { this.cachedHeaders[key.toLowerCase()] = value; } getHeader(key) { return this.cachedHeaders[key.toLowerCase()]; } writeHead(code /* , headers */) { this.statusCode = code; } } function request( cl, method, originalUrl, code, reqHeaders, resHeaders, next, url, custom = undefined ) { const req = new MockRequest( 'my.remote.addr', method, originalUrl, reqHeaders, url, custom ); const res = new MockResponse(); if (next) { next = next.bind(null, req, res, () => {}); } else { next = () => {}; } cl(req, res, next); res.writeHead(code, resHeaders); res.end('chunk', 'encoding'); } test('log4js connect logger', (batch) => { const clm = require('../../lib/connect-logger'); batch.test('getConnectLoggerModule', (t) => { t.type(clm, 'function', 'should return a connect logger factory'); t.test( 'should take a log4js logger and return a "connect logger"', (assert) => { const ml = new MockLogger(); const cl = clm(ml); assert.type(cl, 'function'); assert.end(); } ); t.test('log events', (assert) => { const ml = new MockLogger(); const cl = clm(ml); request(cl, 'GET', 'http://url', 200); const { messages } = ml; assert.type(messages, 'Array'); assert.equal(messages.length, 1); assert.ok(levels.INFO.isEqualTo(messages[0].level)); assert.match(messages[0].message, 'GET'); assert.match(messages[0].message, 'http://url'); assert.match(messages[0].message, 'my.remote.addr'); assert.match(messages[0].message, '200'); assert.end(); }); t.test('log events with level below logging level', (assert) => { const ml = new MockLogger(); ml.level = levels.FATAL; const cl = clm(ml); request(cl, 'GET', 'http://url', 200); assert.type(ml.messages, 'Array'); assert.equal(ml.messages.length, 0); assert.end(); }); t.test('log events with non-default level and custom format', (assert) => { const ml = new MockLogger(); ml.level = levels.INFO; const cl = clm(ml, { level: levels.WARN, format: ':method :url' }); request(cl, 'GET', 'http://url', 200); const { messages } = ml; assert.type(messages, Array); assert.equal(messages.length, 1); assert.ok(levels.WARN.isEqualTo(messages[0].level)); assert.equal(messages[0].message, 'GET http://url'); assert.end(); }); t.test('adding multiple loggers should only log once', (assert) => { const ml = new MockLogger(); ml.level = levels.INFO; const cl = clm(ml, { level: levels.WARN, format: ':method :url' }); const nextLogger = clm(ml, { level: levels.INFO, format: ':method' }); request(cl, 'GET', 'http://url', 200, null, null, nextLogger); const { messages } = ml; assert.type(messages, Array); assert.equal(messages.length, 1); assert.ok(levels.WARN.isEqualTo(messages[0].level)); assert.equal(messages[0].message, 'GET http://url'); assert.end(); }); t.end(); }); batch.test('logger with options as string', (t) => { const ml = new MockLogger(); ml.level = levels.INFO; const cl = clm(ml, ':method :url'); request(cl, 'POST', 'http://meh', 200); const { messages } = ml; t.equal(messages[0].message, 'POST http://meh'); t.end(); }); batch.test('auto log levels', (t) => { const ml = new MockLogger(); ml.level = levels.INFO; const cl = clm(ml, { level: 'auto', format: ':method :url' }); request(cl, 'GET', 'http://meh', 200); request(cl, 'GET', 'http://meh', 201); request(cl, 'GET', 'http://meh', 302); request(cl, 'GET', 'http://meh', 404); request(cl, 'GET', 'http://meh', 500); const { messages } = ml; t.test('should use INFO for 2xx', (assert) => { assert.ok(levels.INFO.isEqualTo(messages[0].level)); assert.ok(levels.INFO.isEqualTo(messages[1].level)); assert.end(); }); t.test('should use WARN for 3xx', (assert) => { assert.ok(levels.WARN.isEqualTo(messages[2].level)); assert.end(); }); t.test('should use ERROR for 4xx', (assert) => { assert.ok(levels.ERROR.isEqualTo(messages[3].level)); assert.end(); }); t.test('should use ERROR for 5xx', (assert) => { assert.ok(levels.ERROR.isEqualTo(messages[4].level)); assert.end(); }); t.end(); }); batch.test('logger with status code rules applied', (t) => { const ml = new MockLogger(); ml.level = levels.DEBUG; const clr = [ { codes: [201, 304], level: levels.DEBUG.toString() }, { from: 200, to: 299, level: levels.DEBUG.toString() }, { from: 300, to: 399, level: levels.INFO.toString() }, ]; const cl = clm(ml, { level: 'auto', format: ':method :url', statusRules: clr, }); request(cl, 'GET', 'http://meh', 200); request(cl, 'GET', 'http://meh', 201); request(cl, 'GET', 'http://meh', 302); request(cl, 'GET', 'http://meh', 304); request(cl, 'GET', 'http://meh', 404); request(cl, 'GET', 'http://meh', 500); const { messages } = ml; t.test('should use DEBUG for 2xx', (assert) => { assert.ok(levels.DEBUG.isEqualTo(messages[0].level)); assert.ok(levels.DEBUG.isEqualTo(messages[1].level)); assert.end(); }); t.test('should use WARN for 3xx, DEBUG for 304', (assert) => { assert.ok(levels.INFO.isEqualTo(messages[2].level)); assert.ok(levels.DEBUG.isEqualTo(messages[3].level)); assert.end(); }); t.test('should use ERROR for 4xx', (assert) => { assert.ok(levels.ERROR.isEqualTo(messages[4].level)); assert.end(); }); t.test('should use ERROR for 5xx', (assert) => { assert.ok(levels.ERROR.isEqualTo(messages[5].level)); assert.end(); }); t.end(); }); batch.test('format using a function', (t) => { const ml = new MockLogger(); ml.level = levels.INFO; const cl = clm(ml, () => 'I was called'); request(cl, 'GET', 'http://blah', 200); t.equal(ml.messages[0].message, 'I was called'); t.end(); }); batch.test('format using a function that also uses tokens', (t) => { const ml = new MockLogger(); ml.level = levels.INFO; const cl = clm( ml, (req, res, tokenReplacer) => `${req.method} ${tokenReplacer(':status')}` ); request(cl, 'GET', 'http://blah', 200); t.equal(ml.messages[0].message, 'GET 200'); t.end(); }); batch.test( 'format using a function, but do not log anything if the function returns nothing', (t) => { const ml = new MockLogger(); ml.level = levels.INFO; const cl = clm(ml, () => null); request(cl, 'GET', 'http://blah', 200); t.equal(ml.messages.length, 0); t.end(); } ); batch.test('format that includes request headers', (t) => { const ml = new MockLogger(); ml.level = levels.INFO; const cl = clm(ml, ':req[Content-Type]'); request(cl, 'GET', 'http://blah', 200, { 'Content-Type': 'application/json', }); t.equal(ml.messages[0].message, 'application/json'); t.end(); }); batch.test('format that includes response headers', (t) => { const ml = new MockLogger(); ml.level = levels.INFO; const cl = clm(ml, ':res[Content-Type]'); request(cl, 'GET', 'http://blah', 200, null, { 'Content-Type': 'application/cheese', }); t.equal(ml.messages[0].message, 'application/cheese'); t.end(); }); batch.test('url token should check originalUrl and url', (t) => { const ml = new MockLogger(); const cl = clm(ml, ':url'); request(cl, 'GET', null, 200, null, null, null, 'http://cheese'); t.equal(ml.messages[0].message, 'http://cheese'); t.end(); }); batch.test('log events with custom token', (t) => { const ml = new MockLogger(); ml.level = levels.INFO; const cl = clm(ml, { level: levels.INFO, format: ':method :url :custom_string', tokens: [ { token: ':custom_string', replacement: 'fooBAR', }, ], }); request(cl, 'GET', 'http://url', 200); t.type(ml.messages, 'Array'); t.equal(ml.messages.length, 1); t.ok(levels.INFO.isEqualTo(ml.messages[0].level)); t.equal(ml.messages[0].message, 'GET http://url fooBAR'); t.end(); }); batch.test('log events with custom override token', (t) => { const ml = new MockLogger(); ml.level = levels.INFO; const cl = clm(ml, { level: levels.INFO, format: ':method :url :date', tokens: [ { token: ':date', replacement: '20150310', }, ], }); request(cl, 'GET', 'http://url', 200); t.type(ml.messages, 'Array'); t.equal(ml.messages.length, 1); t.ok(levels.INFO.isEqualTo(ml.messages[0].level)); t.equal(ml.messages[0].message, 'GET http://url 20150310'); t.end(); }); batch.test('log events with custom format', (t) => { const ml = new MockLogger(); const body = { say: 'hi!' }; ml.level = levels.INFO; const cl = clm(ml, { level: levels.INFO, format: (req, res, format) => format(`:method :url ${JSON.stringify(req.body)}`), }); request( cl, 'POST', 'http://url', 200, { 'Content-Type': 'application/json' }, null, null, null, { body } ); t.ok(levels.INFO.isEqualTo(ml.messages[0].level)); t.equal(ml.messages[0].message, `POST http://url ${JSON.stringify(body)}`); t.end(); }); batch.test( 'handle weird old node versions where socket contains socket', (t) => { const ml = new MockLogger(); const cl = clm(ml, ':remote-addr'); const req = new MockRequest(null, 'GET', 'http://blah'); req.socket = { socket: { remoteAddress: 'this is weird' } }; const res = new MockResponse(); cl(req, res, () => {}); res.writeHead(200, {}); res.end('chunk', 'encoding'); t.equal(ml.messages[0].message, 'this is weird'); t.end(); } ); batch.test( 'handles as soon as any of the events end/finish/error/close triggers (only once)', (t) => { const ml = new MockLogger(); const cl = clm(ml, ':remote-addr'); const req = new MockRequest(null, 'GET', 'http://blah'); req.socket = { socket: { remoteAddress: 'this is weird' } }; const res = new MockResponse(); cl(req, res, () => {}); res.writeHead(200, {}); t.equal(ml.messages.length, 0); res.emit('end'); res.emit('finish'); res.emit('error'); res.emit('close'); t.equal(ml.messages.length, 1); t.equal(ml.messages[0].message, 'this is weird'); t.end(); } ); batch.end(); });
/* eslint max-classes-per-file: ["error", 2] */ const { test } = require('tap'); const EE = require('events').EventEmitter; const levels = require('../../lib/levels'); class MockLogger { constructor() { this.level = levels.TRACE; this.messages = []; this.log = function (level, message) { this.messages.push({ level, message }); }; this.isLevelEnabled = function (level) { return level.isGreaterThanOrEqualTo(this.level); }; } } function MockRequest(remoteAddr, method, originalUrl, headers, url, custom) { this.socket = { remoteAddress: remoteAddr }; this.originalUrl = originalUrl; this.url = url; this.method = method; this.httpVersionMajor = '5'; this.httpVersionMinor = '0'; this.headers = headers || {}; if (custom) { for (const key of Object.keys(custom)) { this[key] = custom[key]; } } const self = this; Object.keys(this.headers).forEach((key) => { self.headers[key.toLowerCase()] = self.headers[key]; }); } class MockResponse extends EE { constructor() { super(); this.cachedHeaders = {}; } end() { this.emit('finish'); } setHeader(key, value) { this.cachedHeaders[key.toLowerCase()] = value; } getHeader(key) { return this.cachedHeaders[key.toLowerCase()]; } writeHead(code /* , headers */) { this.statusCode = code; } } function request( cl, method, originalUrl, code, reqHeaders, resHeaders, next, url, custom = undefined ) { const req = new MockRequest( 'my.remote.addr', method, originalUrl, reqHeaders, url, custom ); const res = new MockResponse(); if (next) { next = next.bind(null, req, res, () => {}); } else { next = () => {}; } cl(req, res, next); res.writeHead(code, resHeaders); res.end('chunk', 'encoding'); } test('log4js connect logger', (batch) => { const clm = require('../../lib/connect-logger'); batch.test('getConnectLoggerModule', (t) => { t.type(clm, 'function', 'should return a connect logger factory'); t.test( 'should take a log4js logger and return a "connect logger"', (assert) => { const ml = new MockLogger(); const cl = clm(ml); assert.type(cl, 'function'); assert.end(); } ); t.test('log events', (assert) => { const ml = new MockLogger(); const cl = clm(ml); request(cl, 'GET', 'http://url', 200); const { messages } = ml; assert.type(messages, 'Array'); assert.equal(messages.length, 1); assert.ok(levels.INFO.isEqualTo(messages[0].level)); assert.match(messages[0].message, 'GET'); assert.match(messages[0].message, 'http://url'); assert.match(messages[0].message, 'my.remote.addr'); assert.match(messages[0].message, '200'); assert.end(); }); t.test('log events with level below logging level', (assert) => { const ml = new MockLogger(); ml.level = levels.FATAL; const cl = clm(ml); request(cl, 'GET', 'http://url', 200); assert.type(ml.messages, 'Array'); assert.equal(ml.messages.length, 0); assert.end(); }); t.test('log events with non-default level and custom format', (assert) => { const ml = new MockLogger(); ml.level = levels.INFO; const cl = clm(ml, { level: levels.WARN, format: ':method :url' }); request(cl, 'GET', 'http://url', 200); const { messages } = ml; assert.type(messages, Array); assert.equal(messages.length, 1); assert.ok(levels.WARN.isEqualTo(messages[0].level)); assert.equal(messages[0].message, 'GET http://url'); assert.end(); }); t.test('adding multiple loggers should only log once', (assert) => { const ml = new MockLogger(); ml.level = levels.INFO; const cl = clm(ml, { level: levels.WARN, format: ':method :url' }); const nextLogger = clm(ml, { level: levels.INFO, format: ':method' }); request(cl, 'GET', 'http://url', 200, null, null, nextLogger); const { messages } = ml; assert.type(messages, Array); assert.equal(messages.length, 1); assert.ok(levels.WARN.isEqualTo(messages[0].level)); assert.equal(messages[0].message, 'GET http://url'); assert.end(); }); t.end(); }); batch.test('logger with options as string', (t) => { const ml = new MockLogger(); ml.level = levels.INFO; const cl = clm(ml, ':method :url'); request(cl, 'POST', 'http://meh', 200); const { messages } = ml; t.equal(messages[0].message, 'POST http://meh'); t.end(); }); batch.test('auto log levels', (t) => { const ml = new MockLogger(); ml.level = levels.INFO; const cl = clm(ml, { level: 'auto', format: ':method :url' }); request(cl, 'GET', 'http://meh', 200); request(cl, 'GET', 'http://meh', 201); request(cl, 'GET', 'http://meh', 302); request(cl, 'GET', 'http://meh', 404); request(cl, 'GET', 'http://meh', 500); const { messages } = ml; t.test('should use INFO for 2xx', (assert) => { assert.ok(levels.INFO.isEqualTo(messages[0].level)); assert.ok(levels.INFO.isEqualTo(messages[1].level)); assert.end(); }); t.test('should use WARN for 3xx', (assert) => { assert.ok(levels.WARN.isEqualTo(messages[2].level)); assert.end(); }); t.test('should use ERROR for 4xx', (assert) => { assert.ok(levels.ERROR.isEqualTo(messages[3].level)); assert.end(); }); t.test('should use ERROR for 5xx', (assert) => { assert.ok(levels.ERROR.isEqualTo(messages[4].level)); assert.end(); }); t.end(); }); batch.test('logger with status code rules applied', (t) => { const ml = new MockLogger(); ml.level = levels.DEBUG; const clr = [ { codes: [201, 304], level: levels.DEBUG.toString() }, { from: 200, to: 299, level: levels.DEBUG.toString() }, { from: 300, to: 399, level: levels.INFO.toString() }, ]; const cl = clm(ml, { level: 'auto', format: ':method :url', statusRules: clr, }); request(cl, 'GET', 'http://meh', 200); request(cl, 'GET', 'http://meh', 201); request(cl, 'GET', 'http://meh', 302); request(cl, 'GET', 'http://meh', 304); request(cl, 'GET', 'http://meh', 404); request(cl, 'GET', 'http://meh', 500); const { messages } = ml; t.test('should use DEBUG for 2xx', (assert) => { assert.ok(levels.DEBUG.isEqualTo(messages[0].level)); assert.ok(levels.DEBUG.isEqualTo(messages[1].level)); assert.end(); }); t.test('should use WARN for 3xx, DEBUG for 304', (assert) => { assert.ok(levels.INFO.isEqualTo(messages[2].level)); assert.ok(levels.DEBUG.isEqualTo(messages[3].level)); assert.end(); }); t.test('should use ERROR for 4xx', (assert) => { assert.ok(levels.ERROR.isEqualTo(messages[4].level)); assert.end(); }); t.test('should use ERROR for 5xx', (assert) => { assert.ok(levels.ERROR.isEqualTo(messages[5].level)); assert.end(); }); t.end(); }); batch.test('format using a function', (t) => { const ml = new MockLogger(); ml.level = levels.INFO; const cl = clm(ml, () => 'I was called'); request(cl, 'GET', 'http://blah', 200); t.equal(ml.messages[0].message, 'I was called'); t.end(); }); batch.test('format using a function that also uses tokens', (t) => { const ml = new MockLogger(); ml.level = levels.INFO; const cl = clm( ml, (req, res, tokenReplacer) => `${req.method} ${tokenReplacer(':status')}` ); request(cl, 'GET', 'http://blah', 200); t.equal(ml.messages[0].message, 'GET 200'); t.end(); }); batch.test( 'format using a function, but do not log anything if the function returns nothing', (t) => { const ml = new MockLogger(); ml.level = levels.INFO; const cl = clm(ml, () => null); request(cl, 'GET', 'http://blah', 200); t.equal(ml.messages.length, 0); t.end(); } ); batch.test('format that includes request headers', (t) => { const ml = new MockLogger(); ml.level = levels.INFO; const cl = clm(ml, ':req[Content-Type]'); request(cl, 'GET', 'http://blah', 200, { 'Content-Type': 'application/json', }); t.equal(ml.messages[0].message, 'application/json'); t.end(); }); batch.test('format that includes response headers', (t) => { const ml = new MockLogger(); ml.level = levels.INFO; const cl = clm(ml, ':res[Content-Type]'); request(cl, 'GET', 'http://blah', 200, null, { 'Content-Type': 'application/cheese', }); t.equal(ml.messages[0].message, 'application/cheese'); t.end(); }); batch.test('url token should check originalUrl and url', (t) => { const ml = new MockLogger(); const cl = clm(ml, ':url'); request(cl, 'GET', null, 200, null, null, null, 'http://cheese'); t.equal(ml.messages[0].message, 'http://cheese'); t.end(); }); batch.test('log events with custom token', (t) => { const ml = new MockLogger(); ml.level = levels.INFO; const cl = clm(ml, { level: levels.INFO, format: ':method :url :custom_string', tokens: [ { token: ':custom_string', replacement: 'fooBAR', }, ], }); request(cl, 'GET', 'http://url', 200); t.type(ml.messages, 'Array'); t.equal(ml.messages.length, 1); t.ok(levels.INFO.isEqualTo(ml.messages[0].level)); t.equal(ml.messages[0].message, 'GET http://url fooBAR'); t.end(); }); batch.test('log events with custom override token', (t) => { const ml = new MockLogger(); ml.level = levels.INFO; const cl = clm(ml, { level: levels.INFO, format: ':method :url :date', tokens: [ { token: ':date', replacement: '20150310', }, ], }); request(cl, 'GET', 'http://url', 200); t.type(ml.messages, 'Array'); t.equal(ml.messages.length, 1); t.ok(levels.INFO.isEqualTo(ml.messages[0].level)); t.equal(ml.messages[0].message, 'GET http://url 20150310'); t.end(); }); batch.test('log events with custom format', (t) => { const ml = new MockLogger(); const body = { say: 'hi!' }; ml.level = levels.INFO; const cl = clm(ml, { level: levels.INFO, format: (req, res, format) => format(`:method :url ${JSON.stringify(req.body)}`), }); request( cl, 'POST', 'http://url', 200, { 'Content-Type': 'application/json' }, null, null, null, { body } ); t.ok(levels.INFO.isEqualTo(ml.messages[0].level)); t.equal(ml.messages[0].message, `POST http://url ${JSON.stringify(body)}`); t.end(); }); batch.test( 'handle weird old node versions where socket contains socket', (t) => { const ml = new MockLogger(); const cl = clm(ml, ':remote-addr'); const req = new MockRequest(null, 'GET', 'http://blah'); req.socket = { socket: { remoteAddress: 'this is weird' } }; const res = new MockResponse(); cl(req, res, () => {}); res.writeHead(200, {}); res.end('chunk', 'encoding'); t.equal(ml.messages[0].message, 'this is weird'); t.end(); } ); batch.test( 'handles as soon as any of the events end/finish/error/close triggers (only once)', (t) => { const ml = new MockLogger(); const cl = clm(ml, ':remote-addr'); const req = new MockRequest(null, 'GET', 'http://blah'); req.socket = { socket: { remoteAddress: 'this is weird' } }; const res = new MockResponse(); cl(req, res, () => {}); res.writeHead(200, {}); t.equal(ml.messages.length, 0); res.emit('end'); res.emit('finish'); res.emit('error'); res.emit('close'); t.equal(ml.messages.length, 1); t.equal(ml.messages[0].message, 'this is weird'); t.end(); } ); batch.end(); });
-1
log4js-node/log4js-node
1,386
add maxLength to recording - closes #1385
gabriel-cloud
"2023-05-19T22:07:06"
"2023-06-07T01:27:16"
26dcec62f9677dceba57de8cd717ff91447781c7
c5d71e9212ed374122dfd783d2518379d5beca13
add maxLength to recording - closes #1385.
./examples/logstashUDP.js
const log4js = require('../lib/log4js'); /* Sample logstash config: udp { codec => json port => 10001 queue_size => 2 workers => 2 type => myAppType } */ log4js.configure({ appenders: { console: { type: 'console', }, logstash: { host: '127.0.0.1', port: 10001, type: 'logstashUDP', logType: 'myAppType', // Optional, defaults to 'category' fields: { // Optional, will be added to the 'fields' object in logstash field1: 'value1', field2: 'value2', }, layout: { type: 'pattern', pattern: '%m', }, }, }, categories: { default: { appenders: ['console', 'logstash'], level: 'info' }, }, }); const logger = log4js.getLogger('myLogger'); logger.info('Test log message %s', 'arg1', 'arg2');
const log4js = require('../lib/log4js'); /* Sample logstash config: udp { codec => json port => 10001 queue_size => 2 workers => 2 type => myAppType } */ log4js.configure({ appenders: { console: { type: 'console', }, logstash: { host: '127.0.0.1', port: 10001, type: 'logstashUDP', logType: 'myAppType', // Optional, defaults to 'category' fields: { // Optional, will be added to the 'fields' object in logstash field1: 'value1', field2: 'value2', }, layout: { type: 'pattern', pattern: '%m', }, }, }, categories: { default: { appenders: ['console', 'logstash'], level: 'info' }, }, }); const logger = log4js.getLogger('myLogger'); logger.info('Test log message %s', 'arg1', 'arg2');
-1
log4js-node/log4js-node
1,386
add maxLength to recording - closes #1385
gabriel-cloud
"2023-05-19T22:07:06"
"2023-06-07T01:27:16"
26dcec62f9677dceba57de8cd717ff91447781c7
c5d71e9212ed374122dfd783d2518379d5beca13
add maxLength to recording - closes #1385.
./test/tap/connect-context-test.js
/* eslint max-classes-per-file: ["error", 2] */ const { test } = require('tap'); const EE = require('events').EventEmitter; const levels = require('../../lib/levels'); class MockLogger { constructor() { this.level = levels.TRACE; this.context = {}; this.contexts = []; } log() { this.contexts.push(Object.assign({}, this.context)); // eslint-disable-line prefer-object-spread } isLevelEnabled(level) { return level.isGreaterThanOrEqualTo(this.level); } addContext(key, value) { this.context[key] = value; } removeContext(key) { delete this.context[key]; } } function MockRequest(remoteAddr, method, originalUrl) { this.socket = { remoteAddress: remoteAddr }; this.originalUrl = originalUrl; this.method = method; this.httpVersionMajor = '5'; this.httpVersionMinor = '0'; this.headers = {}; } class MockResponse extends EE { constructor(code) { super(); this.statusCode = code; this.cachedHeaders = {}; } end() { this.emit('finish'); } setHeader(key, value) { this.cachedHeaders[key.toLowerCase()] = value; } getHeader(key) { return this.cachedHeaders[key.toLowerCase()]; } writeHead(code /* , headers */) { this.statusCode = code; } } test('log4js connect logger', (batch) => { const clm = require('../../lib/connect-logger'); batch.test('with context config', (t) => { const ml = new MockLogger(); const cl = clm(ml, { context: true }); t.beforeEach((done) => { ml.contexts = []; if (typeof done === 'function') { done(); } }); t.test('response should be included in context', (assert) => { const { contexts } = ml; const req = new MockRequest( 'my.remote.addr', 'GET', 'http://url/hoge.png' ); // not gif const res = new MockResponse(200); cl(req, res, () => {}); res.end('chunk', 'encoding'); assert.type(contexts, 'Array'); assert.equal(contexts.length, 1); assert.type(contexts[0].res, MockResponse); assert.end(); }); t.end(); }); batch.test('without context config', (t) => { const ml = new MockLogger(); const cl = clm(ml, {}); t.beforeEach((done) => { ml.contexts = []; if (typeof done === 'function') { done(); } }); t.test('response should not be included in context', (assert) => { const { contexts } = ml; const req = new MockRequest( 'my.remote.addr', 'GET', 'http://url/hoge.png' ); // not gif const res = new MockResponse(200); cl(req, res, () => {}); res.end('chunk', 'encoding'); assert.type(contexts, 'Array'); assert.equal(contexts.length, 1); assert.type(contexts[0].res, undefined); assert.end(); }); t.end(); }); batch.end(); });
/* eslint max-classes-per-file: ["error", 2] */ const { test } = require('tap'); const EE = require('events').EventEmitter; const levels = require('../../lib/levels'); class MockLogger { constructor() { this.level = levels.TRACE; this.context = {}; this.contexts = []; } log() { this.contexts.push(Object.assign({}, this.context)); // eslint-disable-line prefer-object-spread } isLevelEnabled(level) { return level.isGreaterThanOrEqualTo(this.level); } addContext(key, value) { this.context[key] = value; } removeContext(key) { delete this.context[key]; } } function MockRequest(remoteAddr, method, originalUrl) { this.socket = { remoteAddress: remoteAddr }; this.originalUrl = originalUrl; this.method = method; this.httpVersionMajor = '5'; this.httpVersionMinor = '0'; this.headers = {}; } class MockResponse extends EE { constructor(code) { super(); this.statusCode = code; this.cachedHeaders = {}; } end() { this.emit('finish'); } setHeader(key, value) { this.cachedHeaders[key.toLowerCase()] = value; } getHeader(key) { return this.cachedHeaders[key.toLowerCase()]; } writeHead(code /* , headers */) { this.statusCode = code; } } test('log4js connect logger', (batch) => { const clm = require('../../lib/connect-logger'); batch.test('with context config', (t) => { const ml = new MockLogger(); const cl = clm(ml, { context: true }); t.beforeEach((done) => { ml.contexts = []; if (typeof done === 'function') { done(); } }); t.test('response should be included in context', (assert) => { const { contexts } = ml; const req = new MockRequest( 'my.remote.addr', 'GET', 'http://url/hoge.png' ); // not gif const res = new MockResponse(200); cl(req, res, () => {}); res.end('chunk', 'encoding'); assert.type(contexts, 'Array'); assert.equal(contexts.length, 1); assert.type(contexts[0].res, MockResponse); assert.end(); }); t.end(); }); batch.test('without context config', (t) => { const ml = new MockLogger(); const cl = clm(ml, {}); t.beforeEach((done) => { ml.contexts = []; if (typeof done === 'function') { done(); } }); t.test('response should not be included in context', (assert) => { const { contexts } = ml; const req = new MockRequest( 'my.remote.addr', 'GET', 'http://url/hoge.png' ); // not gif const res = new MockResponse(200); cl(req, res, () => {}); res.end('chunk', 'encoding'); assert.type(contexts, 'Array'); assert.equal(contexts.length, 1); assert.type(contexts[0].res, undefined); assert.end(); }); t.end(); }); batch.end(); });
-1
log4js-node/log4js-node
1,386
add maxLength to recording - closes #1385
gabriel-cloud
"2023-05-19T22:07:06"
"2023-06-07T01:27:16"
26dcec62f9677dceba57de8cd717ff91447781c7
c5d71e9212ed374122dfd783d2518379d5beca13
add maxLength to recording - closes #1385.
./lib/appenders/dateFile.js
const streams = require('streamroller'); const os = require('os'); const eol = os.EOL; function openTheStream(filename, pattern, options) { const stream = new streams.DateRollingFileStream(filename, pattern, options); stream.on('error', (err) => { // eslint-disable-next-line no-console console.error( 'log4js.dateFileAppender - Writing to file %s, error happened ', filename, err ); }); stream.on('drain', () => { process.emit('log4js:pause', false); }); return stream; } /** * File appender that rolls files according to a date pattern. * @param filename base filename. * @param pattern the format that will be added to the end of filename when rolling, * also used to check when to roll files - defaults to '.yyyy-MM-dd' * @param layout layout function for log messages - defaults to basicLayout * @param options - options to be passed to the underlying stream * @param timezoneOffset - optional timezone offset in minutes (default system local) */ function appender(filename, pattern, layout, options, timezoneOffset) { // the options for file appender use maxLogSize, but the docs say any file appender // options should work for dateFile as well. options.maxSize = options.maxLogSize; const writer = openTheStream(filename, pattern, options); const app = function (logEvent) { if (!writer.writable) { return; } if (!writer.write(layout(logEvent, timezoneOffset) + eol, 'utf8')) { process.emit('log4js:pause', true); } }; app.shutdown = function (complete) { writer.end('', 'utf-8', complete); }; return app; } function configure(config, layouts) { let layout = layouts.basicLayout; if (config.layout) { layout = layouts.layout(config.layout.type, config.layout); } if (!config.alwaysIncludePattern) { config.alwaysIncludePattern = false; } // security default (instead of relying on streamroller default) config.mode = config.mode || 0o600; return appender( config.filename, config.pattern, layout, config, config.timezoneOffset ); } module.exports.configure = configure;
const streams = require('streamroller'); const os = require('os'); const eol = os.EOL; function openTheStream(filename, pattern, options) { const stream = new streams.DateRollingFileStream(filename, pattern, options); stream.on('error', (err) => { // eslint-disable-next-line no-console console.error( 'log4js.dateFileAppender - Writing to file %s, error happened ', filename, err ); }); stream.on('drain', () => { process.emit('log4js:pause', false); }); return stream; } /** * File appender that rolls files according to a date pattern. * @param filename base filename. * @param pattern the format that will be added to the end of filename when rolling, * also used to check when to roll files - defaults to '.yyyy-MM-dd' * @param layout layout function for log messages - defaults to basicLayout * @param options - options to be passed to the underlying stream * @param timezoneOffset - optional timezone offset in minutes (default system local) */ function appender(filename, pattern, layout, options, timezoneOffset) { // the options for file appender use maxLogSize, but the docs say any file appender // options should work for dateFile as well. options.maxSize = options.maxLogSize; const writer = openTheStream(filename, pattern, options); const app = function (logEvent) { if (!writer.writable) { return; } if (!writer.write(layout(logEvent, timezoneOffset) + eol, 'utf8')) { process.emit('log4js:pause', true); } }; app.shutdown = function (complete) { writer.end('', 'utf-8', complete); }; return app; } function configure(config, layouts) { let layout = layouts.basicLayout; if (config.layout) { layout = layouts.layout(config.layout.type, config.layout); } if (!config.alwaysIncludePattern) { config.alwaysIncludePattern = false; } // security default (instead of relying on streamroller default) config.mode = config.mode || 0o600; return appender( config.filename, config.pattern, layout, config, config.timezoneOffset ); } module.exports.configure = configure;
-1
log4js-node/log4js-node
1,386
add maxLength to recording - closes #1385
gabriel-cloud
"2023-05-19T22:07:06"
"2023-06-07T01:27:16"
26dcec62f9677dceba57de8cd717ff91447781c7
c5d71e9212ed374122dfd783d2518379d5beca13
add maxLength to recording - closes #1385.
./test/tap/no-cluster-test.js
const { test } = require('tap'); const proxyquire = require('proxyquire'); test('clustering is disabled if cluster is not present', (t) => { const log4js = proxyquire('../../lib/log4js', { cluster: null }); const recorder = require('../../lib/appenders/recording'); log4js.configure({ appenders: { vcr: { type: 'recording' } }, categories: { default: { appenders: ['vcr'], level: 'debug' } }, }); log4js.getLogger().info('it should still work'); const events = recorder.replay(); t.equal(events[0].data[0], 'it should still work'); t.end(); });
const { test } = require('tap'); const proxyquire = require('proxyquire'); test('clustering is disabled if cluster is not present', (t) => { const log4js = proxyquire('../../lib/log4js', { cluster: null }); const recorder = require('../../lib/appenders/recording'); log4js.configure({ appenders: { vcr: { type: 'recording' } }, categories: { default: { appenders: ['vcr'], level: 'debug' } }, }); log4js.getLogger().info('it should still work'); const events = recorder.replay(); t.equal(events[0].data[0], 'it should still work'); t.end(); });
-1
log4js-node/log4js-node
1,386
add maxLength to recording - closes #1385
gabriel-cloud
"2023-05-19T22:07:06"
"2023-06-07T01:27:16"
26dcec62f9677dceba57de8cd717ff91447781c7
c5d71e9212ed374122dfd783d2518379d5beca13
add maxLength to recording - closes #1385.
./lib/appenders/file.js
const debug = require('debug')('log4js:file'); const path = require('path'); const streams = require('streamroller'); const os = require('os'); const eol = os.EOL; let mainSighupListenerStarted = false; const sighupListeners = new Set(); function mainSighupHandler() { sighupListeners.forEach((app) => { app.sighupHandler(); }); } /** * File Appender writing the logs to a text file. Supports rolling of logs by size. * * @param file the file log messages will be written to * @param layout a function that takes a logEvent and returns a string * (defaults to basicLayout). * @param logSize - the maximum size (in bytes) for a log file, * if not provided then logs won't be rotated. * @param numBackups - the number of log files to keep after logSize * has been reached (default 5) * @param options - options to be passed to the underlying stream * @param timezoneOffset - optional timezone offset in minutes (default system local) */ function fileAppender( file, layout, logSize, numBackups, options, timezoneOffset ) { if (typeof file !== 'string' || file.length === 0) { throw new Error(`Invalid filename: ${file}`); } else if (file.endsWith(path.sep)) { throw new Error(`Filename is a directory: ${file}`); } else if (file.indexOf(`~${path.sep}`) === 0) { // handle ~ expansion: https://github.com/nodejs/node/issues/684 // exclude ~ and ~filename as these can be valid files file = file.replace('~', os.homedir()); } file = path.normalize(file); numBackups = !numBackups && numBackups !== 0 ? 5 : numBackups; debug( 'Creating file appender (', file, ', ', logSize, ', ', numBackups, ', ', options, ', ', timezoneOffset, ')' ); function openTheStream(filePath, fileSize, numFiles, opt) { const stream = new streams.RollingFileStream( filePath, fileSize, numFiles, opt ); stream.on('error', (err) => { // eslint-disable-next-line no-console console.error( 'log4js.fileAppender - Writing to file %s, error happened ', filePath, err ); }); stream.on('drain', () => { process.emit('log4js:pause', false); }); return stream; } let writer = openTheStream(file, logSize, numBackups, options); const app = function (loggingEvent) { if (!writer.writable) { return; } if (options.removeColor === true) { // eslint-disable-next-line no-control-regex const regex = /\x1b[[0-9;]*m/g; loggingEvent.data = loggingEvent.data.map((d) => { if (typeof d === 'string') return d.replace(regex, ''); return d; }); } if (!writer.write(layout(loggingEvent, timezoneOffset) + eol, 'utf8')) { process.emit('log4js:pause', true); } }; app.reopen = function () { writer.end(() => { writer = openTheStream(file, logSize, numBackups, options); }); }; app.sighupHandler = function () { debug('SIGHUP handler called.'); app.reopen(); }; app.shutdown = function (complete) { sighupListeners.delete(app); if (sighupListeners.size === 0 && mainSighupListenerStarted) { process.removeListener('SIGHUP', mainSighupHandler); mainSighupListenerStarted = false; } writer.end('', 'utf-8', complete); }; // On SIGHUP, close and reopen all files. This allows this appender to work with // logrotate. Note that if you are using logrotate, you should not set // `logSize`. sighupListeners.add(app); if (!mainSighupListenerStarted) { process.on('SIGHUP', mainSighupHandler); mainSighupListenerStarted = true; } return app; } function configure(config, layouts) { let layout = layouts.basicLayout; if (config.layout) { layout = layouts.layout(config.layout.type, config.layout); } // security default (instead of relying on streamroller default) config.mode = config.mode || 0o600; return fileAppender( config.filename, layout, config.maxLogSize, config.backups, config, config.timezoneOffset ); } module.exports.configure = configure;
const debug = require('debug')('log4js:file'); const path = require('path'); const streams = require('streamroller'); const os = require('os'); const eol = os.EOL; let mainSighupListenerStarted = false; const sighupListeners = new Set(); function mainSighupHandler() { sighupListeners.forEach((app) => { app.sighupHandler(); }); } /** * File Appender writing the logs to a text file. Supports rolling of logs by size. * * @param file the file log messages will be written to * @param layout a function that takes a logEvent and returns a string * (defaults to basicLayout). * @param logSize - the maximum size (in bytes) for a log file, * if not provided then logs won't be rotated. * @param numBackups - the number of log files to keep after logSize * has been reached (default 5) * @param options - options to be passed to the underlying stream * @param timezoneOffset - optional timezone offset in minutes (default system local) */ function fileAppender( file, layout, logSize, numBackups, options, timezoneOffset ) { if (typeof file !== 'string' || file.length === 0) { throw new Error(`Invalid filename: ${file}`); } else if (file.endsWith(path.sep)) { throw new Error(`Filename is a directory: ${file}`); } else if (file.indexOf(`~${path.sep}`) === 0) { // handle ~ expansion: https://github.com/nodejs/node/issues/684 // exclude ~ and ~filename as these can be valid files file = file.replace('~', os.homedir()); } file = path.normalize(file); numBackups = !numBackups && numBackups !== 0 ? 5 : numBackups; debug( 'Creating file appender (', file, ', ', logSize, ', ', numBackups, ', ', options, ', ', timezoneOffset, ')' ); function openTheStream(filePath, fileSize, numFiles, opt) { const stream = new streams.RollingFileStream( filePath, fileSize, numFiles, opt ); stream.on('error', (err) => { // eslint-disable-next-line no-console console.error( 'log4js.fileAppender - Writing to file %s, error happened ', filePath, err ); }); stream.on('drain', () => { process.emit('log4js:pause', false); }); return stream; } let writer = openTheStream(file, logSize, numBackups, options); const app = function (loggingEvent) { if (!writer.writable) { return; } if (options.removeColor === true) { // eslint-disable-next-line no-control-regex const regex = /\x1b[[0-9;]*m/g; loggingEvent.data = loggingEvent.data.map((d) => { if (typeof d === 'string') return d.replace(regex, ''); return d; }); } if (!writer.write(layout(loggingEvent, timezoneOffset) + eol, 'utf8')) { process.emit('log4js:pause', true); } }; app.reopen = function () { writer.end(() => { writer = openTheStream(file, logSize, numBackups, options); }); }; app.sighupHandler = function () { debug('SIGHUP handler called.'); app.reopen(); }; app.shutdown = function (complete) { sighupListeners.delete(app); if (sighupListeners.size === 0 && mainSighupListenerStarted) { process.removeListener('SIGHUP', mainSighupHandler); mainSighupListenerStarted = false; } writer.end('', 'utf-8', complete); }; // On SIGHUP, close and reopen all files. This allows this appender to work with // logrotate. Note that if you are using logrotate, you should not set // `logSize`. sighupListeners.add(app); if (!mainSighupListenerStarted) { process.on('SIGHUP', mainSighupHandler); mainSighupListenerStarted = true; } return app; } function configure(config, layouts) { let layout = layouts.basicLayout; if (config.layout) { layout = layouts.layout(config.layout.type, config.layout); } // security default (instead of relying on streamroller default) config.mode = config.mode || 0o600; return fileAppender( config.filename, layout, config.maxLogSize, config.backups, config, config.timezoneOffset ); } module.exports.configure = configure;
-1
log4js-node/log4js-node
1,386
add maxLength to recording - closes #1385
gabriel-cloud
"2023-05-19T22:07:06"
"2023-06-07T01:27:16"
26dcec62f9677dceba57de8cd717ff91447781c7
c5d71e9212ed374122dfd783d2518379d5beca13
add maxLength to recording - closes #1385.
./commitlint.config.js
module.exports = { extends: ['@commitlint/config-conventional'] };
module.exports = { extends: ['@commitlint/config-conventional'] };
-1
log4js-node/log4js-node
1,386
add maxLength to recording - closes #1385
gabriel-cloud
"2023-05-19T22:07:06"
"2023-06-07T01:27:16"
26dcec62f9677dceba57de8cd717ff91447781c7
c5d71e9212ed374122dfd783d2518379d5beca13
add maxLength to recording - closes #1385.
./lib/appenders/console.js
// eslint-disable-next-line no-console const consoleLog = console.log.bind(console); function consoleAppender(layout, timezoneOffset) { return (loggingEvent) => { consoleLog(layout(loggingEvent, timezoneOffset)); }; } function configure(config, layouts) { let layout = layouts.colouredLayout; if (config.layout) { layout = layouts.layout(config.layout.type, config.layout); } return consoleAppender(layout, config.timezoneOffset); } module.exports.configure = configure;
// eslint-disable-next-line no-console const consoleLog = console.log.bind(console); function consoleAppender(layout, timezoneOffset) { return (loggingEvent) => { consoleLog(layout(loggingEvent, timezoneOffset)); }; } function configure(config, layouts) { let layout = layouts.colouredLayout; if (config.layout) { layout = layouts.layout(config.layout.type, config.layout); } return consoleAppender(layout, config.timezoneOffset); } module.exports.configure = configure;
-1
log4js-node/log4js-node
1,386
add maxLength to recording - closes #1385
gabriel-cloud
"2023-05-19T22:07:06"
"2023-06-07T01:27:16"
26dcec62f9677dceba57de8cd717ff91447781c7
c5d71e9212ed374122dfd783d2518379d5beca13
add maxLength to recording - closes #1385.
./.git/description
Unnamed repository; edit this file 'description' to name the repository.
Unnamed repository; edit this file 'description' to name the repository.
-1
log4js-node/log4js-node
1,386
add maxLength to recording - closes #1385
gabriel-cloud
"2023-05-19T22:07:06"
"2023-06-07T01:27:16"
26dcec62f9677dceba57de8cd717ff91447781c7
c5d71e9212ed374122dfd783d2518379d5beca13
add maxLength to recording - closes #1385.
./docs/tcp.md
# TCP Appender The TCP appender sends log events to a master server over TCP sockets. It can be used as a simple way to centralise logging when you have multiple servers or processes. It uses the node.js core networking modules, and so does not require any extra dependencies. Remember to call `log4js.shutdown` when your application terminates, so that the sockets get closed cleanly. It's designed to work with the [tcp-server](tcp-server.md), but it doesn't necessarily have to, just make sure whatever is listening at the other end is expecting JSON objects as strings. ## Configuration - `type` - `tcp` - `port` - `integer` (optional, defaults to `5000`) - the port to send to - `host` - `string` (optional, defaults to `localhost`) - the host/IP address to send to - `endMsg` - `string` (optional, defaults to `__LOG4JS__`) - the delimiter that marks the end of a log message - `layout` - `object` (optional, defaults to a serialized log event) - see [layouts](layouts.md) ## Example ```javascript log4js.configure({ appenders: { network: { type: "tcp", host: "log.server" }, }, categories: { default: { appenders: ["network"], level: "error" }, }, }); ``` This will send all error messages to `log.server:5000`.
# TCP Appender The TCP appender sends log events to a master server over TCP sockets. It can be used as a simple way to centralise logging when you have multiple servers or processes. It uses the node.js core networking modules, and so does not require any extra dependencies. Remember to call `log4js.shutdown` when your application terminates, so that the sockets get closed cleanly. It's designed to work with the [tcp-server](tcp-server.md), but it doesn't necessarily have to, just make sure whatever is listening at the other end is expecting JSON objects as strings. ## Configuration - `type` - `tcp` - `port` - `integer` (optional, defaults to `5000`) - the port to send to - `host` - `string` (optional, defaults to `localhost`) - the host/IP address to send to - `endMsg` - `string` (optional, defaults to `__LOG4JS__`) - the delimiter that marks the end of a log message - `layout` - `object` (optional, defaults to a serialized log event) - see [layouts](layouts.md) ## Example ```javascript log4js.configure({ appenders: { network: { type: "tcp", host: "log.server" }, }, categories: { default: { appenders: ["network"], level: "error" }, }, }); ``` This will send all error messages to `log.server:5000`.
-1
log4js-node/log4js-node
1,386
add maxLength to recording - closes #1385
gabriel-cloud
"2023-05-19T22:07:06"
"2023-06-07T01:27:16"
26dcec62f9677dceba57de8cd717ff91447781c7
c5d71e9212ed374122dfd783d2518379d5beca13
add maxLength to recording - closes #1385.
./examples/stacktrace.js
const log4js = require('../lib/log4js'); log4js.configure({ appenders: { 'console-appender': { type: 'console', layout: { type: 'pattern', pattern: '%[[%p]%] - %10.-100f{2} | %7.12l:%7.12o - %[%m%]', }, }, }, categories: { default: { appenders: ['console-appender'], enableCallStack: true, level: 'info', }, }, }); log4js.getLogger().info('This should not cause problems');
const log4js = require('../lib/log4js'); log4js.configure({ appenders: { 'console-appender': { type: 'console', layout: { type: 'pattern', pattern: '%[[%p]%] - %10.-100f{2} | %7.12l:%7.12o - %[%m%]', }, }, }, categories: { default: { appenders: ['console-appender'], enableCallStack: true, level: 'info', }, }, }); log4js.getLogger().info('This should not cause problems');
-1
log4js-node/log4js-node
1,386
add maxLength to recording - closes #1385
gabriel-cloud
"2023-05-19T22:07:06"
"2023-06-07T01:27:16"
26dcec62f9677dceba57de8cd717ff91447781c7
c5d71e9212ed374122dfd783d2518379d5beca13
add maxLength to recording - closes #1385.
./.git/hooks/prepare-commit-msg.sample
#!/bin/sh # # An example hook script to prepare the commit log message. # Called by "git commit" with the name of the file that has the # commit message, followed by the description of the commit # message's source. The hook's purpose is to edit the commit # message file. If the hook fails with a non-zero status, # the commit is aborted. # # To enable this hook, rename this file to "prepare-commit-msg". # This hook includes three examples. The first one removes the # "# Please enter the commit message..." help message. # # The second includes the output of "git diff --name-status -r" # into the message, just before the "git status" output. It is # commented because it doesn't cope with --amend or with squashed # commits. # # The third example adds a Signed-off-by line to the message, that can # still be edited. This is rarely a good idea. COMMIT_MSG_FILE=$1 COMMIT_SOURCE=$2 SHA1=$3 /usr/bin/perl -i.bak -ne 'print unless(m/^. Please enter the commit message/..m/^#$/)' "$COMMIT_MSG_FILE" # case "$COMMIT_SOURCE,$SHA1" in # ,|template,) # /usr/bin/perl -i.bak -pe ' # print "\n" . `git diff --cached --name-status -r` # if /^#/ && $first++ == 0' "$COMMIT_MSG_FILE" ;; # *) ;; # esac # SOB=$(git var GIT_COMMITTER_IDENT | sed -n 's/^\(.*>\).*$/Signed-off-by: \1/p') # git interpret-trailers --in-place --trailer "$SOB" "$COMMIT_MSG_FILE" # if test -z "$COMMIT_SOURCE" # then # /usr/bin/perl -i.bak -pe 'print "\n" if !$first_line++' "$COMMIT_MSG_FILE" # fi
#!/bin/sh # # An example hook script to prepare the commit log message. # Called by "git commit" with the name of the file that has the # commit message, followed by the description of the commit # message's source. The hook's purpose is to edit the commit # message file. If the hook fails with a non-zero status, # the commit is aborted. # # To enable this hook, rename this file to "prepare-commit-msg". # This hook includes three examples. The first one removes the # "# Please enter the commit message..." help message. # # The second includes the output of "git diff --name-status -r" # into the message, just before the "git status" output. It is # commented because it doesn't cope with --amend or with squashed # commits. # # The third example adds a Signed-off-by line to the message, that can # still be edited. This is rarely a good idea. COMMIT_MSG_FILE=$1 COMMIT_SOURCE=$2 SHA1=$3 /usr/bin/perl -i.bak -ne 'print unless(m/^. Please enter the commit message/..m/^#$/)' "$COMMIT_MSG_FILE" # case "$COMMIT_SOURCE,$SHA1" in # ,|template,) # /usr/bin/perl -i.bak -pe ' # print "\n" . `git diff --cached --name-status -r` # if /^#/ && $first++ == 0' "$COMMIT_MSG_FILE" ;; # *) ;; # esac # SOB=$(git var GIT_COMMITTER_IDENT | sed -n 's/^\(.*>\).*$/Signed-off-by: \1/p') # git interpret-trailers --in-place --trailer "$SOB" "$COMMIT_MSG_FILE" # if test -z "$COMMIT_SOURCE" # then # /usr/bin/perl -i.bak -pe 'print "\n" if !$first_line++' "$COMMIT_MSG_FILE" # fi
-1
README.md exists but content is empty. Use the Edit dataset card button to edit it.
Downloads last month
72
Edit dataset card