Python Logging config:将跟踪输出到文件,将日志消息输出到控制台

时间:2017-07-31 16:18:12

标签: python logging

给出以下日志记录声明:

import logging

...
def ...
    try:
        ...
    except MyException:
        ...
        logger.error("Parsing Error: %s"%(sys.exc_info()[0]),exc_info=True)

以下json配置:

"handlers":{
    "error_file_handler": {
        "class": "logging.handlers.RotatingFileHandler",
        "level": "ERROR",
        "formatter": "simple",
        "filename": "../log/errors.log",
        "maxBytes": 10485760,
        "backupCount": 20,
        "encoding": "utf8"
    },
}

"loggers": {
    "my_module": {
        "level": "ERROR",
        "handlers": ["console"],
        "propagate": "no"
    }
},

如何修改此配置,使跟踪输出不输出到控制台,而是输出到错误日志?

并且,同时:日志消息字符串仍然输出到控制台?

1 个答案:

答案 0 :(得分:0)

试试这个:

"handlers": {
    "error_file_handler": {
        "class": "logging.handlers.RotatingFileHandler",
        "level": "ERROR",
        "formatter": "simple",
        "filename": "../log/errors.log",
        "maxBytes": 10485760,
        "backupCount": 20,
        "encoding": "utf8"
    },
    'console': {
        'level': 'INFO',
        'formatter': 'standard',
        'class': 'logging.StreamHandler'
    }
}

"loggers": {
    "my_module": {
        "level": "ERROR",
        "handlers": ["console", "error_file_handler"],
        "propagate": "no"
    }
}

变化:

  1. "handlers": ["console", "error_file_handler"]:将日志写入文件和控制台
  2. "handlers": ["error_file_handler"]:将日志写入文件