简体   繁体   中英

JSON-log-formatter with logging.config.dictConfig

Recently discovered JSON-log-formatter and would like to use it to write my log output in JSON. Configuring it in the script is relatively straight forward, but most of my existing code utilizes logging.config.dictConfig to load the logging config from a YAML file so I can easily configure logging without modifying the script itself, and I can't figure out how to add a python module as a formatter within the config.

Current YAML

version: 1
disable_existing_loggers: False
formatters:
  simple:
    format: "%(asctime)s | %(name)s | %(funcName)s() | %(levelname)s | %(message)s"
handlers:
  console:
    class: logging.StreamHandler
    level: DEBUG
    formatter: simple
    stream: ext://sys.stdout

  file_handler:
    class: logging.handlers.TimedRotatingFileHandler
    level: INFO
    formatter: simple
    filename: LogFile.log
    encoding: utf8
    backupCount: 30
    encoding: utf8
    when: 'midnight'
    interval: 1
    delay: True

loggers:
  my_module:
    level: ERROR
    handlers: [console]
    propagate: no

root:
  level: INFO
  handlers: [console, file_handler]

The above config works, but I can't figure out how to change the formatter to the JSON using that module. Something like this(I know this doesn't work):

formatters:
  simple:
    format: json_log_formatter.VerboseJSONFormatter()

Python loading up that YAML

import logging.config
import json_log_formatter
import yaml

with open('./logging.yaml', 'r') as stream:
    logConfig = yaml.load(stream, Loader=yaml.FullLoader)
logging.config.dictConfig(logConfig)

I get that python is just loading the YAML into a dictionary object and then configuring logging based on that dictionary, but how do I set the formatter so that it correctly references that JSON logging module and uses it?

nevermind, of course I figured it out after posting this.

formatters:
  myformat:
    (): json_log_formatter.VerboseJSONFormatter

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM