简体   繁体   中英

How do I configure JsonFormatter in logging dictConfig?

I'd like to use logging.config.dictConfig with a json config file. But I want to use a formatter from another class: pythonjsonlogger.jsonlogger.JsonFormatter

What's wrong with this code/json:

$ cat test.json
{
    "version": 1,
    "disable_existing_loggers": "true",
    "formatters": {
        "json": {
          "class": "pythonjsonlogger.jsonlogger.JsonFormatter"
          # also tried "jsonlogger.JsonFormatter" (comment not in real file)
        }
    },
    "handlers": {
        "console": {
            "class": "logging.StreamHandler",
            "level": "DEBUG",
            "formatter": "json",
            "stream": "ext://sys.stdout"
         }
    },
    "loggers": { },
    "root": {
        "handlers": ["console"],
        "level": "DEBUG"
    }
}

code:

import sys
sys.path.append('/usr/local/lib/python2.7/site-packages')
import json
import logging
import logging.config
from pythonjsonlogger import jsonlogger

fp = open('/test.json')
logging.config.dictConfig(json.load(fp))
fp.close()
logging.info('test log line')

output:

test log line

Expected something like { "message": "test log line" }

Ok, pretty funny, but works:

Json:

{
    "version": 1,
    "disable_existing_loggers": true,
    "formatters": {
        "json": {
            "()": "pythonjsonlogger.jsonlogger.JsonFormatter"
        }
    },
    "handlers": {
        "json": {
            "class": "logging.StreamHandler",
            "formatter": "json"
        }
    },
    "loggers": {
        "": {
            "handlers": ["json"],
            "level": 20
        }
    }
}

Code:

import logging_util as safe_logging

import logging.config
import json

fp = open("logger_config.json")
config = json.load(fp)
fp.close()

logging.config.dictConfig(config)

safe_logging.via_logger = logging.getLogger("JsonLogger")
safe_logging.info("event")

Formatter can also have a format, not sure how, but it works:

"json": {
    "()": "pythonjsonlogger.jsonlogger.JsonFormatter",
    "format": "%(asctime)s %(levelname)s %(filename)s %(lineno)s %(message)s"
}

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