1

I have a python module of the following structure

|- src
  |- a
    |- aa
      |- x.py
      |- y.py
    |- ab
      |- xx.py
  |- b
    |- ba
      |- xxx.py

In the .py files, I have loggings like

logging.INFO("A")
logging.DEBUG("B")

I'm thinking to add a global control of the loggings for the whole module. I would like to set up a global logging level, say .setLevel(logging.INFO). Where should I do this? I have tried to put an __init__.py file in the src folder setting the logging level, but it seems to have no effect when I import functions from the .py files.

I'm wondering

  • what is a good way to do this? The level should work when someone uses for example from a.aa.x import A.
  • When I use logger = logging.getLogger() in each .py file, are the logger's all the same?
  • What's the benefit of using different loggers (say logger = logging.getLogger(".a") and logger = logging.getLogger(".b") in different .py files)?

1 Answer 1

1

You can use logging.log(level, msg, *args, **kwargs) to replace logging.INFO and logging.DEBUG() and define a variable for level globally and change that according to your need.

For me, I made a function for my own project

def log_message(message, level="INFO"):
    logging_levels = {
        "CRITICAL": 50,
        "ERROR": 40,
        "WARNING": 30,
        "INFO": 20,
        "DEBUG": 10
    }
    level = level.upper()
    level = logging_levels[level] if level in logging_levels else 20
    print(message)
    logger.log(level, message)

This helps to both print and log the message I want, while I can easily intercept all the logs in this function.

When I use logger = logging.getLogger() in each .py file, are the logger's all the same?

Yes

What's the benefit of using different loggers?

I don't think you should, but I supposed that can help you to better categorize the logs?

Reference: Logging

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks this is helpful! I'm wondering where can I control the default logging level? For example some logs are DEBUG and I don't want them to be logged by default when I do from a.aa.x import A. Should I declare a default logging level in each of the .py files?
Or maybe that's not possible, it depends on the new session where I have from a.aa.x import A. If I don't use logging.setLevel() there, the default level will always be INFO.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.