r/learnpython • • 50m 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.

3 Upvotes

8 comments sorted by

View all comments

•

u/danielroseman 42m 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/MezzoScettico 29m 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.

•

u/cointoss3 13m 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