When building a backend, I usually log messages inside the controllers like this:
router.get('/books', async () => {
const books = await booksService.getAll()
logger.info('All books returned successfully')
return books
})
But what if getAll method from booksService is used in another service method? Should I then log in the service methods too? For example:
class BookService {
getAll() {
const books = [] // all books
logger.info('All books returned successfully')
return books
}
}
For the endpoint /books, this will lead me to two logs with the same information called in different layers. But, it will be useful if another service method calls multiple service, then I will receive information about each service method being called, for example:
class ThirdApiLayerService {
syncBooks() {
const books = await booksService.getAll()
await this.createBooks(books)
logger.info('Books synced successfully')
return books
}
createBooks(books) {
const parsedBooks = this.parse(books)
await this.save(parsedBooks)
logger.info('Books parsed and saved successfully')
return parsedBooks
}
}
So then my question is: Should I log messages inside both controllers and service regardless of repeating messages, which will be only differentiated by the layer that called them? I know I can add context to the logger so the layer where the message is sent is logged too, my question is only about repeated messages being written.
Thanks in advance!
Normally you would use INFO logs for ingress/egress messages i.e. in your controller or for external service to service calls.
Other log messages such as in your BookService would be DEBUG or TRACE depending on the use case.
You should also log a correlation/request id in each log message otherwise the logs will be pretty useless in production.
**** Make you should also redact sensitive information. ****
Popular logging frameworks such as winston and pino can help you with this.
Alternatively you can use a nodejs framework such as NestJS which has logging built into it. See this post for further info