Simple library to emit json formatted logs to stdout
Project description
The other day I was running some containers on Amazon’s ECS and logging to cloudwatch. I then learnt cloudwatch parses JSON logs so obviously I then wanted Sanic to log out JSON.
Ideally this’ll be useful to people but if it isn’t, raise an issue and we’ll make it better :)
To install:
pip install sanic-json-logging
Look at examples/simple.py for a full working example, but this will essentially get you going
from sanic_json_logging import setup_json_logging, NoAccessLogSanic
app = NoAccessLogSanic('app1')
setup_json_logging(app)
The reason NoAccessLogSanic is used instead of Sanic is to disable the default access logger (it also disabled the LOGO).
setup_json_logging does the following:
changes the default log formatters to JSON ones
also filters out no Keepalive warnings
unless told otherwise, will change the asyncio task factory, to implement some rudimentary task-local storage.
installs pre and post request middleware. Pre-request middleware to time tasks and generate a uuid4 request id. Post-request middleware to emit access logs.
will use AWS X-Forwarded-For IPs in the access logs if present
If setup_json_logging changed the task factory, all tasks created from the request’s task will contain the request ID.
Currently I have it outputting access logs like
{
"timestamp": "2018-06-09T17:42:52.195701Z",
"level": "INFO",
"method": "GET",
"path": "/endpoint1",
"remote": "127.0.0.1:33468",
"user_agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.62 Safari/537.36",
"host": "localhost:8000",
"response_time": 0.0,
"req_id": "795617c7-b514-4ed9-bb63-cc4fcd883c3d",
"logger": "sanic.access",
"status_code": 200,
"length": 0,
"type": "access"
}
And if you log to the root logger, inside a request, it’ll look like this.
{
"timestamp": "2018-06-09T17:42:52.195326Z",
"level": "INFO",
"message": "some informational message",
"type": "log",
"logger": "root",
"filename": "simple.py",
"lineno": 16,
"req_id": "795617c7-b514-4ed9-bb63-cc4fcd883c3d"
}
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Hashes for sanic_json_logging-0.3.1-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 9243a80012d77abca0396c17b128a8e936b5290723959db681401787dd71c228 |
|
MD5 | c4b80ea20bd1a5a5dcc08871dddfb609 |
|
BLAKE2b-256 | 9183098c4e150bc92808a53c556c4c98985bc4391a58a910077d4814ce67e0a7 |