Last active
October 22, 2020 04:38
-
-
Save femmerling/0c4bf626ff8deff42f6a4b52fdb8b7d2 to your computer and use it in GitHub Desktop.
This is my workaround for Sanic customized logging information on Gunicorn. I use Gunicorn with Sanic Gunicorn Worker. For this to work you need to add the --capture-output flag in the Gunicorn startup script and setting Sanic's default logging off..
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import time | |
from sanic import Sanic | |
# `configure_logging=False` will stop Sanic's default logging. You'll use print() for printing to stdout | |
app = Sanic(name="MyApp", configure_logging=False) | |
@app.middleware('request') | |
async def embed_start_time(request): | |
request.ctx.start_time = time.time() # Use requst context `request.ctx` to embed extra information | |
@app.middleware('response') | |
async def log_request(request, response): | |
spend_time = round((time.time() - request.ctx.start_time) * 1000) | |
print("[{}] [ACCESS] LEN:{}b\tLAT:{}ms IP:{} STATUS:{} {}\t{} {}".format( | |
datetime.now().strftime("%Y-%m-%d %H:%M:%S"), | |
len(response.body), | |
spend_time, | |
request.headers.get('remote_addr'), | |
response.status, | |
request.method, | |
request.path, | |
request.query_string)) # you can basically embed any information you wish here |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment