r/learnpython • • 2h 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.

4 Upvotes

14 comments sorted by

View all comments

Show parent comment

2

u/MezzoScettico 2h ago

I've only just begun reading the documentation so I'm probably missing a lot.

My confusion was that I was getting the impression that I can log a message as INFO for instance. And I can control whether INFO messages are displayed. But if they are, then all the INFO messages are displayed. It seemed to me (on admittedly a very quick read) that I couldn't say "show me INFO messages level 2 or below" and then switch it to "show me INFO messages level 3 or below", "show me INFO messages level 4 or below" by just changing one parameter up top.

But with what you're saying about the levels, the numbering actually is finer than that. I can log level 10 and above, or level 11 and above, or level 12 and above, etc. I hadn't run into that yet in my reading.

3

u/cointoss3 1h ago

Each level is a value and when you turn on that level, you’ll get everything above it. DEBUG gets you debug, info, warn, error, and critical. ERROR gets you error and critical. You can also set flags that can filter records. You can also have multiple loggers and turn them on and off. Each file (module) can have its own scoped logger that you turn on or off. The logging module has a lot it can do and lots of flexibility but it’s a little confusing at first.

This is a video I felt like I learned from, even though I thought I knew how to use the logging package: https://www.youtube.com/watch?v=9L77QExPmI0

2

u/danielroseman 1h ago

Yes you can, although I really would question the need. Do you absolutely need to distinguish this many levels of INFO? Why?