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.5.0 to 0.5.1

fromreadme.js

9

example-socket.js

@@ -26,3 +26,2 @@ var log4js = require('./lib/log4js')

console.info("Worker %d died.", worker.pid);
// cluster.fork();
});

@@ -38,11 +37,7 @@ } else {

});
function logSomething(i) {
return function() {
console.info("Worker %d - logging something %d", process.pid, i);
}
}
var logger = log4js.getLogger('example-socket');
console.info("Worker %d started.", process.pid);
for (i=0; i < 1000; i++) {
process.nextTick(logSomething(i));
logger.info("Worker %d - logging something %d", process.pid, i);
}

@@ -49,0 +44,0 @@ }

var log4js = require('./lib/log4js');
//log the cheese logger messages to a file, and the console ones as well.
log4js.addAppender(log4js.fileAppender('cheese.log'), 'cheese', 'console');
log4js.configure({
appenders: [
{
type: "file",
filename: "cheese.log",
category: [ 'cheese','console' ]
},
{
type: "console"
}
],
replaceConsole: true
});
//to add an appender programmatically, and without clearing other appenders
//loadAppender is only necessary if you haven't already configured an appender of this type
log4js.loadAppender('file');
log4js.addAppender(log4js.appenders.file('pants.log'), 'pants');
//a custom logger outside of the log4js/lib/appenders directory can be accessed like so
//log4js.loadAppender('what/you/would/put/in/require');
//log4js.addAppender(log4js.appenders['what/you/would/put/in/require'](args));
//or through configure as:
//log4js.configure({
// appenders: [ { type: 'what/you/would/put/in/require', otherArgs: 'blah' } ]
//});
var logger = log4js.getLogger('cheese');
//only errors and above get logged.
//you can also set this log level in the config object
//via the levels field.
logger.setLevel('ERROR');
//console logging methds have been replaced with log4js ones.
//console logging methods have been replaced with log4js ones.
//so this will get coloured output on console, and appear in cheese.log
console.error("AAArgh! Something went wrong", { some: "otherObject", useful_for: "debug purposes" });

@@ -21,3 +48,12 @@

//these don't end up in cheese.log, but will appear on the console
var anotherLogger = log4js.getLogger('another');
anotherLogger.debug("Just checking");
//one for pants.log
//will also go to console, since that's configured for all categories
var pantsLog = log4js.getLogger('pants');
pantsLog.debug("Something for pants");
var layouts = require('../layouts')
, path = require('path')
, fs = require('fs')
, streams = require('../streams');
, streams = require('../streams')
, os = require('os')
, eol = os.EOL || '\n';

