Is there a way to group logs of a python web application which belong to one web request?
Example:
2015-02-11 13:06:32 myapp.middleware.MYAPPMiddleware: INFO Login of user foo was successful
2015-02-11 13:06:32 myapp.middleware.MYAPPMiddleware: INFO Login of user bar failed
2015-02-11 13:06:32 myapp.send_mails: INFO failed to send mail to someone@example.com
The above log lines are unrelated to each other.
How can you solve this the pythonic way?
Log entries in their essence are designed to be independent from each other.
The correct way to connect them together is to include some contextual information into the entries to filter by when looking through the logs later.
Here's a example of a Sharepoint log record with such information:
In Python
logging
docs, Adding contextual information to your logging output recommends either of two methods: using aLoggerAdapter
or aFilter
.LoggerAdapter
is used like this (examples are based on those in the docs):Filter
is used like this:As you can see, the difference is
LoggerAdapter
is non-transparent whileFilter
is transparent. In the examples, the former modifies the message text while the latter sets custom attributes (and actually writing them requires cooperation of theFormatter
used) but in fact, both can do both.So, the former is more useful if you only need to add the context to some messages while the latter is more fit to augment all, or a large portion of, the messages being logged.
You can assign random UUID to each request in init method, and add it to all log messages.
For example, in Tornado:
As result, you will be able to grep log by this UUID to find all messages which belong to separate request.