@@ -23,8 +23,12 @@ class FluentRecordFormatter(logging.Formatter, object):
23
23
Best used with server storing data in an ElasticSearch cluster for example.
24
24
25
25
:param fmt: a dict with format string as values to map to provided keys.
26
+ :param datefmt: strftime()-compatible date/time format string.
27
+ :param style: (NOT USED)
28
+ :param fill_missing_fmt_key: if True, do not raise a KeyError if the format
29
+ key is not found. Put None if not found.s
26
30
"""
27
- def __init__ (self , fmt = None , datefmt = None , style = '%' ):
31
+ def __init__ (self , fmt = None , datefmt = None , style = '%' , fill_missing_fmt_key = False ):
28
32
super (FluentRecordFormatter , self ).__init__ (None , datefmt )
29
33
30
34
if not fmt :
@@ -38,6 +42,8 @@ def __init__(self, fmt=None, datefmt=None, style='%'):
38
42
39
43
self .hostname = socket .gethostname ()
40
44
45
+ self .fill_missing_fmt_key = fill_missing_fmt_key
46
+
41
47
def format (self , record ):
42
48
# Only needed for python2.6
43
49
if sys .version_info [0 :2 ] <= (2 , 6 ) and self .usesTime ():
@@ -47,9 +53,18 @@ def format(self, record):
47
53
super (FluentRecordFormatter , self ).format (record )
48
54
# Add ours
49
55
record .hostname = self .hostname
56
+
50
57
# Apply format
51
- data = dict ([(key , value % record .__dict__ )
52
- for key , value in self ._fmt_dict .items ()])
58
+ data = {}
59
+ for key , value in self ._fmt_dict .items ():
60
+ try :
61
+ value = value % record .__dict__
62
+ except KeyError as exc :
63
+ value = None
64
+ if not self .fill_missing_fmt_key :
65
+ raise exc
66
+
67
+ data [key ] = value
53
68
54
69
self ._structuring (data , record )
55
70
return data
0 commit comments