@@ -49,3 +51,3 @@ /**

return function(loggingEvent) {
logFile.write(layout(loggingEvent)+'\n', "utf8");
logFile.write(layout(loggingEvent) + eol, "utf8");
};

@@ -52,0 +54,0 @@ }

@@ -1,73 +0,131 @@

var log4js = require('../log4js');
var layouts = require('../layouts');
var net = require('net');
var util = require('util');
var log4js = require('../log4js'),
net = require('net'),
END_MSG = '__LOG4JS__';
var LogServer = function createLogServer(config) {
var actualAppender = config.actualAppender;
var server = net.createServer(function serverCreated(clientSocket) {
clientSocket.on('connect', function clientConnected() {
var logMessage = '';
clientSocket.on('data', function chunkReceived(chunk) {
logMessage += chunk;
});
clientSocket.on('end', function gotChunks() {
/**
* Creates a server, listening on config.loggerPort, config.loggerHost.
* Output goes to config.actualAppender (config.appender is used to
* set up that appender).
*/
function logServer(config) {
/**
* Takes a utf-8 string, returns an object with
* the correct log properties.
*/
function deserializeLoggingEvent(clientSocket, msg) {
var loggingEvent;
try {
var loggingEvent = JSON.parse(logMessage);
deserializeLoggingEvent(loggingEvent);
actualAppender(loggingEvent);
loggingEvent = JSON.parse(msg);
loggingEvent.startTime = new Date(loggingEvent.startTime);
loggingEvent.level.toString = function levelToString() {
return loggingEvent.level.levelStr;
};
} catch (e) {
// JSON.parse failed, just log the contents probably a naughty.
actualAppender(createLoggingEvent('ERROR', 'Unable to parse log: ' + logMessage));
// JSON.parse failed, just log the contents probably a naughty.
loggingEvent = {
startTime: new Date(),
categoryName: 'log4js',
level: { toString: function () {
return 'ERROR';
}
},
data: [ 'Unable to parse log:', msg ]
};
}
});
});
});
server.listen(config.loggerPort || 5000, config.loggerHost || 'localhost');
}
function createLoggingEvent(level, message) {
return {
startTime: new Date(),
categoryName: 'log4js',
level: { toString: function () {
return level;
}},
data: [ message ]
};
}
loggingEvent.remoteAddress = clientSocket.remoteAddress;
loggingEvent.remotePort = clientSocket.remotePort;
function deserializeLoggingEvent(loggingEvent) {
loggingEvent.startTime = new Date(loggingEvent.startTime);
loggingEvent.level.toString = function levelToString() {
return loggingEvent.level.levelStr;
};
return loggingEvent;
}
var actualAppender = config.actualAppender,
server = net.createServer(function serverCreated(clientSocket) {
clientSocket.setEncoding('utf8');
clientSocket.on('connect', function clientConnected() {
var logMessage = '';
function logTheMessage(msg) {
if (logMessage.length > 0) {
actualAppender(deserializeLoggingEvent(clientSocket, msg));
}
}
function chunkReceived(chunk) {
var event;
logMessage += chunk || '';
if (logMessage.indexOf(END_MSG) > -1) {
event = logMessage.substring(0, logMessage.indexOf(END_MSG));
logTheMessage(event);
logMessage = logMessage.substring(event.length + END_MSG.length) || '';
//check for more, maybe it was a big chunk
chunkReceived();
}
}
clientSocket.on('data', chunkReceived);
clientSocket.on('end', chunkReceived);
});
});
server.listen(config.loggerPort || 5000, config.loggerHost || 'localhost');
return actualAppender;
}
function workerAppender(config) {
return function log(loggingEvent) {
var socket = net.createConnection(config.loggerPort || 5000, config.loggerHost || 'localhost');
socket.on('connect', function socketConnected() {
socket.end(JSON.stringify(loggingEvent), 'utf8');
});
};
var canWrite = false,
buffer = [],
socket;
createSocket();
function createSocket() {
socket = net.createConnection(config.loggerPort || 5000, config.loggerHost || 'localhost');
socket.on('connect', function() {
emptyBuffer();
canWrite = true;
});
socket.on('timeout', socket.end.bind(socket));
//don't bother listening for 'error', 'close' gets called after that anyway
socket.on('close', createSocket);
}
function emptyBuffer() {
var evt;
while ((evt = buffer.shift())) {
write(evt);
}
}
function write(loggingEvent) {
socket.write(JSON.stringify(loggingEvent), 'utf8');
socket.write(END_MSG, 'utf8');
}
return function log(loggingEvent) {
if (canWrite) {
write(loggingEvent);
} else {
buffer.push(loggingEvent);
}
};
}
function createAppender(config) {
if (config.mode === 'master') {
var server = new LogServer(config);
return config.actualAppender;
} else {
return workerAppender(config);
}
if (config.mode === 'master') {
return logServer(config);
} else {
return workerAppender(config);
}
}
function configure(config) {
var actualAppender;
if (config.appender && config.mode === 'master') {
log4js.loadAppender(config.appender.type);
actualAppender = log4js.appenderMakers[config.appender.type](config.appender);
config.actualAppender = actualAppender;
}
return createAppender(config);
var actualAppender;
if (config.appender && config.mode === 'master') {
log4js.loadAppender(config.appender.type);
actualAppender = log4js.appenderMakers[config.appender.type](config.appender);
config.actualAppender = actualAppender;
}
return createAppender(config);
}

@@ -74,0 +132,0 @@

