平时写的一些小程序时,需要日志来记录程序运行的情况,但是python标准库 logging 配置起来比较麻烦,所以自己写个函数实现日志功能。
废话不多说,先上代码:
# encoding:utf-8
from sys import exc_info, _getframe
import time
from traceback import TracebackException
def logger(message: str, level='ERROR'):
"""
当调用logger时,直接给参数字符串时,会写入文件 log
当给定 level='ERROR' 参数时,另外还会写入异常产生的轨迹,没有则为 None,建议在 except 中使用
:param message:可传入异常信息
:param level:
:return:
"""
try:
if isinstance(message, str):
time_now = time.strftime('%Y-%m-%d %H:%M:%S')
year_month = time.strftime('%Y-%m')
log_name = 'log' + year_month + '.txt'
with open(log_name, 'a', encoding='utf-8') as temp:
file_path, func_name, line_no = find_caller() # 报告日志打印位置
file_name = str(file_path).split('\\')[-1]
format_message = "{time} | {level} | {file_name}:{func_name}:{line_no} - {message}\n".format(
time=time_now, level=level, file_name=file_name,
func_name=func_name, line_no=line_no, message=message
)
tbe = trace_information()
if level == 'ERROR':
print(format_message, ''.join(tbe.format()), file=temp)
print(format_message, ''.join(tbe.format()))
else:
print(format_message, file=temp)
print(format_message)
except Exception as e:
logger('日志发生异常:' + str(e))
def find_caller():
"""
Find the stack frame of the caller so that we can note the source
file name, line number and function name.
抛出一个异常,通过向上查找的方式,找到调用者的信息
# f = sys._getframe(1).f_back
:returns 返回调用者所在的文件名,模块名,行号
"""
try:
raise SystemError
except SystemError:
# f = exc_info()[2].tb_frame.f_back
f = _getframe(1).f_back
return f.f_code.co_filename, f.f_code.co_name, f.f_lineno
def trace_information():
"""
获取异常时的栈轨迹
:return:
"""
exc_type, exc_value, exc_tb = exc_info()
tbe = TracebackException(
exc_type, exc_value, exc_tb,
)
return tbe
其中的函数 find_caller 和 trace_information 是从 logging 源代码中摘抄出来的,用于获取调用者的位置 以及 发生异常时 的异常轨迹。
输出在日志文件和控制台的结果如下图,可以根据实际情况增加或修改功能。