Python: 将日志记录模块与 configparser 或 argparser 一起使用

Python: Use logging module with configparser or argparser

使用 Python 的日志记录模块记录您的脚本所做的一切 的最佳方式是什么,同时还利用 configparser 文件加载配置文件包含您希望保存日志的位置。

这是我的示例代码:

import sys
import os
import logging
import configparser
import argparse

### Create Functions ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def get_logger(LOG_DIR, FULL_LOG_PATH):
    """Create logger."""
    # Create LOG_DIR if it doesn't exist already

    try:
        os.makedirs(f"{LOG_DIR}")

    except:
        pass

    try:
        # Create logger and set level
        logger = logging.getLogger(__name__)
        logger.setLevel(level=logging.INFO)

        # Configure file handler
        formatter = logging.Formatter(
            fmt = '%(asctime)s - %(name)s - %(levelname)s - %(message)s',
            datefmt = "%Y-%m-%d_%H-%M-%S")
        fh = logging.FileHandler(f"{FULL_LOG_PATH}")
        fh.setFormatter(formatter)
        fh.setLevel(level=logging.INFO)

        # Add handlers to logger
        logger.addHandler(fh)
        return  logger

    except:
        sys.exit(-1)

def parse_cl_args():
    """Set CLI Arguments."""

    try:
        # Initiate the parser
        parser = argparse.ArgumentParser(
            description="Script to scrape Twitter users account information."
        )
        # Add optional arguments
        parser.add_argument(
            "-c", "--config-file",
            metavar='Config-file',
            help="Full path to the global config file containing paths/file names for script.",
            required=True
        )

        # Read parsed arguments from the command line into "args"
        args = parser.parse_args()

        # Assign the file name to a variable and return it
        config_file_path = args.config_file
        return config_file_path

    except:

        sys.exit(-1)

def parse_config_file(config_file_path):

    try:
        config = configparser.ConfigParser()
        config.read(config_file_path)
        return config
    except:
        sys.exit(-1)

# A bunch of other functions

if __name__ == '__main__':
    # parse command line args
    config_file_path = parse_cl_args()

    # parse config file
    config = parse_config_file(config_file_path)

    # Set logging path
    LOG_DIR = os.path.join(config["PATHS"]["LOG_DIR"])

    # Set log file name
    FULL_LOG_PATH = os.path.join(config["PATHS"]["LOG_DIR"], "mylog.log")

    # Get logger
    logger = get_logger(
        LOG_DIR = LOG_DIR, 
        FULL_LOG_PATH= FULL_LOG_PATH
        )

get_logger() 行以上的所有内容都无法记录在记录器中,但如果不首先加载我的命令行参数 (config_file.ini) 然后解析该文件,则无法创建记录器(其中包含我希望保存日志的位置)。有更好的方法吗?

如果您想在知道日志文件的位置之前记录日志,但又想在文件中记录这些日志,您可以使用 MemoryHandler,这是一种特殊类型的 BufferingHandler。所以你的程序流程是:

  1. 设置记录器
  2. 将 MemoryHandler 添加到此记录器
  3. 在使用记录器时读取配置文件之类的事情,您必须创建日志
  4. 使用配置中的值设置 FileHandler
  5. 在 MemoryHandler 上调用 setTarget(file_handler),将其传递给 FileHandler
  6. 在 MemoryHandler 上调用 flush() -> 第 3 步的日志被写入文件
  7. 您现在可以选择移除 MemoryHandler