I would like to add an extra variable to my logs, but only if this variable exists / is set.
Here's the solution I came up with:
import sys
from loguru import logger
def formatter(record):
if "remote_ip" in record.get("extra", []):
return "{time} | {level} | {extra[remote_ip]} | {message}\n"
else:
return "{time} | {level} | unset | {message}\n"
logger.remove(0)
logger.add(sys.stderr, format=formatter)
logger.bind(remote_ip="192.168.1.1").info("Request from client1")
logger.info("Internal message without remote_ip")
logger.bind(remote_ip="192.168.1.2").info("Request from client2")
Is this the right way to do this, or is there a better one?
One thing I don't like about this solution is that I can't easily move the logging format out of the code and into a config file.
I would prefer something like {extra.get(remote_ip, 'unset')}
but this doesn't seem possible (or at least I haven't found a way to do it yet).