python elegant log (stack trace)

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/u011510825/article/details/83929151

    3 years, to solve the numerous problems online. It goes without saying for the log line to locate and analyze important issues. So how elegant python logging it?

 

    First of all, python logging, logging module is the first choice, was doing anything controversial.

    General written log is this:

logging.info('info message')
logging.error('error message')

   This log is generally of little use, can only locate where to step to the implementation of some of the information and print output execution of the program. For some of the information listed exceptions, we need to try: execpt get.

    Many people are so abnormal log records:

>>> def test(a):
...     int(a)
>>> try:
...     test("a")
... except Exception as e:
...     print(e.message)
...
invalid literal for int() with base 10: 'a'

    Developers only to see the error of his party python, it is difficult to locate the problem. We need to stack error message, locate the source of the error, for example:

>>> try:
...     test("a")
... except Exception as e:
...     logging.exception(e)
...
ERROR:root:invalid literal for int() with base 10: 'a'
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "<stdin>", line 2, in test
ValueError: invalid literal for int() with base 10: 'a'

Use logging.exception, then you can get a stack information. Is not it amazing, we take a look logging of source code, to see why it can get a stack information.

Comparison error

Found, exception is actually calls the error, the only not at the same time, there is a default parameter exc_info = True. . . It's been calling to see relations, to here:

See here, it should be clear, in fact, he uses sys.exc_info (), the python built-sys function. . .

 

Understand the principles of logging.exception, we can define the log:

>>> try:
...     test("a")
... except Exception as e:
...     logging.error("执行test函数报错", exc_info=True)
...
ERROR:root:执行test函数报错
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "<stdin>", line 2, in test
ValueError: invalid literal for int() with base 10: 'a'

Thus, not only can customize logging, you can also print stack information. info Similarly, as long as the error info can be changed.

 

 

Guess you like

Origin blog.csdn.net/u011510825/article/details/83929151