以上方法的定义中,除了msg和位置参数args外,还有关键字参数**kwargs,主要有三个关键字参数:
1. exc_info
exc_info为布尔值,如果该参数的值为True时,则会将异常信息添加到日志消息中;如果没有则会将None添加到日志信息中。
比如:logging.error(f'程序运行异常,{str(e)}', exc_info=True)
2. stack_info
stack_info值为布尔值,默认为False,如果该参数的值设为True,栈信息将会被添加到日志信息中。
3. extra
extra是一个字典参数,它可以用来自定义消息格式中所包含的字段,但是它的key不能与logging模块定义的字段冲突。
举例,以上三种情况举例如下:
# 日志格式中添加了user、ip两个字段
import logging
LOG_FORMAT = "%(asctime)s - %(levelname)s - %(user)s[%(ip)s] - %(message)s"
DATE_FORMAT = "%m/%d/%Y %H:%M:%S %p"
logging.basicConfig(format=LOG_FORMAT, datefmt=DATE_FORMAT)
try:
a = 1 / 0
except Exception as e:
logging.error(f"error info: {str(e)}", exc_info=True, stack_info=True,
extra={'user': 'Tom', 'ip': '47.98.53.222'})
上面举例的运行结果为:
07/19/2021 11:09:23 AM - ERROR - Tom[47.98.53.222] - error info: division by zero
Traceback (most recent call last):
File "D:/test/vv_finance_auto_trading_python-dev/bank_login/test.py", line 45, in logging_test
a = 1 / 0
ZeroDivisionError: division by zero
Stack (most recent call last):
File "D:/test/vv_finance_auto_trading_python-dev/bank_login/test.py", line 70, in <module>
logging_test()
File "D:/test/vv_finance_auto_trading_python-dev/bank_login/test.py", line 48, in logging_test
extra={'user': 'Tom', 'ip': '47.98.53.222'})
如果代码中没有stack_info = True,则栈信息就不会出现在日志信息中。
LOG_FORMAT = "%(asctime)s - %(levelname)s - %(user)s[%(ip)s] - %(message)s"
DATE_FORMAT = "%m/%d/%Y %H:%M:%S %p"
logging.basicConfig(format=LOG_FORMAT, datefmt=DATE_FORMAT)
logging.warning("Some one delete the log file.", exc_info=True,extra={'user': 'Tom', 'ip':'47.98.53.222'})
以上输入信息为:
07/19/2021 11:05:32 AM - ERROR - Tom[47.98.53.222] - error info: division by zero
Traceback (most recent call last):
File "D:/test/vv_finance_auto_trading_python-dev/bank_login/test.py", line 45, in logging_test
a = 1 / 0
ZeroDivisionError: division by zero