Python中日志记录方法
郝伟 2021/03/02
在工程项目中,日志是必不可少的内容。我们可以自己定义写日志的函数,也可以使用系统自带的库。本文提供了两种方式,以便于用户选择。
写日志实际上就是要将当前的状态写到文件中,同时对相关信息,如时间函数名称等进行补充。如果自己写函数需要进行相同的操作,核心代码如下所示。
自定义的函数没有系统功能多,但是在某些功能上更加强大,推荐中小型项目使用。比如:
", , 等的影响,使之成为格式正确的csv文件,从而便于后期分析。# -*- coding: utf-8 -*- """ 日期:2021/03/02 作者:郝伟老师 邮箱:hwaust@126.com 简介:本代码使用自定义的函数实现日志功能。 """ import sys, time, os, threading def get_head_info(msg, lt='DEBUG'): try: raise Exception except: f = sys.exc_info()[2].tb_frame.f_back fucName=f.f_code.co_name lineNo = f.f_lineno pathName=sys.argv[0] timeTick=time.strftime('%Y/%m/%d %H:%M:%S.') + str(time.time()).split('.')[1] threadId=threading.currentThread().ident threadName=threading.currentThread().getName() processID=os.getpid() parentProcID=os.getppid() return ','.join(str(item) for item in [timeTick,processID,parentProcID,threadId,threadName,pathName,fucName,lineNo,lt,msg]) def f1(): print(get_head_info("hello")) print(get_head_info('test')) f1()
输出如下:
2021/03/02 16:58:55.4992092,19684,36420,33132,MainThread,c:\Users\hao\Documents\Gitee.com\MyNotes\test.py,<module>,21,DEBUG,test
2021/03/02 16:58:55.536082,19684,36420,33132,MainThread,c:\Users\hao\Documents\Gitee.com\MyNotes\test.py,f1,19,DEBUG,hello
系统自带的logging模块功能非常强大,以下只是一个简单的应用示例,更多可以参考以下三个链接:
[1] Python logging模块用法记录,https://blog.csdn.net/zywvvd/article/details/87857816
[2] Python之日志处理(logging模块), https://www.cnblogs.com/yyds/p/6901864.html
[3] Logging HOWTO, https://docs.python.org/3.7/howto/logging.html
# -*- coding: utf-8 -*- """ 日期:2021/03/02 作者:郝伟老师 邮箱:hwaust@126.com 简介:本代码使用系统的logging实现基本的日志功能,其中日志类型的优化级为: DEBUG < INFO < WARNING < ERROR < CRITICAL """ import logging hwlog = logging.getLogger('hwlog.log') # filename 表示文件名,包含在 pathname中,故省略。 keys=['%(' + s + ')s' for s in 'asctime,process,thread,pathname,funcName,lineno,levelname,message'.split(',')] #print(','.join(keys)) logging.basicConfig( datefmt ='%Y%m%d_%H%M%S', filemode ='a', # 默认是追加,也可以每次都新建 level=logging.DEBUG, format= ','.join(keys), filename=('debug.txt') ) # logging.getLogger().setLevel(logging.WARNING) hwlog.setLevel(logging.DEBUG) def f(): hwlog.debug('hello') hwlog.critical('test') f() # 注意这行不加如果程序尚未退出,则相关的日志文件会一直处于打开状态。 logging.shutdown()
输出以下内容
20210302_162843,27668,24040,c:\Users\hao\Documents\Gitee.com\MyNotes\logtest.py,<module>,40,CRITICAL,test
20210302_162843,27668,24040,c:\Users\hao\Documents\Gitee.com\MyNotes\logtest.py,lvtest,39,ERROR,hello
注:以下代码可以实现自定义的过滤器
''' class MyFilter(object): def __init__(self, level): self.__level = level def filter(self, logRecord): return logRecord.levelno <= self.__level #create a logger logger = logging.getLogger('mylogger') logger.setLevel(logging.DEBUG) handler = logging.FileHandler('mylog1.log') formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s %(line)s - %(message)s') handler.setFormatter(formatter) #set filter to log only DEBUG lines # handler.addFilter(MyFilter(logging.DEBUG)) # logger.addHandler(handler) #write a debug line to log file logger.debug('This is a DEBUG message') logger.info('This is a INFO message') logger.warning('This is a WARNING message') logger.error('This is an ERROR message') logger.critical('This is a CRITICAL message') #create a logger logger = logging.getLogger('mylogger') #set logging level logger.setLevel(logging.DEBUG) handler = logging.FileHandler('mylog.log') # create a logging format formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') handler.setFormatter(formatter) logger.addHandler(handler) #write a debug message logger.debug('This is a DEBUG message') '''