5
5
import logging
6
6
import json
7
7
import re
8
- import datetime
8
+ from datetime import date , datetime , time
9
9
import traceback
10
10
11
11
from inspect import istraceback
@@ -44,6 +44,28 @@ def merge_record_extra(record, target, reserved=RESERVED_ATTR_HASH):
44
44
return target
45
45
46
46
47
+ class JsonEncoder (json .JSONEncoder ):
48
+ """
49
+ A custom encoder extending the default JSONEncoder
50
+ """
51
+ def default (self , obj ):
52
+ if isinstance (obj , (date , datetime , time )):
53
+ return self .format_datetime_obj (obj )
54
+
55
+ elif istraceback (obj ):
56
+ return '' .join (traceback .format_tb (obj )).strip ()
57
+
58
+ elif type (obj ) == Exception \
59
+ or isinstance (obj , Exception ) \
60
+ or type (obj ) == type :
61
+ return str (obj )
62
+
63
+ return super (JsonEncoder , self ).default (obj )
64
+
65
+ def format_datetime_obj (self , obj ):
66
+ return obj .isoformat ()
67
+
68
+
47
69
class JsonFormatter (logging .Formatter ):
48
70
"""
49
71
A custom formatter to format logging records as json strings.
@@ -69,17 +91,8 @@ def __init__(self, *args, **kwargs):
69
91
#super(JsonFormatter, self).__init__(*args, **kwargs)
70
92
logging .Formatter .__init__ (self , * args , ** kwargs )
71
93
if not self .json_encoder and not self .json_default :
72
- def _default_json_handler (obj ):
73
- '''Prints dates in ISO format'''
74
- if isinstance (obj , (datetime .date , datetime .time )):
75
- return obj .isoformat ()
76
- elif istraceback (obj ):
77
- tb = '' .join (traceback .format_tb (obj ))
78
- return tb .strip ()
79
- elif isinstance (obj , Exception ):
80
- return "Exception: %s" % str (obj )
81
- return str (obj )
82
- self .json_default = _default_json_handler
94
+ self .json_encoder = JsonEncoder
95
+
83
96
self ._required_fields = self .parse ()
84
97
self ._skip_fields = dict (zip (self ._required_fields ,
85
98
self ._required_fields ))
0 commit comments