|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +const test = require('tap').test; |
| 4 | +const fs = require('fs'); |
| 5 | +const EOL = require('os').EOL || '\n'; |
| 6 | +const log4js = require('../../lib/log4js'); |
| 7 | + |
| 8 | +function remove(filename) { |
| 9 | + try { |
| 10 | + fs.unlinkSync(filename); |
| 11 | + } catch (e) { |
| 12 | + // doesn't really matter if it failed |
| 13 | + } |
| 14 | +} |
| 15 | + |
| 16 | +function cleanup(done) { |
| 17 | + remove(`${__dirname}/categoryFilter-web.log`); |
| 18 | + remove(`${__dirname}/categoryFilter-noweb.log`); |
| 19 | + done(); |
| 20 | +} |
| 21 | + |
| 22 | +test('log4js categoryFilter', (batch) => { |
| 23 | + batch.beforeEach(cleanup); |
| 24 | + |
| 25 | + batch.test('appender should exclude categories', (t) => { |
| 26 | + const logEvents = []; |
| 27 | + const appender = require( |
| 28 | + '../../lib/appenders/categoryFilter' |
| 29 | + ).appender( |
| 30 | + ['app'], |
| 31 | + (evt) => { |
| 32 | + logEvents.push(evt); |
| 33 | + } |
| 34 | + ); |
| 35 | + log4js.clearAppenders(); |
| 36 | + log4js.addAppender(appender, ['app', 'web']); |
| 37 | + |
| 38 | + const webLogger = log4js.getLogger('web'); |
| 39 | + const appLogger = log4js.getLogger('app'); |
| 40 | + |
| 41 | + webLogger.debug('This should get logged'); |
| 42 | + appLogger.debug('This should not'); |
| 43 | + webLogger.debug('Hello again'); |
| 44 | + log4js.getLogger('db').debug('This shouldn\'t be included by the appender anyway'); |
| 45 | + |
| 46 | + t.equal(logEvents.length, 2); |
| 47 | + t.equal(logEvents[0].data[0], 'This should get logged'); |
| 48 | + t.equal(logEvents[1].data[0], 'Hello again'); |
| 49 | + t.end(); |
| 50 | + }); |
| 51 | + |
| 52 | + batch.test('should work with configuration file', (t) => { |
| 53 | + log4js.configure('test/tap/with-categoryFilter.json'); |
| 54 | + const logger = log4js.getLogger('app'); |
| 55 | + const weblogger = log4js.getLogger('web'); |
| 56 | + |
| 57 | + logger.info('Loading app'); |
| 58 | + logger.info('Initialising indexes'); |
| 59 | + weblogger.info('00:00:00 GET / 200'); |
| 60 | + weblogger.warn('00:00:00 GET / 500'); |
| 61 | + |
| 62 | + setTimeout(() => { |
| 63 | + fs.readFile(`${__dirname}/categoryFilter-noweb.log`, 'utf8', (err, contents) => { |
| 64 | + const noWebMessages = contents.trim().split(EOL); |
| 65 | + t.same(noWebMessages, ['Loading app', 'Initialising indexes']); |
| 66 | + |
| 67 | + fs.readFile(`${__dirname}/categoryFilter-web.log`, 'utf8', (e, c) => { |
| 68 | + const messages = c.trim().split(EOL); |
| 69 | + t.same(messages, ['00:00:00 GET / 200', '00:00:00 GET / 500']); |
| 70 | + t.end(); |
| 71 | + }); |
| 72 | + }); |
| 73 | + }, 500); |
| 74 | + }); |
| 75 | + |
| 76 | + batch.afterEach(cleanup); |
| 77 | + batch.end(); |
| 78 | +}); |
0 commit comments