Home > Back-end >  Why do we need to specify logger only on Controller level
Why do we need to specify logger only on Controller level

Time:10-19

I noticed that it's enough to specify a logger on controller level.

import ...

val logger = KotlinLogging.logger { }

@RestController

A subsequent service is able to access this logger without specifying a logger for itself.

In other words - if a service complains about not being able to call logger.info {"..."} then it is enough to add val logger = KotlinLogging.logger { } to a calling controller of that service.

Why is that?

CodePudding user response:

When you create variables like that you are basically creating a top-level variable that might be accessible from anywhere in your code. That is why if you add it to the Controller, the Service will be able to use it.

However, this does not mean you should do that. The recommended way to create a KotlinLogger is using companion objects as follows:

import ...

@RestController
class WhateverController {
    companion object {
        private val logger = KotlinLogging.logger {}
    }
}

This means that you will have a logger for each class, as you should.

  • Related