首页 > 编程语言 > 详细

python 日志模块(不使用配置文件)

时间:2014-12-15 22:08:58      阅读:344      评论:0      收藏:0      [点我收藏+]
"""
    author: htfang
    date  : 2014 12 15

    logging module , use multiple logs without a log config file
"""
import logging
from logging import (DEBUG,
                     CRITICAL,
                     FATAL,
                     ERROR,
                     WARNING,
                     WARN,
                     INFO,
                     DEBUG,
                     NOTSET)

import sys

class LogBuilder():
    """
    as a rookie, you need‘nt know how this builder construct, just learn how to use it!!!
    example:

    log = LogBuilder()
    fd_log = log.getLogger("fd")
    mq_log = log.getLogger("mq")

    fd_log.error("error")
    mq_log.info("info") 


    if you module need log,
    first add a item in LOG_NAMES,appiont handlers and log level(ni dong de!!!)
    second config your handlers in FILE_HANDLERS or STREAM_HANDLERS whitch you appiont in LOG_NAMES,
    then select or add a format to your handlers in FORMATTERS
    """
    LOG_NAMES = {
            "fd":{"handlers":["frame","stderr",],"level":DEBUG},
            "mq":{"handlers":["rabbitmq","stderr",],"level":DEBUG},
        }

    FILE_HANDLERS = {
            "frame":{"fileName":"frame.log","format":"dft"},
            "rabbitmq":{"fileName":"rabbitmq.log","format":"dft"},
        }

    STREAM_HANDLERS = {
            "stdin":{"fileName":sys.stdin, "format":"dft"},
            "stdout":{"fileName":sys.stdout, "format":"dft"},
            "stderr":{"fileName":sys.stderr, "format":"dft"},
        }

    FORMATTERS = {
            "dft":{"fmt":("%(name)s %(asctime)s %(filename)s[line:%(lineno)d]%(levelname)s:%(message)s", 
                ‘%a, %d %b %Y %H:%M:%S‘)},
        }

    def __init__(self):
        for format_name in self.FORMATTERS:
            formatter = logging.Formatter(self.FORMATTERS[format_name]["fmt"][0],
                    self.FORMATTERS[format_name]["fmt"][1])
            self.FORMATTERS[format_name]["formatter"] = formatter

        for handler_name in self.FILE_HANDLERS:
            file_handler = logging.FileHandler(self.FILE_HANDLERS[handler_name]["fileName"])
            file_handler.setFormatter(self.FORMATTERS[self.FILE_HANDLERS[handler_name]["format"]]["formatter"])
            self.FILE_HANDLERS[handler_name]["handler"] = file_handler

        for handler_name  in self.STREAM_HANDLERS:
            stream_handler = logging.StreamHandler(self.STREAM_HANDLERS[handler_name]["fileName"])
            stream_handler.setFormatter(self.FORMATTERS[self.STREAM_HANDLERS[handler_name]["format"]]["formatter"])
            self.STREAM_HANDLERS[handler_name]["handler"] = stream_handler

        for log_name in self.LOG_NAMES:
            logger = logging.getLogger(log_name)

            for handler_name in self.LOG_NAMES[log_name]["handlers"]:
                try:
                    logger.addHandler(self.FILE_HANDLERS[handler_name]["handler"])
                except:
                    logger.addHandler(self.STREAM_HANDLERS[handler_name]["handler"])
                else:
                    pass

            logger.setLevel(self.LOG_NAMES[log_name]["level"])
            self.LOG_NAMES[log_name]["logger"] = logger

    def getLogger(self,log_name):
        return self.LOG_NAMES[log_name]["logger"]
                

log = LogBuilder()

python 日志模块(不使用配置文件)

原文:http://fangnux.blog.51cto.com/7902770/1590082

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!