var layouts = require("../layouts"),
mailer = require("nodemailer");
mailer = require("nodemailer"),
os = require('os');
/**
* SMTP Appender. Sends logging events using SMTP protocol.
* SMTP Appender. Sends logging events using SMTP protocol.
* It can either send an email on each event or group several logging events gathered during specified interval.
*
* @param recipients comma separated list of email recipients
* @param sender sender of all emails (defaults to SMTP user)
* @param subject subject of all email messages (defaults to first event's message)
* @param config appender configuration data
* @param layout a function that takes a logevent and returns a string (defaults to basicLayout).
* @param smtpConfig SMTP configuration for 'nodemailer'
* @param sendInterval the time in seconds between sending attempts (defaults to 0);
* all events are buffered and sent in one email during this time; if 0 than every event sends an email
*/
function smtpAppender(recipients, sender, subject, layout, smtpConfig, sendInterval) {
sender = sender || smtpConfig.user;
function smtpAppender(config, layout) {
layout = layout || layouts.basicLayout;
subjectLayout = layouts.messagePassThroughLayout;
mailer.SMTP = smtpConfig;
sendInterval = sendInterval*1000 || 0;
var subjectLayout = layouts.messagePassThroughLayout;
var sendInterval = config.sendInterval*1000 || 0;
var logEventBuffer = [];
var sendTimer;
var transport = mailer.createTransport(config.transport, config[config.transport]);
function sendBuffer() {
if (logEventBuffer.length == 0)
return;
var firstEvent = logEventBuffer[0];

@@ -35,10 +31,12 @@ var body = "";

}
var msg = {
sender: sender,
to: recipients,
subject: subject || subjectLayout(firstEvent),
body: body
to: config.recipients,
subject: config.subject || subjectLayout(firstEvent),
text: body,
headers: {"Hostname": os.hostname()}
};
mailer.send_mail(msg, function(error, success) {
if (config.sender)
msg.from = config.sender;
transport.sendMail(msg, function(error, success) {
if (error) {

@@ -49,11 +47,11 @@ console.error("log4js.smtpAppender - Error happened ", error);

}
function scheduleSend() {
if (!sendTimer)
sendTimer = setTimeout(function() {
sendTimer = null;
sendTimer = null;
sendBuffer();
}, sendInterval);
}
return function(loggingEvent) {

@@ -73,6 +71,8 @@ logEventBuffer.push(loggingEvent);

}
return smtpAppender(config.recipients, config.sender, config.subject, layout, config.smtp, config.sendInterval);
return smtpAppender(config, layout);
}
exports.name = "smtp";
exports.appender = smtpAppender;
exports.configure = configure;
var dateFormat = require('./date_format')
, util = require('util')
, replacementRegExp = /%[sdj]/g
, layoutMakers = {
"messagePassThrough": function() { return messagePassThroughLayout; }
, "basic": function() { return basicLayout; }
, "colored": function() { return colouredLayout; }
, "coloured": function() { return colouredLayout; }
, "pattern": function (config) {
var pattern = config.pattern || undefined;
return patternLayout(pattern);
}
}
, colours = {
ALL: "grey"
, TRACE: "blue"
, DEBUG: "cyan"
, INFO: "green"
, WARN: "yellow"
, ERROR: "red"
, FATAL: "magenta"
, OFF: "grey"
};
, os = require('os')
, eol = os.EOL || '\n'
, util = require('util')
, replacementRegExp = /%[sdj]/g
, layoutMakers = {
"messagePassThrough": function() { return messagePassThroughLayout; }
, "basic": function() { return basicLayout; }
, "colored": function() { return colouredLayout; }
, "coloured": function() { return colouredLayout; }
, "pattern": function (config) {
var pattern = config.pattern || undefined;
return patternLayout(pattern);
}
}
, colours = {
ALL: "grey"
, TRACE: "blue"
, DEBUG: "cyan"
, INFO: "green"
, WARN: "yellow"
, ERROR: "red"
, FATAL: "magenta"
, OFF: "grey"
};

@@ -28,4 +30,4 @@

var output = ""
, data = Array.isArray(logData) ? logData.slice() : Array.prototype.slice.call(arguments)
, format = data.shift();
, data = Array.isArray(logData) ? logData.slice() : Array.prototype.slice.call(arguments)
, format = data.shift();

@@ -201,3 +203,3 @@ if (typeof format === "string") {

case "n":
replacement = "\n";
replacement = eol;
break;

@@ -262,2 +264,2 @@ case "p":

}
};
};
{
"name": "log4js",
"version": "0.5.0",
"version": "0.5.1",
"description": "Port of Log4js to work with node.",

@@ -5,0 +5,0 @@ "keywords": [

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

NOTE: from log4js 0.5 onwards you'll need to explicitly enable replacement of node's console.log functions. Do this either by calling `log4js.replaceConsole()` or configuring with an object or json file like this:
```javascript
{
appenders: [
{ type: "console" }
],
replaceConsole: true
}
```
## installation

@@ -39,8 +49,9 @@

See example.js:
See example.js for a full example, but here's a snippet (also in fromreadme.js):
var log4js = require('log4js');
log4js.loadAppender('console');
//console log is loaded by default, so you won't normally need to do this
//log4js.loadAppender('console');
log4js.loadAppender('file');
log4js.addAppender(log4js.appenders.console());
//log4js.addAppender(log4js.appenders.console());
log4js.addAppender(log4js.appenders.file('logs/cheese.log'), 'cheese');

@@ -119,9 +130,9 @@

Documentation for most of the core appenders can be found on the [wiki](wiki/Appenders), otherwise take a look at the tests and the examples.
Documentation for most of the core appenders can be found on the [wiki](log4js-node/wiki/Appenders), otherwise take a look at the tests and the examples.
## Documentation
See the [wiki](wiki). Improve the [wiki](wiki), please.
See the [wiki](log4js-node/wiki). Improve the [wiki](log4js-node/wiki), please.
## Contributing
Contributions welcome, but take a look at the [rules](wiki/Contributing) first.
Contributions welcome, but take a look at the [rules](log4js-node/wiki/Contributing) first.

@@ -128,0 +139,0 @@ ## License

@@ -579,3 +579,2 @@ var vows = require('vows')

}
}).export(module);

@@ -10,12 +10,17 @@ var vows = require('vows'),

var fakeMailer = {
send_mail: function (msg, callback) {
msgs.push(msg);
callback(null, true);
}
createTransport: function (name, options) {
return {
config: options,
sendMail: function (msg, callback) {
msgs.push(msg);
callback(null, true);
}
};
}
};
var smtpModule = sandbox.require('../lib/appenders/smtp', {
requires: {
'nodemailer': fakeMailer
}
requires: {
'nodemailer': fakeMailer
}
});

@@ -26,5 +31,5 @@

return {
logger: log4js.getLogger(category),
mailer: fakeMailer,
results: msgs
logger: log4js.getLogger(category),
mailer: fakeMailer,
results: msgs
};

@@ -35,6 +40,6 @@ }

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));
assert.equal(result.results[i].from, sender);
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].text));
}

