[BUG] When context is supplied to Logger, message gets stringified
See original GitHub issueWhat is the current behavior?
Recommended way to use nestjs logger is to instantiate the singleton class Logger
from @nestjs/common
and supply context to it (https://stackoverflow.com/a/52907695/4601673), like so:
import { Logger } from '@nestjs/common';
class MyService implements OnModuleInit {
logger = new Logger(MyService.name);
onModuleInit() {
this.logger.log({ msg: 'test' });
}
}
Using this pattern with nestjs-pino works quite well, but there is a catch. When context is supplied, message is sent as a second argument to pino here: https://github.com/iamolegga/nestjs-pino/blob/master/src/Logger.ts#L35. This results in message being treated as the format string here: https://github.com/pinojs/pino/blob/master/lib/tools.js#L52. So if message is an object, it gets stringified into the “msg” field of the logged json object, like so:
{"level":30,"time":1598681218911,"pid":92,"hostname":"sse-sandbox-hxfsk","context":"AppService","msg":"{\"msg\":\"test\"} "}
If context is not supplied, the message is supplied as the first argument and pino correctly logs the message as an object.
Please provide the steps to reproduce.
Here is the minimal codesandbox based on nestjs-typescript-starter with pino-logger applied and used from AppService. https://codesandbox.io/s/nestjs-pino-logger-context-forked-hxfsk?file=/src/app.service.ts
There are some issues with displaying logging output though 😦
What is the expected behavior?
I expect message to be logged the same way it is logged when context is not supplied (i.e. merged into root object), like so:
{"level":30,"time":1598681218911,"pid":92,"hostname":"sse-sandbox-hxfsk","context":"AppService","msg":"test"}
Please mention other relevant information such as Node.js version and Operating System.
I do not think this is relevant, but I am using node v12.18.2 and OS Windows 10 Pro 2004.
P.S.
If this is not an intended behavior, I can make a PR to fix it by merging message into context object in all of the methods of Logger
class. I would also like to add this usage example to the documentation.
Issue Analytics
- State:
- Created 3 years ago
- Comments:6 (4 by maintainers)
Top GitHub Comments
Hello, thanks for such detailed explanation.
yes, please, feel free to open pr, I’ll try to review it as soon as possible, but please add test for both cases: when
msg
is object and string, or you can ask for my help with tests, if you’ll need it 👍I think that’s unnecessary. I think that the best way to deal with migrating to original class is create codemod, but that could be challenging.
feel free to open it as you will be ready 🙂