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!