简体   繁体   中英

Python switch a logger off by default

In Python, I want to optionally log from a module - but have this logging off by default, enabled with a function call. (The output from this file will be very spammy - so best off by default)

I want my code to look something like this.

log = logging.getLogger("module")
log.switch_off()

---

import module
module.log.switch_on()

I can't seem to find an option to disable a logger.

Options considered:

  • Using filters: I think this is a bit confusing for the client
  • Setting a level higher than one I use to log: (eg logging.CRITICAL ). I don't like that we could inadvertently throw log lines into normal output if we use that level.
  • Use a flag and add ifs
  • Require the client to exclude our log events. See logging config

There are two pieces at play here. Python has logging.Logger objects and logging.Handler objects that work together to serve you logging information. Loggers handle the logic of collecting logging information, and deciding whether logs should be emitted to associated handlers. If the logging level of your log record is less severe than the level specified in the logger, it will not pass info to associated handlers.

Handlers have the same feature, and since handlers are the last line between log records and defined output, you would likely want to disable the interaction there. To accomplish this, and avoid having logs inadvertently logged elsewhere, you can add a new logging level to your application:

logging.addLevelName(logging.CRITICAL + 1, "DISABLELOGGING")

Note: This only maps the name to value for purposes of formatting, so you will need to add a member to the logging module as well:

logging.DISABLELOGGING = logging.CRITICAL + 1

Setting it to a value higher than CRITICAL ensures that no normal log event will pass and be emitted.

Then you just need to set your handler to the level you defined:

handler.setLevel(logging.DISABLELOGGING)

and now there should be no logs that pass the handler, and therefore no output shown.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM