epa095
epa095

Reputation: 238

Temporary disable logging completely in Python

Temporary disable logging completely

I am trying to write a new log-handler in Python which will post a json-representation of the log-message to a HTTP endpoint, and I am using the request library for the posting. The problem is that both request and urllib3 (used by request) logs, and their loggers has propagate=True, meaning that the logs they log will be propagated to any parent loggers. If the user of my log-handler creates a logger with no name given, it becomes the root logger, so it will receive this messages, causing an infinite loop of logging. I am a bit lost on how to fix this, and I have two suggestions which both seem brittle.

1) Get the "reguest" and "urllib3" loggers, set their propagate values to false, post the log message before setting the propagate values back to their old values.

2) Check if the incoming record has a name which contains ".request" or ".urllib3", and if it does then ignore the record.

Both of these will break badly if the request library either replaces urllib3 with something else or changes the name of its logger. It also seems likely that method 1 will be problematic in a multi-threaded or multi-process case.

What I would want is some way of disabling all logging for the current thread from some point and then enable it again after we have posted the message, but I don't know any way to do this.

Any suggestions?

Upvotes: 1

Views: 271

Answers (1)

Violet Red
Violet Red

Reputation: 221

Importing os.devnull and setting it as a default file handler for parent logger maybe?

I usually flush all logs to devnull except that were explicitly set up (dunno if it's a good or bad practice).

Upvotes: 1

Related Questions