1
1
import json
2
2
import logging
3
- from typing import Any
4
-
5
-
6
- def json_formatter (unserializable_value : Any ):
7
- """JSON custom serializer to cast unserializable values to strings.
8
-
9
- Example
10
- -------
11
-
12
- **Serialize unserializable value to string**
13
-
14
- class X: pass
15
- value = {"x": X()}
16
-
17
- json.dumps(value, default=json_formatter)
18
-
19
- Parameters
20
- ----------
21
- unserializable_value: Any
22
- Python object unserializable by JSON
23
- """
24
- return str (unserializable_value )
25
3
26
4
27
5
class JsonFormatter (logging .Formatter ):
@@ -44,17 +22,15 @@ def __init__(self, **kwargs):
44
22
45
23
Other kwargs are used to specify log field format strings.
46
24
"""
47
- self .default_json_formatter = kwargs .pop ("json_default" , json_formatter )
25
+ self .default_json_formatter = kwargs .pop ("json_default" , str )
48
26
datefmt = kwargs .pop ("datefmt" , None )
49
27
50
28
super (JsonFormatter , self ).__init__ (datefmt = datefmt )
51
29
self .reserved_keys = ["timestamp" , "level" , "location" ]
52
- self .format_dict = {
53
- "timestamp" : "%(asctime)s" ,
54
- "level" : "%(levelname)s" ,
55
- "location" : "%(funcName)s:%(lineno)d" ,
56
- "message" : None ,
57
- }
30
+ self .format_dict = dict .fromkeys (kwargs .pop ("format_key" , ["level" , "location" , "message" , "timestamp" ]))
31
+ self .format_dict .update (
32
+ {"level" : "%(levelname)s" , "location" : "%(funcName)s:%(lineno)d" , "timestamp" : "%(asctime)s" }
33
+ )
58
34
self .format_dict .update (kwargs )
59
35
60
36
def update_formatter (self , ** kwargs ):
0 commit comments