r/learnpython • • 16m ago

Can logging replace my verbosity controls?

An old habit from C days is to add print statements for debug and assign them different verbosity levels. I've been doing that in Python as well.

if verbosity > 2:
    print("This level generates a lot of output, so use it sparingly")

I've been told that the logging facility is the Python way to do this, so I'm finally investigating it. What I'm seeing is that the levels are DEBUG, INFO, WARNING, ERROR which doesn't really fit what I want to happen. Everything I want to put under verbosity control is technically DEBUG or INFO.

So my question is: are there sublevels on the DEBUG or INFO logging? Or is there another approach for this sort of thing?

EDIT: Still reading. I think the answer might be a hierarchy of loggers and filters? Trying to figure out how that works now.

2 Upvotes

2 comments sorted by

•

u/danielroseman 8m ago

Levels are just numbers; DEBUG is 10 and CRITICAL is 50. If you need more granularity, then use more numbers.

Although I don't understand your point; if you want to control whether to log more or less verbosely, then logging at DEBUG seems fine.

•

u/auntanniesalligator 1m ago

Not sure I understand what you’re asking. It sounds like your verbosity scale maps to the values associated with INFO, DEBUG, etc. which are compared to the logging commands via inequalities to determine if they apply.

Perhaps you’re unaware that the cumulative effect is handled by same named commands? So instead of querying the logging level directly as the conditional of an if statement, you put in a line like:

logging.warn(“This message shows up for logging levels DEBUG, INFO, and WARN, but not for ERROR or CRITICAL.”)

logging.debug(“This message only shows up if logging level is set to DEBUG.”)

It’s also handy that you can setup multiple loggers at different levels, so, eg, you might set screen output level to WARN and save a log file with the level set to INFO.