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

13 comments sorted by

6

u/danielroseman 2h 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.

2

u/MezzoScettico 1h 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.

2

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?

1

u/auntanniesalligator 2h 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 1h 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.

2

u/cointoss3 1h ago

I feel like this is an XY problem. Why do you feel like you need 3 different info log levels?

1

u/Boothiepro 1h 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.

•

u/pingveno 50m 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/Atmosck 1h 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 1h 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 1h ago

I usually wouldn't go there. The built-in log levels are well supported by log tooling like log aggregators.

•

u/Lumethys 56m 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