2

When we add a new additional handler:

import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s: %(name)s: %(levelname)s: %(message)s')
logging.getLogger().addHandler(logging.FileHandler("debug.log"))
logging.info('an info')

by default, it doesn't keep the same formatter.

So here we would need to have much longer code with:

logging_format = "%(asctime)s: %(name)s: %(levelname)s: %(message)s"
logging.basicConfig(level=logging.INFO, format=logging_format)

# and later, when we want to add a new file handler:

f = logging.Formatter(logging_format)
h = logging.FileHandler("debug.log")
h.setFormatter(f)
logging.getLogger().addHandler(h)

Is there a way to keep the same formatter by default, when adding a new handler?

See also How to set the same logging format for all handlers?.

Basj
  • 41,386
  • 99
  • 383
  • 673

1 Answers1

0

If you use logging.config.dictConfig() to configure logging, you can do this relatively straightforwardly. The documentation is too long to reproduce here, but I've linked to the official documentation.

A configuration in YAML format might be:

version: 1
disable_existing_loggers: false
formatters:
  default:
    format: '%(asctime)s: %(name)s: %(levelname)s: %(message)s'
handlers:
  console:
    class: logging.StreamHandler
    formatter: default
  file:
    class: logging.FileHandler
    formatter: default
    filename: debug.log
root:
  level: INFO
  handlers: [console, file]
Vinay Sajip
  • 95,872
  • 14
  • 179
  • 191