Reputation: 1409
I have two log handlers set up in my basic config. The FileHandler
logs to a file and StreamHandler
logs to stdout.
logging.basicConfig(
format="%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s] %(message)s",
level=logging.INFO,
handlers=[
logging.FileHandler("/my/log/file.log"),
logging.StreamHandler(sys.stdout)
]
)
Currently, the above code works fine, however, I want my StreamHandler
to output a different format, just the %(message)
.
Is there a way to specify this in my logging.basicConfig
?
Upvotes: 4
Views: 3490
Reputation: 78536
Predefine the StreamHandler
and set your desired custom format before passing it to basicConfig
:
handler_sh = logging.StreamHandler(sys.stdout)
handler_sh.setFormatter(logging.Formatter("%(message)s"))
You can now pass the created handler
with an already set formatter to basicConfig
:
logging.basicConfig(
format="%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s] %(message)s",
level=logging.INFO,
handlers=[
logging.FileHandler("/my/log/file.log"),
handler_sh
]
)
Only the FileHandler
takes the format
passed in basicConfig
:
Any handlers which don’t already have a formatter set will be assigned the default formatter created in this function.
Upvotes: 6