Open
Description
I am trying to log with a custom JSON serialization and include the traceback and exception details in the JSON. I used patch()
in order to do this.
Unexpectedly, unless i add the following line record['exception'] = None
to patching()
loguru will log the traceback in a non-JSON format even though I am using format="{extra[serialized]}"
See the code below
Am i doing something wrong or is this a bug?
import sys
import traceback
from loguru import logger
def serialize(record):
error = record["exception"]
if error: # only set when exception.
exception = {
"type": error.type.__name__,
"value": str(error.value),
"traceback": "".join(traceback.format_exception(*error)),
}
else:
exception = None
subset = {
"timestamp": record["time"].timestamp() * 1000, # Should be in milliseconds for Datadog
"message": record["message"],
"level": record["level"].name,
"status": str(record["level"].name),
"logger": {"thread_name": str(record["thread"].name)},
"file": f"{record['file']}",
"function": f"{record['function']}",
"line": f"{record['line']}",
"module": f"{record['module']}",
"name": f"{record['name']}",
"process": f"{record['process']}",
"thread": f"{record['thread']}",
"exception": exception
}
return json.dumps(subset)
def patching(record):
record["extra"]["serialized"] = serialize(record)
# record['exception'] = None
logger.remove(0) # Remove the original logger
logger = logger.patch(patching)
logger.add(sys.stdout, format="{extra[serialized]}")
def log_exception():
try:
open("fakefile.txt")
except:
logger.exception('')
log_exception()