2

I have a question on how to share the Python logging device when we have other modules.

Let's say that I have main.py that imports file protocol.py and declares a logger variable.

import logging
from protocol import Protocol

log = logging.getLogger(__name__)
log.debug("Currently in main.py")

protocol_obj_1 = Protocol(log)
protocol_obj_2 = Protocol()

Within protocol.py, let's say I wish to log additional data by sharing the same log variable.

class Protocol:
    def __init__(self, log_var = None):
        self.log_var = log_var

    def logData(self):
        if self.log_var is not None:
            self.log_var.debug("Currently within class Protocol")
        else:
            print("Currently no logging")

Is this a Pythonic approach? Or are there better ways to share the logging device with other modules?

1
  • It is a common practice to create a new logger with logging.getLogger(__name__) in every module. Commented Jul 24, 2021 at 8:38

1 Answer 1

4

The most idiomatic Python way of creating a logger in a module is, as the documentation says:

A good convention to use when naming loggers is to use a module-level logger, in each module which uses logging, named as follows:

logger = logging.getLogger(__name__)

But there aren't rare cases where you want different modules to log into the same logger. For instance, when it's done in a Python (distribution) package (say, distributed on PyPI). Then, if the package is "flat" then you can use __package__ instead of __name__ in every module.

logger = logging.getLogger(__package__)

If you have import packages in your distribution package, then you may want to provide hardcoded names in every module.

logger = logging.getLogger('mypackage')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.