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?
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.
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.
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With