Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

log4js

Package Overview
Dependencies
Maintainers
1
Versions
152
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

log4js - npm Package Compare versions

Comparing version 0.4.1 to 0.4.2

.project

5

lib/appenders/console.js

@@ -1,2 +0,3 @@

var layouts = require('../layouts');
var layouts = require('../layouts'),
consoleLog = console.log;

@@ -6,3 +7,3 @@ function consoleAppender (layout) {

return function(loggingEvent) {
console._preLog4js_log(layout(loggingEvent));
consoleLog(layout(loggingEvent));
};

@@ -9,0 +10,0 @@ }

129

lib/appenders/file.js
var layouts = require('../layouts')
, path = require('path')
, fs = require('fs');
, fs = require('fs')
, streams = require('../streams');

@@ -21,128 +22,30 @@ /**

function setupLogRolling () {
try {
var stat = fs.statSync(file);
bytesWritten = stat.size;
if (bytesWritten >= logSize) {
rollThatLog();
}
} catch (e) {
//file does not exist
bytesWritten = 0;
function openTheStream(file, fileSize, numFiles) {
var stream;
if (fileSize) {
stream = new streams.BufferedWriteStream(
new streams.RollingFileStream(
file,
fileSize,
numFiles
)
);
} else {
stream = new streams.BufferedWriteStream(fs.createWriteStream(file, { encoding: "utf8", mode: 0644, flags: 'a' }));
}
}
function rollThatLog () {
function index(filename) {
return parseInt(filename.substring((path.basename(file) + '.').length), 10) || 0;
}
var nameMatcher = new RegExp('^' + path.basename(file));
function justTheLogFiles (item) {
return nameMatcher.test(item);
}
function byIndex(a, b) {
if (index(a) > index(b)) {
return 1;
} else if (index(a) < index(b) ) {
return -1;
} else {
return 0;
}
}
function increaseFileIndex (fileToRename) {
var idx = index(fileToRename);
if (idx < numBackups) {
//on windows, you can get a EEXIST error if you rename a file to an existing file
//so, we'll try to delete the file we're renaming to first
try {
fs.unlinkSync(file + '.' + (idx+1));
} catch (e) {
//couldn't delete, but that could be because it doesn't exist
//try renaming anyway
}
fs.renameSync(path.join(path.dirname(file), fileToRename), file + '.' + (idx + 1));
}
}
//roll the backups (rename file.n to file.n+1, where n <= numBackups)
fs.readdirSync(path.dirname(file))
.filter(justTheLogFiles)
.sort(byIndex)
.reverse()
.forEach(increaseFileIndex);
//let's make a new file
var newLogFileFD = fs.openSync(file, 'a', 0644)
, oldLogFileFD = logFile.fd;
logFile.fd = newLogFileFD;
fs.close(oldLogFileFD);
//reset the counter
bytesWritten = 0;
}
function fileExists (filename) {
try {
fs.statSync(filename);
return true;
} catch (e) {
return false;
}
}
function openTheStream() {
var stream = fs.createWriteStream(file, { flags: 'a', mode: 0644, encoding: 'utf8' });
stream.on("open", function() {
canWrite = true;
flushBuffer();
});
stream.on("error", function (err) {
console.error("log4js.fileAppender - Writing to file %s, error happened ", file, err);
});
stream.on("drain", function() {
canWrite = true;
flushBuffer();
if (logEventBuffer.length > 0) {
writeToLog(logEventBuffer.shift());
}
});
return stream;
}
function flushBuffer() {
while (logEventBuffer.length > 0 && canWrite) {
writeToLog(logEventBuffer.shift());
}
}
var logFile = openTheStream(file, logSize, numBackups);
var logEventBuffer = []
, canWrite = false
, logFile = openTheStream();
if (logSize > 0) {
setupLogRolling();
}
//close the file on process exit.
process.on('exit', function() {
flushBuffer();
logFile.end();
logFile.destroy();
});
function writeToLog(loggingEvent) {
var logMessage = layout(loggingEvent)+'\n';
//not entirely accurate, but it'll do.
bytesWritten += logMessage.length;
canWrite = logFile.write(logMessage, "utf8");
if (bytesWritten >= logSize) {
rollThatLog();
}
}
return function(loggingEvent) {
logEventBuffer.push(loggingEvent);
flushBuffer();
logFile.write(layout(loggingEvent)+'\n', "utf8");
};

@@ -149,0 +52,0 @@ }

@@ -82,5 +82,6 @@ var levels = require("./levels");

};
next();
}
//ensure next gets always called
next();
};

@@ -87,0 +88,0 @@ }

@@ -34,3 +34,3 @@ function Level(level, levelStr) {

if (typeof otherLevel === "string") {
otherLevel = Level.toLevel(otherLevel);
otherLevel = toLevel(otherLevel);
}

@@ -42,3 +42,3 @@ return this.level <= otherLevel.level;

if (typeof otherLevel === "string") {
otherLevel = Level.toLevel(otherLevel);
otherLevel = toLevel(otherLevel);
}

@@ -45,0 +45,0 @@ return this.level >= otherLevel.level;

@@ -327,17 +327,43 @@ /*

var config = configurationFileOrObject;
options = options || {};
if (config === undefined || config === null || typeof(config) === 'string') {
options = options || { };
if (options.reloadSecs) {
initReloadConfiguration(config, options);
}
configureOnceOff(loadConfigurationFile(config));
config = loadConfigurationFile(config);
} else {
options = options || {};
if (options.reloadSecs) {
getLogger('log4js').warn('Ignoring configuration reload parameter for "object" configuration.');
}
configureOnceOff(config);
}
if (options.hasOwnProperty('cwd')) {
if(config.hasOwnProperty('appenders')) {
config.appenders.forEach(function(appender) {
if (!appender.hasOwnProperty('type')) return;
if (appender.type === 'file') {
if(!appender.hasOwnProperty('filename')) return;
if(appender.hasOwnProperty('absolute')) {
if(appender.absolute) return;
}
appender.filename = path.join(options.cwd, appender.filename);
}
});
}
}
configureOnceOff(config);
}
var originalConsoleFunctions = {
log: console.log,
debug: console.debug,
info: console.info,
warn: console.warn,
error: console.error
};
function replaceConsole(logger) {

@@ -349,18 +375,12 @@ function replaceWith(fn) {

}
if (console['_preLog4js_log'] === undefined) {
logger = logger || getLogger("console");
['log','debug','info','warn','error'].forEach(function (item) {
console['_preLog4js_'+item] = console[item];
console[item] = replaceWith(item === 'log' ? logger.info : logger[item]);
});
}
logger = logger || getLogger("console");
['log','debug','info','warn','error'].forEach(function (item) {
console[item] = replaceWith(item === 'log' ? logger.info : logger[item]);
});
}
function restoreConsole() {
if (console['_preLog4js_log']) {
['log', 'debug', 'info', 'warn', 'error'].forEach(function (item) {
console[item] = console['_preLog4js_'+item];
delete console['_preLog4js_'+item];
});
}
['log', 'debug', 'info', 'warn', 'error'].forEach(function (item) {
console[item] = originalConsoleFunctions[item];
});
}

@@ -367,0 +387,0 @@

{
"name": "log4js",
"version": "0.4.1",
"version": "0.4.2",
"description": "Port of Log4js to work with node.",

@@ -13,4 +13,8 @@ "keywords": [

"author": "Gareth Jones <gareth.jones@sensis.com.au>",
"repository": {
"type": "git",
"url": "https://github.com/nomiddlename/log4js-node.git"
},
"bugs": {
"url": "http://github.com/csausdev/log4js-node/issues"
"url": "http://github.com/nomiddlename/log4js-node/issues"
},

@@ -26,2 +30,4 @@ "engines": [ "node >=0.4" ],

"dependencies": {
"async": "0.1.15",
"compress-buffer": ">= 0.5.0"
},

@@ -28,0 +34,0 @@ "devDependencies": {

@@ -1,2 +0,2 @@

# log4js-node
# log4js-node [![Build Status](https://secure.travis-ci.org/nomiddlename/log4js-node.png?branch=master)](http://travis-ci.org/nomiddlename/log4js-node)

@@ -76,2 +76,31 @@ NOTE: v0.3.8 of log4js is the last that will work with node versions older than 0.4. To use v0.3.9 you will need node 0.4 or later.

For FileAppender you can also pass the path to the log directory as an option where all your log files would be stored.
log4js.configure('my_log4js_configuration.json', { cwd: '/absolute/path/to/log/dir' });
If you have already defined an absolute path for one of the FileAppenders in the configuration file, you could add a "absolute": true to the particular FileAppender to override the cwd option passed. Here is an example configuration file:
#### my_log4js_configuration.json ####
{
"appenders": [
{
"type": "file",
"filename": "relative/path/to/log_file.log",
"maxLogSize": 20480,
"backups": 3,
"pollInterval": 15,
"category": "relative-logger"
},
{
"type": "file",
"absolute": true,
"filename": "/absolute/path/to/log_file.log",
"maxLogSize": 20480,
"backups": 10,
"pollInterval": 15,
"category": "absolute-logger"
}
]
}
## connect/express logger

@@ -224,2 +253,20 @@

## gelf logger
A gelf logger has been added to log4js, by [arifamirani](https://github.com/arifamirani). This allows log4js to log to [GELF](http://www.graylog2.org/about/gelf) compatible servers such as [Graylog](http://www.graylog2.org/). This is currently configuration based and needs the following configuration to be added to log4j.json. For example:
<pre>
{
"appenders": [
{
"type": "gelf",
"host": "logs.mydomain.com", //defaults to localhost
"hostname":"mrs-dev", //defaults to the value returned by os.hostname()
"port": "12201", //defaults to 12201
"facility": "myapp" //defaults to nodejs-server
}
}
}
</pre>
## author (of this node version)

@@ -226,0 +273,0 @@

@@ -20,5 +20,6 @@ var vows = require('vows')

topic: function() {
var testFile = __dirname + '/fa-default-test.log'
var that = this, testFile = __dirname + '/fa-default-test.log'
, logger = log4js.getLogger('default-settings');
remove(testFile);
log4js.clearAppenders();
log4js.addAppender(log4js.fileAppender(testFile), 'default-settings');

@@ -28,3 +29,5 @@

fs.readFile(testFile, "utf8", this.callback);
setTimeout(function() {
fs.readFile(testFile, "utf8", that.callback);
}, 100);
},

@@ -46,2 +49,3 @@ 'should write log messages to the file': function(err, fileContents) {

//log file of 100 bytes maximum, no backups
log4js.clearAppenders();
log4js.addAppender(log4js.fileAppender(testFile, log4js.layouts.basicLayout, 100, 0), 'max-file-size');

@@ -80,2 +84,3 @@ logger.info("This is the first log message.");

//log file of 50 bytes maximum, 2 backups
log4js.clearAppenders();
log4js.addAppender(log4js.fileAppender(testFile, log4js.layouts.basicLayout, 50, 2), 'max-file-size-backups');

@@ -101,3 +106,3 @@ logger.info("This is the first log message.");

'should be named in sequence': function (files) {
assert.deepEqual(files, ['fa-maxFileSize-with-backups-test.log', 'fa-maxFileSize-with-backups-test.log.1', 'fa-maxFileSize-with-backups-test.log.2']);
assert.deepEqual(files.sort(), ['fa-maxFileSize-with-backups-test.log', 'fa-maxFileSize-with-backups-test.log.1', 'fa-maxFileSize-with-backups-test.log.2']);
},

@@ -152,2 +157,2 @@ 'and the contents of the first file': {

}).export(module);
}).export(module);

@@ -47,4 +47,4 @@ var vows = require('vows')

logger.debug('main');
return logger;
//wait for the file system to catch up
setTimeout(this.callback, 100);
},

@@ -51,0 +51,0 @@ 'tmp-tests.log': {

var vows = require('vows'),
assert = require('assert'),
log4js = require('../lib/log4js'),
sandbox = require('sandboxed-module');
assert = require('assert'),
log4js = require('../lib/log4js'),
sandbox = require('sandboxed-module');
function setupLogging(category, options) {
var msgs = [];
var fakeMailer = {
send_mail: function (msg, callback) {
msgs.push(msg);
callback(null, true);
}
};
var msgs = [];
var smtpModule = sandbox.require('../lib/appenders/smtp', {
requires: {
'nodemailer': fakeMailer
}
});
var fakeMailer = {
send_mail: function (msg, callback) {
msgs.push(msg);
callback(null, true);
}
};
log4js.addAppender(smtpModule.configure(options), category);
return {
logger: log4js.getLogger(category),
mailer: fakeMailer,
results: msgs
};
var smtpModule = sandbox.require('../lib/appenders/smtp', {
requires: {
'nodemailer': fakeMailer
}
});
log4js.addAppender(smtpModule.configure(options), category);
return {
logger: log4js.getLogger(category),
mailer: fakeMailer,
results: msgs
};
}
function checkMessages (result, sender, subject) {
for (var i = 0; i < result.results.length; ++i) {
assert.equal(result.results[i].sender, sender ? sender : result.mailer.SMTP.user);
assert.equal(result.results[i].to, 'recipient@domain.com');
assert.equal(result.results[i].subject, subject ? subject : 'Log event #' + (i+1));
assert.ok(new RegExp('.+Log event #' + (i+1) + '\n$').test(result.results[i].body));
}
for (var i = 0; i < result.results.length; ++i) {
assert.equal(result.results[i].sender, sender ? sender : result.mailer.SMTP.user);
assert.equal(result.results[i].to, 'recipient@domain.com');
assert.equal(result.results[i].subject, subject ? subject : 'Log event #' + (i+1));
assert.ok(new RegExp('.+Log event #' + (i+1) + '\n$').test(result.results[i].body));
}
}

@@ -42,122 +42,122 @@

vows.describe('log4js smtpAppender').addBatch({
'minimal config': {
topic: function() {
var setup = setupLogging('minimal config', {
recipients: 'recipient@domain.com',
smtp: {
port: 25,
user: 'user@domain.com'
}
});
setup.logger.info('Log event #1');
return setup;
},
'mailer should be configured properly': function (result) {
assert.ok(result.mailer.SMTP);
assert.equal(result.mailer.SMTP.port, 25);
assert.equal(result.mailer.SMTP.user, 'user@domain.com');
},
'there should be one message only': function (result) {
assert.equal(result.results.length, 1);
},
'message should contain proper data': function (result) {
checkMessages(result);
'minimal config': {
topic: function() {
var setup = setupLogging('minimal config', {
recipients: 'recipient@domain.com',
smtp: {
port: 25,
user: 'user@domain.com'
}
});
setup.logger.info('Log event #1');
return setup;
},
'fancy config': {
topic: function() {
var setup = setupLogging('fancy config', {
recipients: 'recipient@domain.com',
sender: 'sender@domain.com',
subject: 'This is subject',
smtp: {
port: 25,
user: 'user@domain.com'
}
});
setup.logger.info('Log event #1');
return setup;
},
'mailer should be configured properly': function (result) {
assert.ok(result.mailer.SMTP);
assert.equal(result.mailer.SMTP.port, 25);
assert.equal(result.mailer.SMTP.user, 'user@domain.com');
},
'there should be one message only': function (result) {
assert.equal(result.results.length, 1);
},
'message should contain proper data': function (result) {
checkMessages(result, 'sender@domain.com', 'This is subject');
'mailer should be configured properly': function (result) {
assert.ok(result.mailer.SMTP);
assert.equal(result.mailer.SMTP.port, 25);
assert.equal(result.mailer.SMTP.user, 'user@domain.com');
},
'there should be one message only': function (result) {
assert.equal(result.results.length, 1);
},
'message should contain proper data': function (result) {
checkMessages(result);
}
},
'fancy config': {
topic: function() {
var setup = setupLogging('fancy config', {
recipients: 'recipient@domain.com',
sender: 'sender@domain.com',
subject: 'This is subject',
smtp: {
port: 25,
user: 'user@domain.com'
}
});
setup.logger.info('Log event #1');
return setup;
},
'separate email for each event': {
topic: function() {
var self = this;
var setup = setupLogging('separate email for each event', {
recipients: 'recipient@domain.com',
smtp: {
port: 25,
user: 'user@domain.com'
}
});
setTimeout(function () {
setup.logger.info('Log event #1');
}, 0);
setTimeout(function () {
setup.logger.info('Log event #2');
}, 500);
setTimeout(function () {
setup.logger.info('Log event #3');
}, 1050);
setTimeout(function () {
self.callback(null, setup);
}, 2100);
},
'there should be three messages': function (result) {
assert.equal(result.results.length, 3);
},
'messages should contain proper data': function (result) {
checkMessages(result);
'mailer should be configured properly': function (result) {
assert.ok(result.mailer.SMTP);
assert.equal(result.mailer.SMTP.port, 25);
assert.equal(result.mailer.SMTP.user, 'user@domain.com');
},
'there should be one message only': function (result) {
assert.equal(result.results.length, 1);
},
'message should contain proper data': function (result) {
checkMessages(result, 'sender@domain.com', 'This is subject');
}
},
'separate email for each event': {
topic: function() {
var self = this;
var setup = setupLogging('separate email for each event', {
recipients: 'recipient@domain.com',
smtp: {
port: 25,
user: 'user@domain.com'
}
});
setTimeout(function () {
setup.logger.info('Log event #1');
}, 0);
setTimeout(function () {
setup.logger.info('Log event #2');
}, 500);
setTimeout(function () {
setup.logger.info('Log event #3');
}, 1050);
setTimeout(function () {
self.callback(null, setup);
}, 2100);
},
'multiple events in one email': {
topic: function() {
var self = this;
var setup = setupLogging('multiple events in one email', {
recipients: 'recipient@domain.com',
sendInterval: 1,
smtp: {
port: 25,
user: 'user@domain.com'
}
});
setTimeout(function () {
setup.logger.info('Log event #1');
}, 0);
setTimeout(function () {
setup.logger.info('Log event #2');
}, 500);
setTimeout(function () {
setup.logger.info('Log event #3');
}, 1050);
setTimeout(function () {
self.callback(null, setup);
}, 2100);
},
'there should be two messages': function (result) {
assert.equal(result.results.length, 2);
},
'messages should contain proper data': function (result) {
assert.equal(result.results[0].sender, result.mailer.SMTP.user);
assert.equal(result.results[0].to, 'recipient@domain.com');
assert.equal(result.results[0].subject, 'Log event #1');
assert.equal(result.results[0].body.match(new RegExp('.+Log event #[1-2]$', 'gm')).length, 2);
'there should be three messages': function (result) {
assert.equal(result.results.length, 3);
},
'messages should contain proper data': function (result) {
checkMessages(result);
}
},
'multiple events in one email': {
topic: function() {
var self = this;
var setup = setupLogging('multiple events in one email', {
recipients: 'recipient@domain.com',
sendInterval: 1,
smtp: {
port: 25,
user: 'user@domain.com'
}
});
setTimeout(function () {
setup.logger.info('Log event #1');
}, 0);
setTimeout(function () {
setup.logger.info('Log event #2');
}, 500);
setTimeout(function () {
setup.logger.info('Log event #3');
}, 1050);
setTimeout(function () {
self.callback(null, setup);
}, 2100);
},
'there should be two messages': function (result) {
assert.equal(result.results.length, 2);
},
'messages should contain proper data': function (result) {
assert.equal(result.results[0].sender, result.mailer.SMTP.user);
assert.equal(result.results[0].to, 'recipient@domain.com');
assert.equal(result.results[0].subject, 'Log event #1');
assert.equal(result.results[0].body.match(new RegExp('.+Log event #[1-2]$', 'gm')).length, 2);
assert.equal(result.results[1].sender, result.mailer.SMTP.user);
assert.equal(result.results[1].to, 'recipient@domain.com');
assert.equal(result.results[1].subject, 'Log event #3');
assert.ok(new RegExp('.+Log event #3\n$').test(result.results[1].body));
}
assert.equal(result.results[1].sender, result.mailer.SMTP.user);
assert.equal(result.results[1].to, 'recipient@domain.com');
assert.equal(result.results[1].subject, 'Log event #3');
assert.ok(new RegExp('.+Log event #3\n$').test(result.results[1].body));
}
}
}).export(module);
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc