8000 Added loading of config from require paths, and now defaults to conso… · Web5design/log4js-node@40d3f5a · GitHub
[go: up one dir, main page]

Skip to content

Commit 40d3f5a

Browse files
Gareth JonesGareth Jones
authored andcommitted
Added loading of config from require paths, and now defaults to console appender with basic layout
1 parent ee776fe commit 40d3f5a

File tree

4 files changed

+118
-12
lines changed

4 files changed

+118
-12
lines changed

README.md

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,13 @@ Tests now use [vows](http://vowsjs.org), run with `vows test/logging.js`. I am s
1616

1717
## usage
1818

19+
Minimalist version:
20+
var log4js = require('log4js')();
21+
var logger = log4js.getLogger();
22+
logger.debug("Some debug messages");
23+
By default, log4js outputs to stdout with the basic layout, so for the above you would see:
24+
[2010-01-17 11:43:37.987] [DEBUG] [default] - Some debug messages
25+
1926
See example.js:
2027

2128
var log4js = require('log4js')(); //note the need to call the function
@@ -40,8 +47,8 @@ Output
4047
## configuration
4148

4249
You can either configure the appenders and log levels manually (as above), or provide a
43-
configuration file (`log4js.configure('path/to/file.json')`). An example file can be found
44-
in test/log4js.json
50+
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).
51+
An example file can be found in test/log4js.json
4552

4653
## todo
4754

lib/log4js.js

Lines changed: 38 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -44,10 +44,13 @@
4444
* @static
4545
* Website: http://log4js.berlios.de
4646
*/
47-
module.exports = function (fileSystem) {
48-
var fs = fileSystem || require('fs'),
47+
module.exports = function (fileSystem, standardOutput, configPaths) {
48+
var fs = fileSystem || require('fs'),
49+
standardOutput = standardOutput || console.log,
50+
configPaths = configPaths || require.paths,
4951
sys = require('sys'),
5052
events = require('events'),
53+
path = require('path'),
5154
DEFAULT_CATEGORY = '[default]',
5255
ALL_CATEGORIES = '[all]',
5356
loggers = {},
@@ -91,8 +94,6 @@ module.exports = function (fileSystem) {
9194
}
9295
};
9396

94-
95-
9697
/**
9798
* Get a logger instance. Instance is cached on categoryName level.
9899
* @param {String} categoryName name of category to log to.
@@ -133,7 +134,7 @@ module.exports = function (fileSystem) {
133134
function addAppender () {
134135
var args = Array.prototype.slice.call(arguments);
135136
var appender = args.shift();
136-
if (args.length == 0) {
137+
if (args.length == 0 || args[0] === undefined) {
137138
args = [ ALL_CATEGORIES ];
138139
}
139140
//argument may already be an array
@@ -169,9 +170,34 @@ module.exports = function (fileSystem) {
169170
}
170171

171172
function configure (configurationFile) {
172-
var config = JSON.parse(fs.readFileSync(configurationFile));
173-
configureAppenders(config.appenders);
174-
configureLevels(config.levels);
173+
if (configurationFile) {
174+
try {
175+
var config = JSON.parse(fs.readFileSync(configurationFile, "utf8"));
176+
configureAppenders(config.appenders);
177+
configureLevels(config.levels);
178+
} catch (e) {
179+
throw new Error("Problem reading log4js config file " + configurationFile + ". Error was " + e.message);
180+
}
181+
}
182+
}
183+
184+
function findConfiguration() {
185+
//add current directory onto the list of configPaths
186+
var paths = ['.'].concat(configPaths);
187+
//add this module's directory to the end of the list, so that we pick up the default config
188+
paths.push(__dirname);
189+
var pathsWithConfig = paths.filter( function (pathToCheck) {
190+
try {
191+
fs.statSync(path.join(pathToCheck, "log4js.json"));
192+
return true;
193+
} catch (e) {
194+
return false;
195+
}
196+
});
197+
if (pathsWithConfig.length > 0) {
198+
return path.join(pathsWithConfig[0], 'log4js.json');
199+
}
200+
return undefined;
175201
}
176202

177203
function configureAppenders(appenderList) {
@@ -310,7 +336,7 @@ module.exports = function (fileSystem) {
310336
function consoleAppender (layout) {
311337
layout = layout || basicLayout;
312338
return function(loggingEvent) {
313-
console.log(layout(loggingEvent));
339+
standardOutput(layout(loggingEvent));
314340
};
315341
}
316342

@@ -488,6 +514,9 @@ module.exports = function (fileSystem) {
488514

489515
};
490516

517+
//set ourselves up if we can find a default log4js.json
518+
configure(findConfiguration());
519+
491520
return {
492521
getLogger: getLogger,
493522
getDefaultLogger: getDefaultLogger,

lib/log4js.json

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
{
2+
"appenders": [
3+
{
4+
"type": "console",
5+
"layout": {
6+
"type": "basic"
7+
}
8+
}
9+
]
10+
}

test/logging.js

Lines changed: 61 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,66 @@ vows.describe('log4js').addBatch({
129129
assert.deepEqual(messages['tmp-tests.log'], ['main\n','both\n','both\n','main\n']);
130130
assert.deepEqual(messages['tmp-tests-warnings.log'], ['both\n','both\n']);
131131
}
132+
},
133+
134+
'with no appenders defined' : {
135+
topic: function() {
136+
var logger, message, log4js = require('../lib/log4js')(null, function (msg) { message = msg; } );
137+
logger = log4js.getLogger("some-logger");
138+
logger.debug("This is a test");
139+
return message;
140+
},
141+
'should default to the console appender': function(message) {
142+
assert.isTrue(/This is a test$/.test(message));
143+
}
144+
},
145+
146+
'default setup': {
147+
topic: function() {
148+
var pathsChecked = [],
149+
message,
150+
logger,
151+
fakeFS = {
152+
readFileSync: function (file, encoding) {
153+
assert.equal(file, '/path/to/config/log4js.json');
154+
assert.equal(encoding, 'utf8');
155+
return '{ "appenders" : [ { "type": "console", "layout": { "type": "messagePassThrough" }} ] }';
156+
},
157+
statSync: function (path) {
158+
pathsChecked.push(path);
159+
if (path === '/path/to/config/log4js.json') {
160+
return true;
161+
} else {
162+
throw new Error("no such file");
163+
}
164+
}
165+
},
166+
fakeConsoleLog = function (msg) { message = msg; },
167+
fakeRequirePath = [ '/a/b/c', '/some/other/path', '/path/to/config', '/some/later/directory' ],
168+
log4js = require('../lib/log4js')(fakeFS, fakeConsoleLog, fakeRequirePath),
169+
logger = log4js.getLogger('a-test');
170+
logger.debug("this is a test");
171+
172+
return [ pathsChecked, message ];
173+
},
174+
175+
'should check current directory, require paths, and finally the module dir for log4js.json': function(args) {
176+
var pathsChecked = args[0];
177+
assert.deepEqual(pathsChecked, [
178+
'log4js.json',
179+
'/a/b/c/log4js.json',
180+
'/some/other/path/log4js.json',
181+
'/path/to/config/log4js.json',
182+
'/some/later/directory/log4js.json',
183+
require('path').normalize(__dirname + '/../lib/log4js.json')
184+
]);
185+
},
186+
187+
'should configure log4js from first log4js.json found': function(args) {
188+
var message = args[1];
189+
assert.equal(message, 'this is a test');
190+
}
132191
}
133-
192+
193+
134194
}).export(module);

0 commit comments

Comments
 (0)
0