Skip to content

Instantly share code, notes, and snippets.

@ldesplat
Last active Aug 29, 2015
Embed
What would you like to do?
var Log = require('./log');
function convertLogs(event) {
var LogEvent = {
event: event.data,
tags: event.tags
};
if (event.request) {
LogEvent.request = event.request;
}
if (LogEvent.event instanceof Error) {
LogEvent.event = LogEvent.event.toString();
}
if (LogEvent.tags.indexOf('hapi') !== -1) {
LogEvent.comp = 'hapi';
Log.info(LogEvent);
} else if (LogEvent.tags.indexOf('trace') !== -1) {
Log.trace(LogEvent);
} else if (LogEvent.tags.indexOf('debug') !== -1) {
Log.debug(LogEvent);
} else if (LogEvent.tags.indexOf('info') !== -1) {
Log.info(LogEvent);
} else if (LogEvent.tags.indexOf('warn') !== -1) {
Log.warn(LogEvent);
} else if (LogEvent.tags.indexOf('error') !== -1) {
Log.error(LogEvent);
} else if (LogEvent.tags.indexOf('fatal') !== -1) {
Log.fatal(LogEvent);
} else {
Log.info(LogEvent);
}
}
var api = new Hapi.Server();
api.pack.events.on('log', function(event, tags) {
convertLogs(event);
});
api.pack.events.on('request', function(request, event, tags) {
convertLogs(event);
});
'use strict';
var bunyan = require('bunyan');
var stream = require('stream');
function mapLevels(logLevel) {
switch(logLevel) {
case 10:
return 'TRACE';
case 20:
return 'DEBUG';
case 30:
return 'INFO';
case 40:
return 'WARN';
case 50:
return 'ERROR';
case 60:
return 'FATAL';
default:
return "UNKNOWN";
}
}
var prettyStream = new stream.Writable();
prettyStream._write = function(chunk, encoding, callback) {
try {
var logObj = JSON.parse(chunk.toString());
var msg = logObj.msg;
if (!msg || msg === '') {
msg = logObj.event;
}
if (!msg) {
return callback();
}
var comp = logObj.name;
if (logObj.comp) {
comp = logObj.comp;
}
if (logObj.request) {
if (msg.method) {
console.log('[' + comp + ']','[' + mapLevels(logObj.level) + ']', '[' + logObj.request + ']', msg.method, msg.url);
} else {
console.log('[' + comp + ']','[' + mapLevels(logObj.level) + ']', '[' + logObj.request + ']', msg);
}
} else {
console.log('[' + comp + ']','[' + mapLevels(logObj.level) + ']', msg);
}
} catch (err) {
console.error(err);
}
callback();
};
var log = bunyan.createLogger(
{
name: 'yourname',
streams: [
{
path: 'yourlog.log'
},
{
stream: prettyStream,
level: 'trace'
}
]
});
module.exports = log;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment