11import json
22import logging
33
4+ from zcs .core .exception import ZcsException
5+
6+ old_factory = logging .getLogRecordFactory ()
7+
8+ def record_factory (* args , ** kwargs ):
9+ record = old_factory (* args , ** kwargs )
10+
11+ record .error_code = None
12+ if args [4 ] and isinstance (args [4 ], ZcsException ):
13+ record .error_code = args [4 ].get_error_code ()
14+
15+ # Set original exception value if needed
16+ record .original_exception = None
17+ if args [6 ] is not None :
18+ for arg in args [6 ]:
19+ if isinstance (arg , Exception ):
20+ record .original_exception = arg
21+ if isinstance (arg , ZcsException ):
22+ record .error_code = arg .get_error_code ()
23+
24+ return record
25+
26+ logging .setLogRecordFactory (record_factory )
27+
428class CloudJsonFormatter (logging .Formatter ):
529 def format (self , record ):
30+
31+ message = record .getMessage ()
32+ if record .exc_info and record .original_exception :
33+ message = str (record .original_exception )
34+
635 log_record = {
736 "severity" : record .levelname ,
8- "message" : record .getMessage (),
9- "time" : self .formatTime (record , self .datefmt )
37+ "message" : message ,
38+ "time" : self .formatTime (record , self .datefmt ),
39+ "logging.googleapis.com/sourceLocation" : {
40+ "file" : record .filename ,
41+ "line" : record .lineno ,
42+ "function" : record .funcName ,
43+ "pathname" : record .pathname ,
44+ "traceback" : self .formatException (record .exc_info ) if record .exc_info else ""
45+ },
46+ "logging.googleapis.com/labels" : {
47+ "logger_name" : record .name ,
48+ "error_code" : record .error_code ,
49+ },
1050 }
1151 return json .dumps (log_record )
1252
@@ -29,7 +69,7 @@ def __init__(self, verbose = False):
2969
3070 self .FORMATTERS = {
3171 logging .DEBUG : logging .Formatter (set_grey + base_format + reset ),
32- logging .INFO : logging .Formatter (set_green + base_format + reset ),
72+ logging .INFO : logging .Formatter (base_format ),
3373 logging .WARNING : logging .Formatter (set_yellow + base_format + reset ),
3474 logging .ERROR : logging .Formatter (set_red + base_format + reset ),
3575 logging .CRITICAL : logging .Formatter (set_bold_red + base_format + reset )
0 commit comments