Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logging from static methods

Tags:

python

logging

In a class with few no static functions, I typically do logging like this:

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've been doing 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 could do this but it seems 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 pattern for logging from static methods?

like image 577
Matthew Lund Avatar asked Dec 08 '11 22:12

Matthew Lund


People also ask

Can logger be static?

Loggers should be declared to be static and final. It is good programming practice to share a single logger object between all of the instances of a particular class and to use the same logger for the duration of the program.

What is Java logging system?

A Java logging framework is a computer data logging package for the Java platform. This article covers general purpose logging frameworks. Logging refers to the recording of activity by an application and is a common issue for development teams.


2 Answers

You could turn them into class methods instead.

class ClassB(object):
    _logger = logging.getLogger("ClassB")

    @classmethod
    def do_something(cls):
         cls._logger.info("Doing something")

But note that when you derive from ClassB and call do_something, it will get a different logger since cls denotes the derived class rather than ClassB.

like image 106
Fred Foo Avatar answered Nov 15 '22 15:11

Fred Foo


That pretty much does exhaust your options. After all, there are only three scopes accessible to a static method: the method scope, the class scope, and the module scope. And if you want to have the logger name match the class name, you will need at minimum one logger per class, so there's no point in storing them at the module scope when you might as well store them at the class scope (as your second example does).

Personally, I usually use a logger per module. But if I were doing individual class loggers, I would probably use your pattern #2, having a _logger variable in each class. It just seems the cleanest to me.

like image 44
David Z Avatar answered Nov 15 '22 13:11

David Z