python - 如何在记录 dictConfig 时配置 JsonFormatter?

标签 python json logging

我想将 logging.config.dictConfig 与 json 配置文件一起使用。但我想使用另一个类的格式化程序:pythonjsonlogger.jsonlogger.JsonFormatter

这段代码/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"
    }
}

代码:

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')

输出:

test log line

预期类似 { "message": "test log line"}

最佳答案

好吧,很有趣,但有效:

JSON:

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

代码:

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 也可以有一个格式,不知道如何,但它有效:

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

关于python - 如何在记录 dictConfig 时配置 JsonFormatter?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50100882/

相关文章:

javascript - 考虑到 mongodb 中的推特数据,如何使用 node.js 将 json 文件转换为 excel

c++ - 完全控制日志记录的 C/C++ 日志记录

python - 查找最近邻更改算法

python - 在 python 中使用格式化打印的双引号与单引号

python - 从字符串中提取某些整数,然后对其进行归一化

java - 将 Json 从 Java 应用程序传递到 PHP (Laravel)

python - 在python 3.1中将google搜索结果转换为json

java - 动态创建 Logback Loggers 和 Appenders

logging - 使用 MySQL 执行存储评论

python - 列数大于阈值