rbehzadan
rbehzadan

Reputation: 87

How to configure Python Logging with YAML to log in UTC?

I know I can set logging.Formatter().converter = time.gmtime. But how can I do this in YAML and logging.config.dictConfig?

Here is what I did:

version: 1
formatters:
  simple:
    format: '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
    converter: ext://time.gmtime
handlers:
  console:
    class: logging.StreamHandler
    level: DEBUG
    formatter: simple
    stream: ext://sys.stdout
loggers:
  my_app:
    level: DEBUG
    handlers: [console]

But it still logs in local time.

Upvotes: 4

Views: 1678

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121834

The logging.config module only supports the keys format, datefmt and class; your converter key is entirely ignored.

The class key does let you specify a custom formatter, so your best option is to subclass logging.Formatter() and have that subclass set the converter:

from logging import Formatter
import time

class GMTFormatter(Formatter):
    converter = time.gmtime

then refer to that class in your YAML:

formatters:
  simple:
    format: '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
    class: ext://your.module.GMTFormatter

Upvotes: 8

Related Questions