mooma
mooma

Reputation: 1

How do I set a different name to an individual log handler?

I have two log handlers in my code: a StreamHandler to write INFO level logs from the same module to stdout, and a FileHandler to write more verbose, DEBUG logs to a file. This is my code:

import sys
import logging

log = logging.getLogger('mymodule')
log.setLevel(logging.DEBUG)

logf = logging.FileHandler('file.log')
logf.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
log.addHandler(logf)

logs = logging.StreamHandler(sys.stdout)
logs.setLevel(logging.INFO)
logs.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
log.addHandler(logs)

However, I want the FileHandler to also write DEBUG info from other modules. I can achieve this if I remove the name from logging.getLogger(), but this will also affect my StreamHandler, which I only want to print output from my own module.

So is there a way to have either of the handlers use a different name?

Upvotes: 0

Views: 763

Answers (1)

durden2.0
durden2.0

Reputation: 9542

There's a name attribute available on the base Handler class. I took a look at the Python source and doesn't look like it's used internally so you could manually set each handler to a different name.

Upvotes: 2

Related Questions