r/learnpython • u/MezzoScettico • 1d 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
u/auntanniesalligator 1d 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.
2
u/MezzoScettico 1d ago
My desire is that INFO subdivides into INFO1, INFO2, INFO3, etc and that INFO, DEBUG, WARN was not enough granularity.
logging.warn(“This message shows up for logging levels DEBUG, INFO, and WARN, but not for ERROR or CRITICAL.”)
OK, but what if I don't want all the INFO messages? Sometimes I want only the higher level, sometimes I want really verbose detail. I typically have at least 0-2, and often more.
I know, I know. RTFM. I'm reading, still trying to absorb the model. Another answer says that there are actually level numbers and they are a lot finer granularity. Maybe that's the answer.
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.
The multiple-logger thing seems like a powerful mechanism and I think that's what I really want to understand. It's overkill for what I'm trying to do today but I'm trying to practice with some baby code to figure it out.
4
u/cointoss3 1d ago
I feel like this is an XY problem. Why do you feel like you need 3 different info log levels?
2
u/Outside_Complaint755 1d ago
Instead of sending all messages to the terminal, send the logging output to a file, and then you can use Ctrl+F to search the file for whatever specific message you are looking for. You can then include keys to search for (I1, I2, etc) in the log messages instead of trying to insert a dozen custom logging levels.
1
u/Boothiepro 1d ago
Indeed you can. You can add more levels between 10-debug and 20-info, or you can assign them to different handlers. handlers are where the logs go, e.g. filehandler, just the default stdout console handler etc. You can assign multiple console handlers, pipe the logs into each of them based on your criteria, and turn them on/off based on your needs. handlers are fun, i wrote one to flash my rgb gaming mouse when an error occurs or send me a Discord message. You can format these messages to show the offending error line, function called, file ran, color these fields accordingly etc. With this info open a link to the github repo's specific file and code line to check what errored when i'm not on my computer.
1
u/pingveno 1d ago
I've always found that multiple loggers handle most needs. It's better to not make it more complicated before it needs to be. There's a lot of power given to you with loggers, handlers, formatters, and so on.
Once you're comfortable with logging, it's worth looking into structured logging. It uses key-value pairs to structure your logs instead of flat strings. It's much nicer to use a JSON query tool rather than attempt to construct a regex when sifting through a gigabyte of logs. But again, leave that to later.
1
u/dariusbiggs 23h ago
or you change your approach and instead of info1 info2 info3, you just use the existing logging levels. info1 == warn info2 == info info3 == debug
problem solved.
Also the logging levels are numbers, INFO is just a predefined constant, you can add more constant mappings to use internally and pass those around.
You then have a different problem, you should be logging all the information needed to dehug the problem without changing the program, its configuration, or restarting it.
1
u/Atmosck 1d 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.debug instead of print. Or do the same thing with logging.info if 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
import logging
class VerboseInfoLogger:
def __init__(self, verbosity: int = 1):
self.verbosity = verbosity
self.logger = logging.getLogger(__name__)
def __call__(self, msg: str, verbosity: int = 1):
if verbosity <= self.verbosity:
self.logger.info(msg)
log = VerboseInfoLogger(2)
log("This level generates a lot of output, so use it sparingly", 2)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.
1
u/Explorer651 1d ago
Custom levels are possible. The logging HOWTO says Logger.log takes the level as an explicit argument, which is how you log at custom levels, and it gives the numeric values so you can pick your own relative to the built-in ones. It also says the existing levels should usually be enough, so keep custom ones to a minimum.
1
u/pingveno 1d ago
I usually wouldn't go there. The built-in log levels are well supported by log tooling like log aggregators.
1
u/Lumethys 1d ago
The logging level are defined by RFC 5424. Not only for Python but for all programming language, yes that does include C
Humanity has yet to find a problem that require your level of fine-grained verbosity.
If you want to filter specific log lines from your logs, you use a Observability tool or platform, like VictoriaLogs, Loki, ElasticSearch,... they have dedicated log query language to filter your logs to any fine-grained level
Personally I prefer VictoriaLog, extremely performance, just a few MBs of RAM, just 1 docker compose line. But you can also look at OpenObserve if the want a 3-in-1 tool in Parquet format and SQL query
11
u/danielroseman 1d 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.