您现在的位置是:首页 > 文章详情

python单例模式实现日志记录(logging模块应用)

日期:2018-10-21点击:418

通过单例模块实现日志记录,代码如下:

import logging class Logger(object): def __init__(self): self.log_file_path = "./test.log" file_handler = logging.FileHandler(self.log_file_path, 'a', encoding='utf-8') file_handler.setFormatter(logging.Formatter(fmt="%(asctime)s - %(name)s - %(levelname)s - %(filename)s[line: %(lineno)d] : %(message)s")) self.logger = logging.Logger('cmdb', level=logging.INFO) self.logger.addHandler(file_handler) def info(self,msg): self.logger.info(msg) def error(self,msg): self.logger.error(msg) logger = Logger() 

日志记录的变量请参考: https://www.jianshu.com/p/d5ed1d5bc976 #十二、logging模块

引用:

from .logger import logger if __name__ == '__main__': logger.info("hello world") 

日志输出:

2018-10-22 12:24:37,510 - cmdb - INFO - logger.py[line: 16] : hello world 2018-10-22 12:26:18,157 - cmdb - ERROR - logger.py[line: 18] : hello world 2018-10-22 14:00:05,689 - cmdb - ERROR - logger.py[line: 19] : hello world 
原文链接:https://yq.aliyun.com/articles/656756
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章