Last active
December 18, 2015 22:59
-
-
Save tobiasmcnulty/5858829 to your computer and use it in GitHub Desktop.
Sample Django logging configuration for adding static contextual fields to logging records to be sent to Graylog2 via graypy.GELFHandler. Also included is a filter to remove the Django request object from logging records, which may not be picklable or you may not always want to send to Graylog2 (since it can contain sensitive information).
This file contains hidden or 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 logging | |
| class QuotelessStr(str): | |
| """ | |
| Return the repr() of this string *without* quotes. This is a | |
| temporary fix until https://github.com/severb/graypy/pull/34 is resolved. | |
| """ | |
| def __repr__(self): | |
| return self | |
| class StaticFieldFilter(logging.Filter): | |
| """ | |
| Python logging filter that adds the given static contextual information | |
| in the ``fields`` dictionary to all logging records. | |
| """ | |
| def __init__(self, fields): | |
| self.static_fields = fields | |
| def filter(self, record): | |
| for k, v in self.static_fields.items(): | |
| setattr(record, k, QuotelessStr(v)) | |
| return True | |
| class RequestFilter(logging.Filter): | |
| """ | |
| Python logging filter that removes the (non-pickable) Django ``request`` | |
| object from the logging record. | |
| """ | |
| def filter(self, record): | |
| if hasattr(record, 'request'): | |
| del record.request | |
| return True |
This file contains hidden or 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
| LOGGING = { | |
| # ... | |
| 'filters': { | |
| 'require_debug_false': { | |
| '()': 'django.utils.log.RequireDebugFalse', | |
| }, | |
| 'static_fields': { | |
| '()': 'projectname.core.logfilters.StaticFieldFilter', | |
| 'fields': {'deployment': 'projectname', 'environment': 'staging'}, | |
| }, | |
| 'django_exc': { | |
| '()': 'projectname.core.logfilters.RequestFilter', | |
| }, | |
| # ... | |
| }, | |
| 'handlers': { | |
| 'mail_admins': { | |
| 'level': 'ERROR', | |
| 'class': 'django.utils.log.AdminEmailHandler', | |
| 'include_html': False, | |
| 'filters': ['require_debug_false'], | |
| }, | |
| 'sam_gelf': { | |
| 'class': 'graypy.GELFHandler', | |
| 'host': 'graylog2.example.com', | |
| 'port': 12201, | |
| 'filters': ['static_fields', 'django_exc'], | |
| }, | |
| # ... | |
| }, | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment