Registration using static methods

In a class with several static functions, I usually write the following messages:

class ClassA: def __init__(self): self._logger = logging.getLogger(self.__class__.__name__) def do_something(self): self._logger.info("Doing something") def do_something_else(self): self._logger.info("Doing something else.") 

In a class with static methods, I did this:

 class ClassB: _logger = logging.getLogger("ClassB") @staticmethod def do_something(): ClassB._logger.info("Doing something") @staticmethod def do_something_else(): ClassB._logger.info("Doing something else") 

You can do this, but it looks lame:

 class ClassB: @staticmethod def do_something(): logger = logging.getLogger("ClassB") logger.info("Doing something") @staticmethod def do_something_else(): logger = logging.getLogger("ClassB") logger.info("Doing something else") 

Is there a better template for registering from static methods?

+6
source share
3 answers

Instead, you can turn them into class methods.

 class ClassB(object): _logger = logging.getLogger("ClassB") @classmethod def do_something(cls): cls._logger.info("Doing something") 

But note that when you exit ClassB and call do_something , it will get a different registrar, since cls is the derived class, not ClassB .

+4
source

This pretty much exhausts your possibilities. In the end, only three areas are available for a static method: the method area, the class scope, and the module area. And if you want the log name to match the class name, you will need at least one registrar for each class, so it makes no sense to store them in the module area if you can also save them in the class area (as a second example).

Personally, I usually use logger for each module. But if I were to deal with separate class registrars, I would probably use your template # 2, which has the _logger variable in each class. It just seems to me the cleanest.

+3
source

late to answer, but would like to add another point.

If you have more complicated log initialization (paths to initialization files for logging in, etc.), you can do this by creating logger_init outside the class.

 def init_logger(): logger = logging.getLogger('general_logger') # do other logger setup like # setup logger handlers, # set formatters, # set logging levels, etc return logger 

then run your logger from a static class

  class MyClass(object): _logger = init_logger() @classmethod def do_something(cls): cls._logger.info("doing something") 

happy magazine!

0
source

Source: https://habr.com/ru/post/903418/


All Articles