user3029790
user3029790

Reputation: 321

How to set logging environment for a module in python

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

Upvotes: 1

Views: 851

Answers (1)

kennysliding
kennysliding

Reputation: 2985

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

Upvotes: 1

Related Questions