栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python日志配置demo

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python日志配置demo

python日志配置demo

  • 日志类
# -*- coding: utf-8 -*-
import os
import sys
import threading
import logging
import logging.config

CONFIG_FILE = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'log.config')


class LogConfig(object):
    """日志配置类
    """

    _instance_lock = threading.Lock()

    def __new__(cls, *args, **kwargs):
        """单例模式
        """
        if not hasattr(LogConfig, "_instance"):
            with LogConfig._instance_lock:
                if not hasattr(LogConfig, "_instance"):
                    LogConfig._instance = object.__new__(cls)
        return LogConfig._instance

    def __init__(self, config_file=CONFIG_FILE):
        super().__init__()
        #日志配置文件
        self.__config_file = config_file
        #默认创建log文件夹,设置其他日志路径,需要自己创建
        self.__log_path = os.path.join(os.path.dirname(os.path.realpath(self.__config_file)), 'logs')
        if not os.path.exists(self.__log_path):
            os.makedirs(self.__log_path)
        logging.config.fileConfig(self.__config_file)
        # 输出日志到控制台,获取的是root对应的logger
        #console_logger = logging.getLogger()
        # 输出日志到单个文件
        #file_logger = logging.getLogger(name="fileLogger")
        # rotatingFileLogger中额consoleHandler输出到控制台,rotatingHandler输出日志到文件
        if __debug__:
            self.__log = logging.getLogger("debug")
        else:
            self.__log = logging.getLogger("prod")

    def __getattr__(self, attr):
        return getattr(self.__log, attr)


log = LogConfig()

__all__ = [log]
  • 配置文件
[loggers]
keys=root,debugLogger,prodLogger

[handlers]
keys=consoleHandler,fileHandler,timedRotatingFileHandler

[formatters]
keys=simpleFormatter

[logger_root]
level=DEBUG
handlers=consoleHandler

[logger_debugLogger]
level=DEBUG
# 该logger中配置的handler
handlers=fileHandler
# logger 的名称
qualname=debug
propagate=0

[logger_prodLogger]
level=INFO
# 这样配置,timedRotatingFileLogger中就同时配置了consoleHandler,timedRotatingFileHandler
# consoleHandler 负责将日志输出到控制台
# timedRotatingFileHandler 负责将日志输出保存到文件中
handlers=timedRotatingFileHandler
qualname=prod
propagate=0

[handler_consoleHandler]
class=StreamHandler
level=DEBUG
formatter=simpleFormatter
args=(sys.stdout,)

[handler_fileHandler]
class=FileHandler
level=DEBUG
formatter=simpleFormatter
args=('logs/debug.log', 'a')

[handler_timedRotatingFileHandler]
class=handlers.TimedRotatingFileHandler
level=INFO
formatter=simpleFormatter
args=("logs/prod.log", "d")
suffix=%Y-%m-%d.log

[formatter_simpleFormatter]
format=[%(asctime)s %(module)s %(thread)d %(levelname)s Line:%(lineno)s]:%(message)s
datefmt=%Y-%m-%d %H:%M:%S
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/339811.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号