简介

在任何工程项目中,日志都是必不可少的内容。在Python语言中,有自带的日志库也有第三方的日志库,或者我们可以自己定义写日志的函数。本文提供了两种方式,以便于用户选择。

自定义方法

写日志实际上就是要将当前的状态写到文件中,同时对相关信息,如时间函数名称等进行补充。如果自己写函数需要进行相同的操作,核心代码如下所示。
自定义的函数没有系统功能多,但是在某些功能上更加强大,推荐中小型项目使用。比如:

  • 可以追加更多的信息,比如process的父进程名称,或者追加其他信息如项目名称,作者名称等;
  • 可以对消息字符串进行转义, 从而避免 ", , 等的影响,使之成为格式正确的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模块

系统自带的logging模块功能非常强大,以下只是一个简单的应用示例

# -*- 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')
('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')