"""
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()