簡體   English   中英

Python記錄:dictConfig

[英]Python Logging: dictConfig

我正在嘗試使用配置文件來配置Python日志記錄,但也在加載dict配置后添加處理程序。 所以我的配置文件就像

version: 1
formatters:
  default_formatter:
    format: '%(asctime)s : %(levelname)s : %(message)s'
    datefmt: '%d-%b-%Y %H:%M:%S'
  plain_formatter:
    format: '%(message)s'
handlers:  
  console_default_handler:
    class: logging.StreamHandler
    level: INFO
    formatter: default_formatter
    stream: ext://sys.stdout  
root:
  level: INFO
  handlers: [console_default_handler]

然后在代碼中 - 我做

log_config_dict=yaml.load(open(log_config_file, 'r'))
logging.config.dictConfig(log_config_dict)

我希望以這種方式添加記錄器 -

fhandler1=logging.FileHandler(log_file_name,mode="w")
fhandler1.setFormatter(log_config_dict['formatters']['plain_formatter'])
fhandler1.setLevel(logging.DEBUG)

這不起作用。 有沒有什么方法可以捕獲dictConfig中定義的提取值,以便在我的手動日志配置中使用它們?

謝謝

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import logging
import logging.handlers
from logging.config import dictConfig

logger = logging.getLogger(__name__)

DEFAULT_LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
}
def configure_logging(logfile_path):
    """
    Initialize logging defaults for Project.

    :param logfile_path: logfile used to the logfile
    :type logfile_path: string

    This function does:

    - Assign INFO and DEBUG level to logger file handler and console handler

    """
    dictConfig(DEFAULT_LOGGING)

    default_formatter = logging.Formatter(
        "[%(asctime)s] [%(levelname)s] [%(name)s] [%(funcName)s():%(lineno)s] [PID:%(process)d TID:%(thread)d] %(message)s",
        "%d/%m/%Y %H:%M:%S")

    file_handler = logging.handlers.RotatingFileHandler(logfile_path, maxBytes=10485760,backupCount=300, encoding='utf-8')
    file_handler.setLevel(logging.INFO)

    console_handler = logging.StreamHandler()
    console_handler.setLevel(logging.DEBUG)

    file_handler.setFormatter(default_formatter)
    console_handler.setFormatter(default_formatter)

    logging.root.setLevel(logging.DEBUG)
    logging.root.addHandler(file_handler)
    logging.root.addHandler(console_handler)



[31/10/2015 22:00:33] [DEBUG] [yourmodulename] [yourfunction_name():9] [PID:61314 TID:140735248744448] this is logger infomation from hello module

我認為配置日志功能更方便。

哦,我明白了。 我需要做的是

formatter =logging.Formatter(log_config_dict['formatters']['plain_formatter']['format'])             
fhandler1.setFormatter(formatter)

所以,我需要創建一個Formatter對象。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM