python爬虫学习之日志记录模块
2023-03-14 09:45:57 时间
这次的代码就是一个日志记录模块,代码很容易懂,注释很详细,也不需要安装什么库。提供的功能是日志可以显示在屏幕上并且保存在日志文件中。
调用的方式也很简单,测试代码里面有。
源代码:
#encoding=utf-8 import logging import getpass import sys # 定义MyLog类 class MyLog(object): # 类MyLog的构造函数 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' #print(sys.argv[0]) 代表文件名 输出 mylog.py self.formatter = logging.Formatter('%(asctime)-12s %(levelname)-8s %(name)-10s %(message)-12s\r\n') # 日志显示到屏幕上并输出到日志文件内 # 输出到日志文件 self.logHand = logging.FileHandler(self.logFile, encoding='utf8') self.logHand.setFormatter(self.formatter) self.logHand.setLevel(logging.DEBUG) # 输出到屏幕 self.logHandSt = logging.StreamHandler() self.logHandSt.setFormatter(self.formatter) self.logHandSt.setLevel(logging.DEBUG) # 添加两个Handler 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 warning(self,msg): self.logger.warning(msg) def error(self,msg): self.logger.error(msg) def critical(self,msg): self.logger.critical(msg) if __name__ == '__main__': mylog = MyLog() mylog.debug(u"I'm debug 测试中文") mylog.info("I'm info") mylog.warning("I'm warn") mylog.error(u"I'm error 测试中文") mylog.critical("I'm critical")
测试结果:
相关文章
- Python之configparser模块详解和使用
- Python教程:selenium模块用法教程
- 软件测试|Python基础之面向对象(一)
- 软件测试|Python基础之面向对象(二)
- 软件测试|Python基础之面向对象(三)
- 软件测试|Python基础之面向对象(四)
- 软件测试|Python基础之模块导入和使用
- 软件测试|Python基础之包的使用和软件开发目录规范及常用内置模块
- 软件测试|Python内置模块使用(一)
- 软件测试|Python第三方库使用(一)
- 软件测试|Python基础之数据库
- 软件测试|什么是Python函数及名称空间?
- 软件测试|教你轻松玩转Python日期时间
- 软件测试|教你如何用Python获取昨天今天明天的日期
- 软件测试|Python高手教你玩转 Excel 自动化
- 软件测试|Python神器logging,你真的了解吗?
- 软件测试|Python删除列表元素的3种方法,你都会吗?
- 软件测试|神操作!用 Python 操作 xmind 绘制思维导图
- 软件测试|Python实用炫酷技能——推导式
- 软件测试|一步到位教会你Python字典操作(一)