INSTALLED_APPS = [
...
"structured_log",
...
]
Add filter, formater and handler. Use handler for logging.
"filters": {
"request_info": {
"()": "structured_log.filters.RequestInfoFilter"
}
},
"formatters": {
"cloudrun": {
"()": "structured_log.formaters.GoogleCloudFormatter"
},
},
"handlers": {
"console": {
"level": "DEBUG",
"class": "logging.StreamHandler",
"stream": sys.stdout,
"formatter": "cloudrun",
"filters": ["request_info"],
},
},
"loggers": {
"": {
"level": "INFO",
"handlers": ["console"],
"propagate": False
},
"django": {
"level": "INFO",
"handlers": ["console"],
"propagate": False
},
...
}
You can use another log formater for your local environment:
from .settings import DEBUG
if DEBUG:
log_formatter = "color_console"
else:
log_formatter = "cloudrun"
"handlers": {
"console": {
"level": "DEBUG",
"class": "logging.StreamHandler",
"stream": sys.stdout,
"formatter": log_formatter,
"filters": ["request_info"],
},
},
Replace get_wsgi_application import in wsgi.py.
import os
from structured_log import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings")
application = WSGIHandler()
Use django-xff
to set HTTP_REMOTE_ADDR from X-Forwarded-For header.
MIDDLEWARE = [
"xff.middleware.XForwardedForMiddleware",
...
]
# Only one proxy for Cloud Run
XFF_TRUSTED_PROXY_DEPTH = 1