r/learnpython • u/MezzoScettico • 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.
View all comments
1
u/Atmosck 2h ago
You should definitely use the logging module instead of print statements. The print function has no place in real code.
The log levels are based on the type of information they carry. If you want to have multiple levels of verbosity for your debug output, I would do what you're doing with an explicit verbosity level and checks, but use
logging.debuginstead ofprint. Or do the same thing withlogging.infoif they are normal user-facing rather than debug logs, but you still want them to have multiple verbosity levels.A slightly more sophisticated way to do that would to create your own wrapper function like
Then set the level when you call VerboseInfoLogger based on command line options or whatever you want to determine it, then pass the log function you created as an argument to things that use it. I do something conceptually similar to this for some simulations I work on where there is a command to trace a single run of the simulation, with varying levels of verbosity. That's a situation where you want multiple levels of what are conceptually INFO logs.
That's just one way to approach it. You can go a lot deeper with the logging module if you want, defining custom log levels or categories.