I have a custom formatter in my python Flask application, which I've added to the root logger:
logger = logging.getLogger()
logger.setLevel(logging.INFO)
handler = logging.StreamHandler()
handler.setLevel(logging.INFO)
formatter = CustomLoggingFormatter()
handler.setFormatter(formatter)
logger.addHandler(handler)
This works perfectly fine when I want to log something (logger.info()...), but I have an issue with the logs from libraries, e.g. uwsgi.
Here is an example of a log-message:
{"@timestamp": "2017-09-25T06:57:45.373Z", "level": "INFO", "message": " * Running on %s://%s:%d/ %s"}
I thought perhaps something was wrong with my formatter, but when I log the LogRecord which my CustomLoggingFormatter receivs, it looks like this for the line above:
LogRecord: werkzeug, 20, <...>/lib/python3.5/site-packages/werkzeug/_internal.py, 87, " * Running on %s://%s:%d/ %s"
Here is my CustomLoggingFormatter:
class CustomLoggingFormatter(Formatter):
data = {}
def __init__(self):
super(CustomLoggingFormatter, self).__init__()
def format(self, record):
print(record)
input_data = {}
input_data['@timestamp'] = datetime.utcnow().isoformat()[:-3] + 'Z'
input_data['level'] = record.levelname
if record.msg:
input_data['message'] = record.msg
input_data.update(self.data)
return json.dumps(input_data)
For my formatter to work, it seems the string formatting must be resolved first, but for several libraries that doesn't happen. Anyone who knows how to fix this issue?
Formatter.format()
always has to handle aLogRecord
instance; the default implementation callsFormatter.formatMessage()
to handle the actual formatting (which typically usesvars(record)
as a dictionary).