Skip to content
Browse files

added a nice logger instead of console

  • Loading branch information...
1 parent e36cc11 commit 321b63b774ae29f3d22ebd7df34216670c88d363 Geoff Flarity committed Feb 7, 2012
View
14 lib/graphite_axon.js
@@ -2,6 +2,10 @@ var net = require('net');
var events = require("events");
var util = require('util');
+var streamlogger_helper = require('./streamlogger_helper');
+
+//get the main logger
+var log = streamlogger_helper.getStreamLogger( 'main' );
//TODO eventually this Axon should share a connection to graphite
@@ -31,7 +35,7 @@ var GraphiteAxon = function ( namespace, host, port) {
//connect message
var on_connect = function() {
- console.log( 'graphite connected' );
+ log.info( 'graphite connected' );
this_axon.tcp_connection.setKeepAlive( true );
@@ -57,7 +61,7 @@ var GraphiteAxon = function ( namespace, host, port) {
//TODO create an error message and enque it
//log error
- console.log( 'graphite connection error: ' + error );
+ log.error( 'graphite connection error: ' + error );
//destroy the connection so that reconnect fires
this_axon.tcp_connection.destroy();
@@ -68,7 +72,7 @@ var GraphiteAxon = function ( namespace, host, port) {
//TODO create an end message
//log that we ended
- console.log( 'disconnected from graphite, reconnecting in 10000 ms' );
+ log.info( 'disconnected from graphite, reconnecting in 10000 ms' );
//reconnect after 1000 ms
setTimeout( function () {
@@ -101,7 +105,7 @@ GraphiteAxon.prototype.fire = function( name, value, timestamp ) {
this_axon.tcp_connection.write( line );
} catch ( e ) {
- console.log( 'write to graphite failed: ' + e );
+ log.error( 'write to graphite failed: ' + e );
//TODO need to resend these
this.message_buffer.push ( line );
@@ -114,7 +118,7 @@ GraphiteAxon.prototype.misfire = function( error ) {
this_axon = this;
- console.log( 'misfire: ' + error );
+ log.error( 'misfire: ' + error );
var name = 'nervous.misfire';
this_axon.fire( name, 1 );
View
9 lib/nervous.js
@@ -1,10 +1,19 @@
//deps
var fs = require('fs');
var path = require('path');
+var steamlogger_helper = require('./streamlogger_helper');
//code
+
+//get a logger for for a log file relative to this path with the id 'main'
+
+
var load_plugins = function () {
var full_path_of_config = require.resolve( '../conf/nervous.json' );
+ debugger;
+ var root_path = path.resolve(full_path_of_config, '../..');
+ var logger = steamlogger_helper.createStreamLogger( 'main', root_path + '/log/nervous.log');
+
var config = JSON.parse(fs.readFileSync( full_path_of_config ) );
var system_type = config.system_type;
View
2 lib/node_modules/streamlogger/.npmignore
@@ -0,0 +1,2 @@
+*.swp
+*.log
View
19 lib/node_modules/streamlogger/LICENSE
@@ -0,0 +1,19 @@
+Copyright (c) 2010 Andrew Cholakian <andrew@andrewvc.com>
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
View
114 lib/node_modules/streamlogger/README.md
@@ -0,0 +1,114 @@
+# Node-Streamlogger
+
+## About
+
+A node.js library for extremely customizable logging
+
+## Features
+
+ * Arbitrary user definable severity levels with debug, info, warn, fatal by default
+ * Custom output formats
+ * Almost all events are listenable
+ * Writing to multiple files simultaneously
+ * Log rotation (reopening log files on demand)
+
+## Simple Example (From simple-example.js)
+
+ var
+ sys = require('sys'),
+ http = require('http'),
+ streamLogger = require('./lib/streamlogger'),
+ logger = new streamLogger.StreamLogger('log1.log');
+ //Defaults to info, debug messages will not be logged at info
+ logger.level = logger.levels.debug;
+
+ http.createServer(function(req, res) {
+ //Other default levels are .debug .warn and .fatal
+ logger.info("My Info message");
+
+ res.writeHead(200);
+ res.write("Hello!");
+ res.end();
+ }).listen(8000);
+
+ //If you want to rotate logs, this will re-open the files on sighup
+ process.addListener("SIGHUP", function() {
+ logger.reopen();
+ });
+
+## Full (Ridiculous) Example (Taken from example.js)
+
+ var
+ sys = require('sys'),
+ path = require('path'),
+ http = require('http'),
+ streamLogger = require('./lib/streamlogger'),
+ logger = new streamLogger.StreamLogger('log1.log','log2.log');
+
+ logger.level = logger.levels.info; //Defaults to info
+ logger.emitter
+ .addListener('open', function() {
+ sys.puts("All streams are open");
+ })
+ .addListener('error', function(err,logPath) {
+ sys.puts("Error: " + err + " while writing to " + logPath);
+ })
+ .addListener('message', function(message,levelName) {
+ sys.puts("Received message: " + message + " with level " + levelName);
+ })
+ .addListener('loggedMessage', function(message,levelName) {
+ //Only gets called for levels allowed by StreamLogger#level
+ sys.puts("Logged message: " + message + " with level " + levelName);
+ })
+ .addListener('close', function() {
+ sys.puts("All loggers closed");
+ })
+ //Alternate style
+ .addListener('message-info', function(message) {
+ sys.puts("OnlyInfo");
+ })
+ .addListener('loggedMessage-info', function(message) {
+ sys.puts("Logged OnlyInfo");
+ });
+
+ //If you want to rotate logs, this will re-open the files on sighup
+ process.addListener("SIGHUP", function() {
+ logger.reopen();
+ });
+
+ http.createServer(function(req, res) {
+ logger.debug("DebugMsg"); //Won't get printed since log level was set to debug
+ logger.info("InfoMsg");
+ logger.warn("WarnMsg", function () {sys.puts("MSG flushed to kernel")});
+ logger.fatal("FatalMsg");
+
+ res.writeHead(200);
+ res.write("Hello!");
+ res.end();
+
+ //Setting a custom format, note that since this is an async lib
+ //setting the format here WILL affect messages outputted prior during this
+ //tick, and possibly the next
+ logger.format = function(message,levelName) {
+ if (levelName == 'warn')
+ return "Custom message: " + message;
+ else
+ return false; //Use the default format
+ }
+ logger.warn("Should be custom");
+ logger.info("Should be standard");
+
+ //Setting custom log levels, note that since this is an async lib this can
+ //can cause problems with calls sent earlier in this tick if you delete
+ //an existing log level
+ var levels = logger.levels;
+ levels.extraFatal = levels.fatal + 1;
+ //This will not work, as emitter is an existing property of the logger
+ //Trying to set this will cause logger to emit an 'error'
+ levels.emitter = 20;
+ logger.levels = levels;
+ logger.extraFatal("I've been shot through the heart!");
+ }).listen(8000);
+
+## Copyright
+ Copyright Andrew Cholakian, released under the MIT License (see LICENSE)
View
5 lib/node_modules/streamlogger/debian/changelog
@@ -0,0 +1,5 @@
+nodejs-streamlogger (0.0.1-0sg0) unstable; urgency=low
+
+ * Debianized
+
+ -- Wade Simmons <wade@simplegeo.com> Mon, 01 Nov 2010 16:21:01 -0600
View
1 lib/node_modules/streamlogger/debian/compat
@@ -0,0 +1 @@
+5
View
13 lib/node_modules/streamlogger/debian/control
@@ -0,0 +1,13 @@
+Source: nodejs-streamlogger
+Section: misc
+Priority: extra
+Uploaders: Wade Simmons <wade@simplegeo.com>
+Maintainer: SimpleGeo Nerds <nerds@simplegeo.com>
+build-Depends: cdbs, debhelper (>= 7)
+Standards-Version: 3.9.1
+
+Package: nodejs-streamlogger
+Depends: nodejs (>= 0.2.3), ${misc:Depends}
+Architecture: all
+Description: node-streamlogger
+ http://github.com/andrewvc/node-streamlogger
View
9 lib/node_modules/streamlogger/debian/copyright
@@ -0,0 +1,9 @@
+This package was debianised by Wade Simmons <wade@simplegeo.com>
+
+The upstream repo is:
+ http://github.com/andrewvc/node-streamlogger
+ MIT license
+
+The Debian packaging is
+ Copyright 2010, SimpleGeo, Inc.
+ MIT license
View
1 lib/node_modules/streamlogger/debian/dirs
@@ -0,0 +1 @@
+usr/lib/nodejs
View
1 lib/node_modules/streamlogger/debian/install
@@ -0,0 +1 @@
+lib/streamlogger.js /usr/lib/nodejs
View
3 lib/node_modules/streamlogger/debian/rules
@@ -0,0 +1,3 @@
+#!/usr/bin/make -f
+
+include /usr/share/cdbs/1/rules/debhelper.mk
View
1 lib/node_modules/streamlogger/debian/source/format
@@ -0,0 +1 @@
+3.0 (quilt)
View
71 lib/node_modules/streamlogger/example.js
@@ -0,0 +1,71 @@
+var
+ sys = require('sys'),
+ path = require('path'),
+ http = require('http'),
+ streamLogger = require('./lib/streamlogger'),
+ logger = new streamLogger.StreamLogger('log1.log','log2.log');
+
+logger.level = logger.levels.info; //Defaults to info
+logger.emitter
+ .addListener('open', function() {
+ sys.puts("All streams are open");
+ })
+ .addListener('error', function(err,logPath) {
+ sys.puts("Error: " + err + " while writing to " + logPath);
+ })
+ .addListener('message', function(message,levelName) {
+ sys.puts("Received message: " + message + " with level " + levelName);
+ })
+ .addListener('loggedMessage', function(message,levelName) {
+ //Only gets called for levels allowed by StreamLogger#level
+ sys.puts("Logged message: " + message + " with level " + levelName);
+ })
+ .addListener('close', function() {
+ sys.puts("All loggers closed");
+ })
+ //Alternate style
+ .addListener('message-info', function(message) {
+ sys.puts("OnlyInfo");
+ })
+ .addListener('loggedMessage-info', function(message) {
+ sys.puts("Logged OnlyInfo");
+ });
+
+//If you want to rotate logs, this will re-open the files on sighup
+process.addListener("SIGHUP", function() {
+ logger.reopen();
+});
+
+http.createServer(function(req, res) {
+ logger.debug("DebugMsg"); //Won't get printed since log level was set to debug
+ logger.info("InfoMsg");
+ logger.warn("WarnMsg", function () {sys.puts("MSG flushed to kernel")});
+ logger.fatal("FatalMsg");
+
+ res.writeHead(200);
+ res.write("Hello!");
+ res.end();
+
+ //Setting a custom format, note that since this is an async lib
+ //setting the format here WILL affect messages outputted prior during this
+ //tick, and possibly the next
+ logger.format = function(message,levelName) {
+ if (levelName == 'warn')
+ return "Custom message: " + message;
+ else
+ return false; //Use the default format
+ }
+ logger.warn("Should be custom");
+ logger.info("Should be standard");
+
+ //Setting custom log levels, note that since this is async lib this can
+ //can cause problems with calls sent earlier in this tick, if you delete
+ // an existing log level
+ var levels = logger.levels;
+ levels.extraFatal = levels.fatal + 1;
+ //This will not work, as emitter is an existing property of the logger
+ //Trying to set this will cause logger to emit an 'error'
+ levels.emitter = 20;
+ logger.levels = levels;
+ logger.extraFatal("I've been shot through the heart!");
+}).listen(8000);
View
158 lib/node_modules/streamlogger/lib/streamlogger.js
@@ -0,0 +1,158 @@
+var
+
+ fs = require('fs'),
+ events = require('events'),
+ clone = function (obj) {
+ if(obj == null || typeof(obj) != 'object')
+ return obj;
+ var temp = obj.constructor(); // changed
+ for(var key in obj)
+ temp[key] = clone(obj[key]);
+ return temp;
+ };
+
+
+var StreamLogger = exports.StreamLogger = function() {
+ this.filePaths = [];
+ for (var i = arguments.length; i != 0; i--)
+ this.filePaths.push(arguments[i - 1]);
+ this.fstreams = [];
+ this.emitter = new events.EventEmitter();
+ this.levels = {debug: 0, info:1, warn:2, fatal:3};
+ this.level = this.levels.info;
+
+ // used while re-opening the stream
+ this.logQueue = [];
+
+ this.open();
+};
+
+StreamLogger.prototype.__defineGetter__("levels", function() {
+ return clone(this.levelList);
+});
+StreamLogger.prototype.__defineSetter__("levels", function(newLevels) {
+ this.levelList = this.levelList || {};
+
+ //Make sure the level name doesn't conflict with an existing function name
+ for(var newLevel in newLevels) {
+ if (this[newLevel] && (this.levelList[newLevel] == undefined)) {
+ this.emitter.emit("error", "Invalid log level '" + newLevel + "', conflicting name");
+ delete(newLevels[newLevel]);
+ }
+ }
+
+ this.levelList = newLevels;
+
+ //Build a reverse mapping of level values to keys, for fast lookup later
+ this.revLevels = {}
+ for (var lName in this.levelList) {
+ var lVal = this.levels[lName];
+ this.revLevels[lVal]= lName;
+ }
+
+ //Remove old levels
+ for (var oldLevel in this.levelList)
+ delete(this[oldLevel]);
+
+ //Setup a method for each log level
+ for (var logLevel in this.levelList) {
+ this[logLevel] = (function(logLevel) {
+ return function (message,callback) {
+ this.logAtLevel(message, this.levelList[logLevel], callback);
+ }
+ })(logLevel);
+ }
+});
+
+//Create write streams for all the files, emit 'open', if/when
+//all streams open. Will fire callback after as well
+StreamLogger.prototype.open = function(callback) {
+ var emitter = this.emitter;
+ for (var i = this.filePaths.length; i != 0; i--) {
+ var filePath = this.filePaths[i - 1];
+ var unopenedFilePathCount = this.filePaths.length;
+ var stream = fs.createWriteStream(filePath,
+ {flags: 'a', mode: 0644, encoding: 'utf8'}
+ )
+ .addListener('open', function(fd) {
+ unopenedFilePathCount--;
+ if (unopenedFilePathCount == 0) {
+ emitter.emit("open");
+ if (callback)
+ callback();
+ }
+ })
+ .addListener('error', function(err) {
+ emitter.emit('error', err,filePath)
+ });
+ this.fstreams.push(stream);
+ }
+};
+
+//Close all write streams, fire the callback after all streams are closed
+//Also emits 'close' after all streams are closed
+StreamLogger.prototype.close = function(callback) {
+ for (var i = this.fstreams.length; i !=0; i--) {
+ this.fstreams[i - 1].end();
+ }
+ //We're done closing, so emit the callbacks, then remove the fstreams
+ this.fstreams = [];
+ this.emitter.emit("close");
+ if (callback)
+ callback();
+};
+
+StreamLogger.prototype.reopen = function(callback) {
+ var slSelf = this;
+ this.close(function() {
+ slSelf.open(function() {
+ slSelf.logQueue.forEach(function(msg) {
+ slSelf._log.apply(slSelf, msg);
+ });
+ slSelf.logQueue = [];
+ if (callback)
+ callback();
+ });
+ });
+};
+
+StreamLogger.prototype.logAtLevel = function(message,level,callback) {
+ var levelName = this.revLevels[level];
+ this.emitter.emit('message', message, levelName);
+ this.emitter.emit('message-' + levelName, message);
+
+ if (level < this.level)
+ return false
+
+ this.emitter.emit('loggedMessage', message, levelName);
+ this.emitter.emit('loggedMessage-' + levelName, message);
+
+ //Check if there's a custom formatting callback
+ if (this.format)
+ var outMessage = this.format(message,levelName);
+ else
+ var outMessage = (new Date).toUTCString() + ' - ' +
+ levelName + ': ' + message;
+
+ this._log(outMessage, callback);
+}
+
+StreamLogger.prototype._log = function(outMessage, callback) {
+ if (this.fstreams.length == 0) {
+ this.logQueue.push(arguments);
+ return;
+ }
+
+ for (var i = this.fstreams.length; i != 0; i--) {
+ var fstream = this.fstreams[i - 1];
+ //Ideally we could trap the errors #write creates, I'm not sure
+ //if thats possible though
+ if (fstream.writable || fstream.writeable) {
+ fstream.write(outMessage + "\n");
+ if (callback)
+ callback();
+ }
+ else
+ this.emitter.emit('error',"Stream not writable", fstream.path);
+ }
+};
View
8 lib/node_modules/streamlogger/package.json
@@ -0,0 +1,8 @@
+{
+ "name": "streamlogger",
+ "description": "node-streamlogger",
+ "version": "0.0.1",
+ "author": "Andrew Cholakian <andrew@andrewvc.com>",
+ "main": "./lib/streamlogger.js",
+ "engines": { "node": ">= 0.2.1" }
+}
View
21 lib/node_modules/streamlogger/simple-example.js
@@ -0,0 +1,21 @@
+var
+ sys = require('sys'),
+ http = require('http'),
+ streamLogger = require('./lib/streamlogger'),
+ logger = new streamLogger.StreamLogger('log1.log');
+ //Defaults to info, debug messages will not be logged at info
+ logger.level = logger.levels.debug;
+
+http.createServer(function(req, res) {
+ //Other default levels are .debug .warn and .fatal
+ logger.info("My Info message");
+
+ res.writeHead(200);
+ res.write("Hello!");
+ res.end();
+}).listen(8000);
+
+//If you want to rotate logs, this will re-open the files on sighup
+process.addListener("SIGHUP", function() {
+ logger.reopen();
+});
View
5 lib/stdout_axon.js
@@ -2,6 +2,9 @@
var net = require('net');
var util = require('util');
var events = require("events");
+var streamlogger_helper = require('./streamlogger_helper');
+
+var log = streamlogger_helper.getStreamLogger( 'main' );
//code
var STDOUTAxon = function ( namespace) {
@@ -41,7 +44,7 @@ STDOUTAxon.prototype.fire = function( name, value, timestamp ) {
STDOUTAxon.prototype.misfire = function( err ) {
this_axon = this;
- console.log(err);
+ log.error(err);
};
View
30 lib/streamlogger_helper.js
@@ -0,0 +1,30 @@
+//deps
+var streamlogger = require( 'streamlogger' );
+
+var loggers = {};
+
+module.exports.createStreamLogger = function ( id, log_path ) {
+
+ var logger;
+ if ( loggers[id] ) {
+
+ logger = loggers[id];
+ }
+ else {
+
+ logger = new streamlogger.StreamLogger( log_path );
+
+ //this is a bit obfuscated, but I really think fatal should be called error
+ logger.error = logger.fatal;
+
+ loggers[id] = logger;
+ }
+
+ return logger;
+};
+
+
+module.exports.getStreamLogger = function ( id ) {
+
+ return loggers[id];
+};
View
0 log/.keep
No changes.

0 comments on commit 321b63b

Please sign in to comment.
Something went wrong with that request. Please try again.