In Moleculer project every main module has a custom logger instance. They inherit it from the broker logger instance which you can set in the broker options.
It supports also external loggers like Pino, Bunyan, Winston, …etc.
Built-in logger
The Moleculer has a built-in console logger. You can enable it with logger: console
or logger: true
options.
Built-in console logger:
let { ServiceBroker } = require("moleculer"); |
Console messages:
[2017-08-18T12:37:25.714Z] INFO dev-pc/POSTS: Log message via Service logger |
Custom log levels
You can change the log level with logLevel
option in broker options. You can use it with built-in console logger only.
let broker = new ServiceBroker({ |
Available log levels:
fatal
,error
,warn
,info
,debug
,trace
Custom log formats
You can set a custom log formatter function for the built-in logger.
const broker = new ServiceBroker({ |
Output:
WARN dev-pc: Warn message |
Custom object & array printing formatter
You can set a custom formatter function to print object & arrays. The default function prints the objects & arrays to a single line in order to be easy to process with an external log tool. But when you are developing, it would be useful to print objects to a human-readable multi-line format. For this purpose, overwrite the logObjectPrinter
function in the broker options.
Output with default function
[2017-08-18T12:37:25.720Z] INFO dev-pc/BROKER: { name: 'node', lts: 'Carbon', sourceUrl: 'https://nodejs.org/download/release/v8.10.0/node-v8.10.0.tar.gz', headersUrl: 'https://nodejs.org/download/release/v8.10.0/node-v8.10.0-headers.tar.gz' } |
**Switch to multi-line printing & increment depth
const util = require("util"); |
Output:
[2017-08-18T12:37:25.720Z] INFO dev-pc/BROKER: { name: 'node', |
External loggers
You can use external loggers with Moleculer. In this case you can set a creator function to logger
. The ServiceBroker will call it when a new module inherits a new logger instance.
Pino
const pino = require("pino")({ level: "info" }); |
Bunyan
const bunyan = require("bunyan"); |
Winston
const broker = new ServiceBroker({ |
Winston context
const WinstonContext = require("winston-context"); |
Some external loggers have not
trace
&fatal
log methods (e.g.: winston). In this case you have to extend your logger.
const WinstonContext = require("winston-context"); |
The bindings
object contains the following properties:
ns
- namespacenodeID
- nodeIDmod
- type of core module:broker
,cacher
,transit
,transporter
svc
- service namever
- service version
Please noteAvoid using these bindings property names when you log an
Object
.
For example: thebroker.logger.error({ mod: "peanut" })
overrides the originalmod
value!