@@ -46,121 +51,122 @@ }

'minimal config': {
topic: function() {
var setup = setupLogging('minimal config', {
recipients: 'recipient@domain.com',
smtp: {
port: 25,
user: 'user@domain.com'
topic: function() {
var setup = setupLogging('minimal config', {
recipients: 'recipient@domain.com',
transport: "SMTP",
SMTP: {
port: 25,
auth: {
user: 'user@domain.com'
}
}
});
setup.logger.info('Log event #1');
return setup;
},
'there should be one message only': function (result) {
assert.equal(result.results.length, 1);
},
'message should contain proper data': function (result) {
checkMessages(result);
}
});
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);
}
},
'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'
topic: function() {
var setup = setupLogging('fancy config', {
recipients: 'recipient@domain.com',
sender: 'sender@domain.com',
subject: 'This is subject',
transport: "SMTP",
SMTP: {
port: 25,
auth: {
user: 'user@domain.com'
}
}
});
setup.logger.info('Log event #1');
return setup;
},
'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');
}
});
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');
}
},
'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'
topic: function() {
var self = this;
var setup = setupLogging('separate email for each event', {
recipients: 'recipient@domain.com',
transport: "SMTP",
SMTP: {
port: 25,
auth: {
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);
}
});
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);
}
},
'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'
topic: function() {
var self = this;
var setup = setupLogging('multiple events in one email', {
recipients: 'recipient@domain.com',
sendInterval: 1,
transport: "SMTP",
SMTP: {
port: 25,
auth: {
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].to, 'recipient@domain.com');
assert.equal(result.results[0].subject, 'Log event #1');
assert.equal(result.results[0].text.match(new RegExp('.+Log event #[1-2]$', 'gm')).length, 2);
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].text));
}
});
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));
}
}
}).export(module);

Sorry, the diff of this file is not supported yet

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