44import traceback
55
66from datetime import datetime as _datetime
7+ from typing import Dict as _Dict , Union as _Union , Callable as _Callable , Any as _Any
78
89__all__ = ['Formatter' , 'CONSOLE_REPORTER_FORMAT' , 'FILE_REPORTER_FORMAT' , 'EMAIL_REPORTER_FORMAT' ]
910
11+ RESERVED_KEYS = (
12+ '__name__' ,
13+ 'type' ,
14+ 'message' ,
15+ 'traceback' ,
16+ 'name' ,
17+ 'file' ,
18+ 'lineno' ,
19+ 'function' ,
20+ 'asctime'
21+ )
22+
1023
1124class Formatter :
12- def __init__ (self , format_ : str , style : str = '%' , datefmt : str = '%Y-%m-%d %H:%M:%S' ):
25+ def __init__ (self , format_ : str , style : str = '%' , datefmt : str = '%Y-%m-%d %H:%M:%S' ,
26+ extra_values : _Dict [str , _Union [str , _Callable , _Any ]] = None ):
1327 self ._format = format_
1428
1529 if style in ['%' , '{' ]:
@@ -18,6 +32,12 @@ def __init__(self, format_: str, style: str = '%', datefmt: str = '%Y-%m-%d %H:%
1832 raise ValueError ('Invalid style: "' + str (style ) + '" Valid styles: %, {' )
1933
2034 self .datefmt = datefmt
35+ self .extra_values = dict ()
36+ if extra_values :
37+ for key in extra_values :
38+ if key in RESERVED_KEYS :
39+ raise ValueError (f'`{ key } ` is a reserved-key and cannot be used in `extra_values`.' )
40+ self .extra_values [key ] = extra_values [key ]
2141
2242 def format (self , exception : BaseException ):
2343 exception_dict = {
@@ -31,6 +51,11 @@ def format(self, exception: BaseException):
3151 'function' : exception .__traceback__ .tb_next .tb_frame .f_code .co_name ,
3252 'asctime' : _datetime .now ().strftime (self .datefmt ),
3353 }
54+ for key , value in self .extra_values .items ():
55+ if callable (value ):
56+ exception_dict [key ] = value ()
57+ else :
58+ exception_dict [key ] = value
3459
3560 if self .__style == '%' :
3661 return self ._format % exception_dict
0 commit comments