npm install @r3wt/log --save
a simple logger for node.js
I wanted a logger with these features:
- identical output/features provided by
console.log, but with:- color coded log levels
- timestamps
- multiple, customizable transports (console and file built in)
- optional ability to override
consolefunctionslog,warn,error,andinfoglobally for ease of integration.
I found this library from quirkey and modified it according to the above principals.
The logger uses (
syslog)[https://en.wikipedia.org/wiki/Syslog#Severity_level] style log levels, shown below in order of priority (least to greatest):debug , info , notice , warning , error , crit , alert , emerg
The logger has named methods for each of the above log levels (see code examples below)
Any of the logging methods take
narguments, which are each joined by ' ' (similar toconsole.log()).You set the default log level, and nothing with a lower priority is logged.
| function | options | example |
|---|---|---|
createLogger(Object options) | {log_level: String, transports: Array< String|Object >, debug: Bool } | createLogger ({log_level:'warning'}) |
a few common use cases are shown below
create a logger and use the log instance:
const{createLogger}=require('@r3wt/log');constlog=createLogger();log('the quick %s fox jumped %s the %s %s','brown','over','lazy','dog');//default level is info. log.warning('uh oh!');log.error('oh fudge some bad stuff happened',newError('am bad stuff. did happen'),{someOtherData:true});// works just like the console, you get the point right?setting the log level:
const{createLogger}=require('@r3wt/log');constlog=createLogger({log_level:'warning'});wrapping console globally:
const{createLogger,wrapConsole,unwrapConsole}=require('@r3wt/log');constlog=createLogger();wrapConsole(log);//wraps the console globally with the log instance, making integration into large existing project less painful// NOTE: only the following 4 functions are wrapped. console.log('hi!');console.warn('warning');console.error('error');console.info('info');unwrapConsole();//unwrap console globallyusing built in transports file and console:
const{createLogger}=require('@r3wt/log');constlog=createLogger({transports:['console','file']});//log to console and file. file logger defaults to `process.cwd()` with file names `combined.log` and `error.log` respectively.providing options to built in transports:
const{createLogger}=require('@r3wt/log');constFileTransport=require('@r3wt/log/transports/file');constConsoleTransport=require('@r3wt/log/transports/console');constmyFileTransport=newFileTransport({nextTick: true,//delay writing file until process.nextTick function queue is processederror:'./my-custom-error-file.log',combined: './my-custom-combined-file.log'});constmyConsoleTransport=newConsoleTransport({nextTick:true//NOTE: if process exits with this enabled, any queued writes to stderr/stdout will be lost. });constlog=createLogger({transports:[myFileTransport,myConsoleTransport]});providing custom transports:
const{createLogger}=require('@r3wt/log');//technique 1 write formatted messagesclassCustomTransport1{write(message,level,logger){// basic transport must include a `write` function. see below for custom transports// the function is called with formatted message, log level of message, and the logger instance// do something with the message// your code here}}//technique 2 customize the formatting of your messagesclassCustomTransport2{//use writeCustom to take control of all formatting responsibilities.writeCustom(args,level,date,logger){// args are the original arguments passed to the logging function// level is the log level// date is a Date object for the time of the message// logger is the logger instance// your code here}}constmyTransport1=newCustomTransport1;constmyTransport2=newCustomTransport2;constlog=createLogger({transports: ['console',myTransport1,myTransport2]//in this example we keep the default console and add our custom Transports as well});providing a custom date formatter:
const{createLogger}=require('@r3wt/log');constmyDateFormatter=(date)=>{//format a date how you likereturndate.toLocaleString('en-GB',{timeZone: 'UTC'});};constlog=createLogger({formatDate: myDateFormatter});all log functions:
const{createLogger}=require('@r3wt/log');log('hi!');// alias to log.info()log.debug('blah blah blah');log.info('hi!');log.notice('a notice');log.warning('warning message');log.error(newError('test'));log.crit('a critical error');log.alert('an important error');log.emerg('an emergency error');all exports:
const{createLogger,Logger,wrapConsole,unwrapConsole,isFormattableString}=require('@r3wt/log');constlogger=createLogger();log.logger;// Logger this is the low level Logger instance. it has some functions you can call directlylog.logger.setTransports([consoleTransport]);//sets the transports on the flylog.logger.setLevel('warning');//set lo level on the flylog.logger.setDateFormat(function(date){returndate.getTime();});//set the date formatter on the flyMIT, see the source.