Skip to content

Commit 2f3e1d1

Browse files
committed
补全UPDATE
1 parent d554d5c commit 2f3e1d1

1 file changed

Lines changed: 71 additions & 0 deletions

File tree

‎Python Common/如何创建记录异常日志的装饰器.org‎

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,3 +70,74 @@
7070
#+END_EXAMPLE
7171

7272
我觉得这份代码很方便,我希望你们大家也会觉得有用.
73+
74+
UPDATE: 一个热心的读者提出,将代码泛化成从外界传递一个logger对象到装饰器会更好些. 那么然我们来看看如何实现它!
75+
76+
* 传递logger到我们的装饰器中
77+
首先,将原始的代码中的logging代码拆到自己的模块中。 假设放到文件exception_logger.py中. 下面是源代码:
78+
#+BEGIN_SRC python
79+
# exception_logger.py
80+
import logging
81+
def create_logger():
82+
"""
83+
Creates a logging object and returns it
84+
"""
85+
logger = logging.getLogger("example_logger")
86+
logger.setLevel(logging.INFO)
87+
# create the logging file handler
88+
fh = logging.FileHandler(r"/path/to/test.log")
89+
fmt = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
90+
formatter = logging.Formatter(fmt)
91+
fh.setFormatter(formatter)
92+
# add handler to logger object
93+
logger.addHandler(fh)
94+
return logger
95+
logger = create_logger()
96+
#+END_SRC
97+
98+
然后我们修改装饰器代码,使之接受一个logger为参数并保存为exception_decor.py
99+
#+BEGIN_SRC python
100+
# exception_decor.py
101+
102+
import functools
103+
104+
105+
def exception(logger):
106+
"""
107+
A decorator that wraps the passed in function and logs
108+
exceptions should one occur
109+
110+
@param logger: The logging object
111+
"""
112+
113+
def decorator(func):
114+
115+
def wrapper(*args, **kwargs):
116+
try:
117+
return func(*args, **kwargs)
118+
except:
119+
# log the exception
120+
err = "There was an exception in "
121+
err += func.__name__
122+
logger.exception(err)
123+
124+
# re-raise the exception
125+
raise
126+
return wrapper
127+
return decorator
128+
#+END_SRC
129+
130+
你会发现我们定义了多层嵌套的函数。 请看仔细并理解其中的意思。 最后,我们需要修改一下测试的代码:
131+
#+BEGIN_SRC python
132+
from exception_decor import exception
133+
from exception_logger import logger
134+
135+
@exception(logger)
136+
def zero_divide():
137+
1 / 0
138+
139+
if __name__ == '__main__':
140+
zero_divide()
141+
#+END_SRC
142+
143+
代码中,我们导入了装饰器和logger对象。 然后我们将装饰器作用于要记录的函数,并且我们给该装饰器传递了一个logger对象。 你运行该测试代码后,会发现产生了与第一个测试相同的文件.

0 commit comments

Comments
 (0)