一、前言:
对Python 日志模块logging进行了格式化输出封装,形成自己的日志格式。以后就可以拿来主义了。
1.输出到控制台。
2.输出到当前workspace指定文件。
二、代码:
##模块[log.py]
import logging
import unittest
import sys
def handleException(excType, excValue, traceback, logger):
logger.error("Uncaught exception", exc_info=(excType, excValue, traceback))
class Log(object):
@staticmethod
def log(tag, message, level=logging.INFO):
"""
Log messages to console and file(create to current workspace)
Args:
tag: message tag
message: the message
level(optional): logging level of the message
"""
logger = Log.get_logger(tag)
if level == logging.INFO:
logger.info(message)
if level == logging.WARNING:
logger.warning(message)
if level == logging.DEBUG:
logger.debug(message)
if level == logging.CRITICAL:
logger.critical(message)
if level == logging.ERROR:
logger.error(message)
@staticmethod
def get_logger(tag):
"""
Setup the logger
"""
if len(logging.root.handlers) == 0:
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s [%(levelname)s][%(name)s]: %(message)s',
filename='console.log',
filemode='a')
console = logging.StreamHandler()
console.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s [%(levelname)s][%(name)s]: %(message)s')
console.setFormatter(formatter)
logging.getLogger('').addHandler(console)
sys.excepthook = handleException
return logging.getLogger(tag)
三、测试:
from log import Log
Log.log(“tag”,"test log model~")
尊重劳动成果,转载请注明出处,Thx。