首页 > 代码库 > python 日志模块(不使用配置文件)
python 日志模块(不使用配置文件)
""" 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 日志模块(不使用配置文件)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。