您的位置:首页 > 编程语言 > Python开发

为python脚本设计自己的log模块

2018-02-25 13:13 399 查看
这个方法是来自《python网络实战》(清华大学出版社)中推荐使用的log方法,原理是利用log功能抽象出一个专门的模块负责log记录,剥离之后模块可以提供更多的自定义空间,使用起来非常方便

import loggingimport getpassimport sys
#定义Mylog类,管理log信息class MyLog(object): def __init__(self): self.user = getpass.getuser() self.logger = logging.getLogger(self.user) self.logger.setLevel(logging.DEBUG)
#日志文件名 self.logFile = sys.argv[0][0:-3] + '.log' self.formatter = logging.Formatter('%(asctime)-12s %(levelname)- 8s %(name)-10s %(message)-12s\r\n')
#日志显示到屏幕并输出到文档 self.logHand = logging.FileHandler(self.logFile, encoding='utf-8') self.logHand.setFormatter(self.formatter) self.logHand.setLevel(logging.DEBUG)
self.logHandSt = logging.StreamHandler() self.logHandSt.setFormatter(self.formatter) self.logHandSt.setLevel(logging.DEBUG)
self.logger.addHandler(self.logHand) self.logger.addHandler(self.logHandSt)
#日志的5个级别对应5个函数 def debug(self, msg): self.logger.debug(msg)
def info(self, msg): self.logger.info(msg)
def warn(self, msg): self.logger.warn(msg)
def error(self, msg): self.logger.error(msg)
def critical(self, msg): self.logger.critical(msg)
#测试代码 __name__是访问当前函数名的方法,如果作为模块就不是main函数 下面的方法不会执行if __name__ == '__main__': mylog = MyLog() mylog.debug(u"I'm 测试中文") mylog.info("I;m info") mylog.warn("warning") mylog.error("Error") mylog.critical("this is a critical")

在别的模块中引用时,需要import Mylog,然后调用里面的方法即可
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python log