Added loading of config from require paths, and now defaults to console appender with basic layout

This commit is contained in:
Gareth Jones 2010-12-05 07:56:09 +08:00
parent 9364a8a442
commit 838f0c8f28
4 changed files with 118 additions and 12 deletions

View File

@ -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

View File

@ -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,

10
lib/log4js.json Normal file
View File

@ -0,0 +1,10 @@
{
"appenders": [
{
"type": "console",
"layout": {
"type": "basic"
}
}
]
}

View File

@ -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);