meta2-logger
Simple logging library for NodeJS with support of facilities and multiple transports.
Logger has also first-class support for TypeScript and is fully documented.
Table of Contents:
- Features
- Installation
- Usage - TypeScript
- Usage - vanilla JS
- Facilities
- Setting log level
- Configuring Logging Targets
- Custom Logging Target
- Utility Functions
- Logging Stack Trace
- API Reference
- Development
- License
Features
Built-in transports:
- Console
- Text file
- JSON file
- Memory
- GrayLog
Log levels:
Library supports all of standard syslog levels.
- debug
- info
- notice
- warn
- error
- critical
- alert
- emergency
Other features:
- Facilities
- Meta-data
- Custom targets
- Colorized console output
- TypeScript decorators to simply enable logging on classes and methods
- Remote management server with UI and REST API provided by
meta2-logger-server
package
Installation
# Using NPM npm install meta2-logger # To save as dependency npm install --save meta2-logger
Usage (TypeScript)
; // Use global loggerlogger.info"From global logger"; // Or create new instance; // Setup targetslogger.toConsole.toFile"demo.log", .toJsonFile"demo.json", .toGrayLog; // Log some messageslogger.debug"Hello %s", "debug";logger.info"Hello %s", "info";logger.notice"Hello %s", "notice";logger.warn"Hello %s", "warn"; // or logger.warning("Hello %s", "warn");logger.error"Hello %s", "error";logger.crit"Hello %s", "critical";logger.alert"Hello %s", "alert";logger.emerg"Hello %s", "emergency"; // or logger.panic("Hello %s", "emergency"); // Create facility; facility.notice"Server started on port %d", 8080; // Passing meta-data using object as first argumentfacility.warn, "Bad request";
Usage (vanilla JS)
const Logger = ; // Accessing global logger instanceconst logger = Loggerdefault; // Or create new instanceconst logger = ; // Setup targetslogger; // Log some messageslogger;logger;logger;logger; // or logger.warning("Hello %s", "warn");logger;logger;logger;logger; // or logger.panic("Hello %s", "emergency"); // Create facilityconst facility = logger; facility; // Passing meta-data using object as first argumentfacility;
Facilities
Logging facility provides a way to decouple logging based on their purpose.
Creating facility from logger:
; // Create facility from main logger - options are optional; // We can change facility log level laterfacility.setLevelLOG_LEVEL.NOTICE;facility.getLevel; // -> LOG_LEVEL.NOTICE // Log to facilityfacility.info"Message"; // We can get existing facility instance by calling facility method again; // We can get map of all registered facilitieslogger.getAllFacilities; // -> { facilityName: LoggerFacility }
Creating facility manually:
; // Create facility and pass logger as first argument, options are optional; // Log to facilityfacility.info"Message";
Setting log level
Log levels can be set on logger, facility and on targets.
Classes Logger
, LoggerFacility
and logging targets support setLevel
and getLevel
methods.
Example:
; logger.setLevelLOG_LEVEL.INFO; logger.debug"Message"; //Does not loglogger.warn"Message"; //Does log logger.getLevel; //Returns LOG_LEVEL.INFO; // Changing log level on target(s)logger.toConsole; logger.getTarget"__console__".setLevelLOG_LEVEL.DEBUG;logger.getTarget"__console__".getLevel; // -> LOG_LEVEL.DEBUG // Also works on LoggerFacility; facility.setLevelLOG_LEVEL.WARN;facility.getLevel; // -> LOG_LEVEL.WARN
Configuring Logging Targets
Logging target represents destination transport for log messages.
; logger.to"uniqueLoggerId", new ConsoleTarget;
See built-in targets below. Logging target class must implement ILoggerTarget
interface.
Console Target
Prints log messages to stdout (console).
; logger.toConsole; // Orlogger.to"myConsole", new ConsoleTargetopts;
Sample output:
2018-01-10 14:24:30 warn: [http] (reqId=123) Bad request
2018-01-10 14:24:30 info: Something happend
eg.:
date time level: [facility] (meta=data) Formatted message
Notice: Method toConsole
overrides previous console target settings. Use logger.to(...)
method to define more targets.
File Target
Appends log messages to specified file.
Messages are formatted the same way as to the console.
File target can be set for multiple files with different configurations.
; logger.toFile"filename.log", ; // Orlogger.to"myFile", new FileTarget"filename.log", opts;
Sample output:
2018-01-10 14:24:30 warn: [http] (reqId=123) Bad request
2018-01-10 14:24:30 info: Something happend
JSON File Target
Appends log messages to specified JSON file.
File target can be set for multiple files with different configurations.
; logger.toJsonFile"filename.json", ; // Orlogger.to"myJsonFile", new JsonFileTarget"filename.json", opts;
Sample output:
{},
{ timestamp: 1515557050.342, level: 5, facility: "http", msg: "Bad request", meta: { reqId: 123 } },
{ timestamp: 1515557086.342, level: 7, facility: null, msg: "Something happend", meta: {} }
Recommended way to parse JSON log file:
const fs = ; const logFile = fs;const logMessages = JSON;
Memory Target
Stores log messages in memory.
; logger.toMemory; // Get messageslogger.getTarget"__memory__".getMessages; // Or; logger.to"myMemory", memTarget; memTarget.getMessages;
GrayLog Target
Sends log messages to GrayLog server using GELF protocol.
; logger.toGrayLog; // Orlogger.to"myGrayLogTarget", new GraylogTargetopts;
Notice: Message meta-data are added as additional fields.
Custom Logging Target
To create custom logging target define class which implements ILoggerTarget
interface. Or extend class BaseTarget
.
; ; // Use such targetlogger.to"suchTarget", new SuchTarget;
Utility Functions
parseLogLevel
This function parses log level from string to number. Is case insensitive.
Usage:
; logger.toConsole;
@Logging decorator
Decorator to configure and assign LoggerFacility
instance to a class.
Note: decorators are experimental TypeScript feature.
Usage:
; ; // Second argument can be omitted ;obj.doSomething; // -> will log debug: [facilityName] Hello
@LogMethodCall decorator
Decorator to log every method call. When @Logging
decorator is applied it's configuration will be used.
Note: decorators are experimental TypeScript feature.
Usage:
; ; // Second argument can be omitted ;obj.doSomething"hello", "world";
will log:
debug: [facilityName] (method=doSomething) (class=MyClass) Hey Method MyClass.doSomething called with arguments [ 'hello', 'world' ] at class_1.descriptor.value [as doSomething] (/path/to/app/node_modules/meta2-logger/dist/src/util.ts:90:38) at Logger.info (/path/to/app/node_modules/meta2-logger/dist/src/Logger.js:286:14) at Object.<anonymous> (/path/to/app/index.js:30:24) at Module._compile (module.js:571:32) at Object.Module._extensions..js (module.js:580:10) at Module.load (module.js:488:32) at tryModuleLoad (module.js:447:12) at Function.Module._load (module.js:439:3) at Module.runMain (module.js:605:10)
Logging Stack Trace (experimental)
Logger has built-in feature to capture stack trace for every log message. If enabled call stack will be available as trace
meta value. Note that internal logger function calls are excluded.
Warning: Capturing of stack traces has a significant impact on performance and should be used only for temporary debugging.
This feature is currently experimental.
Also, note that this feature does not affect possibility to log stack trace by passing an error object as an argument to a log method - eg ... catch(err){ logger.error("Operation failed:", err); }
will work always.
Following example:
; logger.enableTrace;logger.toConsole; logger.info"Hello!"; // To turn it offlogger.enableTracefalse;
will print to console:
info: hello >> at Logger.info (/path/to/app/node_modules/meta2-logger/dist/src/Logger.js:286:14) at Object.<anonymous> (/path/to/app/index.js:30:24) at Module._compile (module.js:571:32) at Object.Module._extensions..js (module.js:580:10) at Module.load (module.js:488:32) at tryModuleLoad (module.js:447:12) at Function.Module._load (module.js:439:3) at Module.runMain (module.js:605:10)
API Reference
;
Development
# Install dependencies npm install # Transpile TypeScript npm run build # Run linter npm run lint # Run tests npm test
License
This library is published under MIT license.
Copyright (c) 2017 - 2018 Jiri Hybek, jiri@hybek.cz