日志报错要去修,要不然是隐患,总有一天会爆炸
增加日志是排错的好方法,不要不舍得加日志,比如怕代码变难看,怕日志输出太多。
python logging
exc_info
sys.exc_info()
This function returns a tuple of three values that give information about the exception that is currently being handled. The information returned is specific both to the current thread and to the current stack frame. If the current stack frame is not handling an exception, the information is taken from the calling stack frame, or its caller, and so on until a stack frame is found that is handling an exception. Here, “handling an exception” is defined as “executing an except clause.” For any stack frame, only information about the exception being currently handled is accessible.
If no exception is being handled anywhere on the stack, a tuple containing three None values is returned. Otherwise, the values returned are (type, value, traceback). Their meaning is: type gets the type of the exception being handled (a subclass of BaseException); value gets the exception instance (an instance of the exception type); traceback gets a traceback object (see the Reference Manual) which encapsulates the call stack at the point where the exception originally occurred.
stack_info
traceback.print_stack(f=None, limit=None, file=None)
Print up to limit stack trace entries (starting from the invocation point) if limit is positive. Otherwise, print the last abs(limit) entries. If limit is omitted or None, all entries are printed. The optional f argument can be used to specify an alternate stack frame to start. The optional file argument has the same meaning as for print_tb().
Changed in version 3.5: Added negative limit support.
两个参数确实增加了日志信息:
>>> import logging >>> try: ... assert False ... except Exception as e: ... print('e: %s' % e) ... logging.error(e, exc_info=True, stack_info=True) ... e: ERROR:root: Traceback (most recent call last): File "<stdin>", line 2, in <module> AssertionError Stack (most recent call last): File "<stdin>", line 5, in <module>
>>> try: ... assert False ... except Exception as e: ... logging.error(e) ... ERROR:root:
是否 log 都要加上以上两个参数,如果都要,python 为什么不将这两个参数变为默认参数?
这两个参数可否在 dict config 中配置?
在 python LogRecord attributes 存在
但是文档中写不需要 format:
exc_info |
You shouldn’t need to format this yourself. |
Exception tuple (à la sys.exc_info) or, if no exception has occurred, None. |
stack_info |
You shouldn’t need to format this yourself. |
Stack frame information (where available) from the bottom of the stack in the current thread, up to and including the stack frame of the logging call which resulted in the creation of this record. |
看了sentry的Django文档,没有找到能够配置 exc_info 与 stack_info 的参数。文档中都是显式调用
exc_info and extra={'stack': True}
。
python 自带的 logging 我设置了
%(exc_info)s: %(stack_info)s
,但好像没有生效。
还有一个需求,调用函数的时候出错,日志能否自动记录下调用函数的参数?
说完了格式,说下需要打日志的地方。
1. 异常分支或错误处理一定要打log
2. 重大操作时一定要打log,下面打log场景会讲述
与金钱相关。
追踪一笔订单的整个生命周期
从下单最后完成支付,发货的整个周期都需要能够通过日志追踪。
参考