python爬虫(四) ---- yaml文件配置简单日志

部署运行你感兴趣的模型镜像

python爬虫之yaml文件配置简单日志

一、环境准备

# 第三方日志包, 可以按日期和文件大小轮转日志
pip install concurrent-log-handler 
# 加载yaml文件需要的依赖包
pip install pyyaml

二、配置示例

  • config/logging_config.py
    import logging
    import logging.config
    import os
    import yaml
    
    _logger_initialized = False
    
    
    def setup_logger(config_path="../config/logging_config.yaml"):
    	""" 获取打包后资源文件的绝对路径 """
        if getattr(sys, 'frozen', False):
            # 如果是打包后的exe运行
            base_path = sys._MEIPASS
        else:
            # 如果是普通Python脚本运行
            base_path = os.path.abspath('..')
    
        # 使用相对路径
        config_path = os.path.join(base_path, "config/logging_config.yaml")
    
        global _logger_initialized
        if _logger_initialized:
            return
    
        print(f"正在尝试加载日志配置文件:{os.path.abspath(config_path)}")  # 调试输出路径
    
        if not os.path.exists(config_path):
            raise FileNotFoundError(f"日志配置文件未找到: {config_path}")
    
        with open(config_path, "r", encoding="utf-8") as f:
            config = yaml.safe_load(f)
    
        # 提取所有 file 类型 handler 的日志文件路径, 如果目录不存在, 自动创建
        handlers = config.get('handlers', {})
        for handler in handlers.values():
            if 'filename' in handler:
                log_file = handler['filename']
                log_dir = os.path.dirname(log_file)
                if log_dir and not os.path.exists(log_dir):
                    os.makedirs(log_dir, exist_ok=True)
                    print(f"已创建日志目录:{log_dir}")
        logging.config.dictConfig(config)
    
        _logger_initialized = True
    
    
  • config/logging_config.yaml
    version: 1
    disable_existing_loggers: False
    
    formatters:
      simple:
        format: "%(asctime)s - %(levelname)s - %(name)s.%(funcName)s:%(lineno)d - %(message)s"
    
    handlers:
      #控制台日志
      console:
        class: logging.StreamHandler
        level: INFO
        formatter: simple
        stream: ext://sys.stdout
    
      #info日志文件, 按时间和文件大小轮转
      info_file:
        class: concurrent_log_handler.ConcurrentTimedRotatingFileHandler
        level: INFO
        formatter: simple
        filename: ../logs/info/log_info.log
        when: midnight
        backupCount: 7
        maxBytes: 104857600  # 100 MB
        encoding: utf8
    
      #error日志文件, 按时间和文件大小轮转
      error_file:
        class: concurrent_log_handler.ConcurrentTimedRotatingFileHandler
        level: ERROR
        formatter: simple
        filename: ../logs/error/log_error.log
        when: midnight
        backupCount: 7
        maxBytes: 104857600  # 100 MB
        encoding: utf8
    
    loggers:
      root:  # root logger
        level: DEBUG
        handlers: [console, info_file, error_file]
    
      #指定某一个文件中的日志级别
      'spiders.js_spider':
        level: INFO
    

三、目录结构及结果展示

  • 执行时需要在主函数main方法中执行setup_logger()初始化日志
    在这里插入图片描述

您可能感兴趣的与本文相关的镜像

Python3.9

Python3.9

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值