From 6032c073b392c0bc1a036a319e85aff5cd31b942 Mon Sep 17 00:00:00 2001 From: csausdev Date: Sun, 5 Dec 2010 10:56:09 +1100 Subject: [PATCH] Added loading of config from require paths, and now defaults to console appender with basic layout --- README.md | 11 +++++++-- lib/log4js.js | 47 ++++++++++++++++++++++++++++++------- lib/log4js.json | 10 ++++++++ test/logging.js | 62 ++++++++++++++++++++++++++++++++++++++++++++++++- 4 files changed, 118 insertions(+), 12 deletions(-) create mode 100644 lib/log4js.json diff --git a/README.md b/README.md index d2afb3b..ee1929f 100644 --- a/README.md +++ b/README.md @@ -16,6 +16,13 @@ Tests now use [vows](http://vowsjs.org), run with `vows test/logging.js`. I am s ## usage +Minimalist version: + var log4js = require('log4js')(); + var logger = log4js.getLogger(); + logger.debug("Some debug messages"); +By default, log4js outputs to stdout with the basic layout, so for the above you would see: + [2010-01-17 11:43:37.987] [DEBUG] [default] - Some debug messages + See example.js: var log4js = require('log4js')(); //note the need to call the function @@ -40,8 +47,8 @@ Output ## configuration You can either configure the appenders and log levels manually (as above), or provide a -configuration file (`log4js.configure('path/to/file.json')`). An example file can be found -in test/log4js.json +configuration file (`log4js.configure('path/to/file.json')`) explicitly, or just let log4js look for a file called `log4js.json` (it looks in the current directory first, then the require paths, and finally looks for the default config included in the same directory as the log4js.js file). +An example file can be found in test/log4js.json ## todo diff --git a/lib/log4js.js b/lib/log4js.js index 38a3630..c5424db 100644 --- a/lib/log4js.js +++ b/lib/log4js.js @@ -44,10 +44,13 @@ * @static * Website: http://log4js.berlios.de */ -module.exports = function (fileSystem) { - var fs = fileSystem || require('fs'), +module.exports = function (fileSystem, standardOutput, configPaths) { + var fs = fileSystem || require('fs'), + standardOutput = standardOutput || console.log, + configPaths = configPaths || require.paths, sys = require('sys'), events = require('events'), + path = require('path'), DEFAULT_CATEGORY = '[default]', ALL_CATEGORIES = '[all]', loggers = {}, @@ -91,8 +94,6 @@ module.exports = function (fileSystem) { } }; - - /** * Get a logger instance. Instance is cached on categoryName level. * @param {String} categoryName name of category to log to. @@ -133,7 +134,7 @@ module.exports = function (fileSystem) { function addAppender () { var args = Array.prototype.slice.call(arguments); var appender = args.shift(); - if (args.length == 0) { + if (args.length == 0 || args[0] === undefined) { args = [ ALL_CATEGORIES ]; } //argument may already be an array @@ -169,9 +170,34 @@ module.exports = function (fileSystem) { } function configure (configurationFile) { - var config = JSON.parse(fs.readFileSync(configurationFile)); - configureAppenders(config.appenders); - configureLevels(config.levels); + if (configurationFile) { + try { + var config = JSON.parse(fs.readFileSync(configurationFile, "utf8")); + configureAppenders(config.appenders); + configureLevels(config.levels); + } catch (e) { + throw new Error("Problem reading log4js config file " + configurationFile + ". Error was " + e.message); + } + } + } + + function findConfiguration() { + //add current directory onto the list of configPaths + var paths = ['.'].concat(configPaths); + //add this module's directory to the end of the list, so that we pick up the default config + paths.push(__dirname); + var pathsWithConfig = paths.filter( function (pathToCheck) { + try { + fs.statSync(path.join(pathToCheck, "log4js.json")); + return true; + } catch (e) { + return false; + } + }); + if (pathsWithConfig.length > 0) { + return path.join(pathsWithConfig[0], 'log4js.json'); + } + return undefined; } function configureAppenders(appenderList) { @@ -310,7 +336,7 @@ module.exports = function (fileSystem) { function consoleAppender (layout) { layout = layout || basicLayout; return function(loggingEvent) { - console.log(layout(loggingEvent)); + standardOutput(layout(loggingEvent)); }; } @@ -488,6 +514,9 @@ module.exports = function (fileSystem) { }; + //set ourselves up if we can find a default log4js.json + configure(findConfiguration()); + return { getLogger: getLogger, getDefaultLogger: getDefaultLogger, diff --git a/lib/log4js.json b/lib/log4js.json new file mode 100644 index 0000000..fdd836f --- /dev/null +++ b/lib/log4js.json @@ -0,0 +1,10 @@ +{ + "appenders": [ + { + "type": "console", + "layout": { + "type": "basic" + } + } + ] +} \ No newline at end of file diff --git a/test/logging.js b/test/logging.js index 09b88a1..fc9e471 100644 --- a/test/logging.js +++ b/test/logging.js @@ -129,6 +129,66 @@ vows.describe('log4js').addBatch({ assert.deepEqual(messages['tmp-tests.log'], ['main\n','both\n','both\n','main\n']); assert.deepEqual(messages['tmp-tests-warnings.log'], ['both\n','both\n']); } + }, + + 'with no appenders defined' : { + topic: function() { + var logger, message, log4js = require('../lib/log4js')(null, function (msg) { message = msg; } ); + logger = log4js.getLogger("some-logger"); + logger.debug("This is a test"); + return message; + }, + 'should default to the console appender': function(message) { + assert.isTrue(/This is a test$/.test(message)); + } + }, + + 'default setup': { + topic: function() { + var pathsChecked = [], + message, + logger, + fakeFS = { + readFileSync: function (file, encoding) { + assert.equal(file, '/path/to/config/log4js.json'); + assert.equal(encoding, 'utf8'); + return '{ "appenders" : [ { "type": "console", "layout": { "type": "messagePassThrough" }} ] }'; + }, + statSync: function (path) { + pathsChecked.push(path); + if (path === '/path/to/config/log4js.json') { + return true; + } else { + throw new Error("no such file"); + } + } + }, + fakeConsoleLog = function (msg) { message = msg; }, + fakeRequirePath = [ '/a/b/c', '/some/other/path', '/path/to/config', '/some/later/directory' ], + log4js = require('../lib/log4js')(fakeFS, fakeConsoleLog, fakeRequirePath), + logger = log4js.getLogger('a-test'); + logger.debug("this is a test"); + + return [ pathsChecked, message ]; + }, + + 'should check current directory, require paths, and finally the module dir for log4js.json': function(args) { + var pathsChecked = args[0]; + assert.deepEqual(pathsChecked, [ + 'log4js.json', + '/a/b/c/log4js.json', + '/some/other/path/log4js.json', + '/path/to/config/log4js.json', + '/some/later/directory/log4js.json', + require('path').normalize(__dirname + '/../lib/log4js.json') + ]); + }, + + 'should configure log4js from first log4js.json found': function(args) { + var message = args[1]; + assert.equal(message, 'this is a test'); + } } - + + }).export(module);