Skip to content

Instantly share code, notes, and snippets.

@gyli
Created April 3, 2019 06:27
Show Gist options
  • Save gyli/2be260876185250de9818c78f94abddc to your computer and use it in GitHub Desktop.
Save gyli/2be260876185250de9818c78f94abddc to your computer and use it in GitHub Desktop.
Send log to Papertrail with Python logging dictconfig
# Code is modified from Papertrail's official examples:
# https://help.papertrailapp.com/kb/configuration/configuring-centralized-logging-from-python-apps/#examples
import logging
import logging.config
import os
import socket
class ContextFilter(logging.Filter):
"""
Fetching hostname
"""
hostname = socket.gethostname()
def filter(self, record):
record.hostname = ContextFilter.hostname
return True
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_hostname': {
'()': ContextFilter,
},
},
'formatters': {
'simple': {
'format': '%(asctime)s %(hostname)s YOUR_APP: [%(levelname)s] %(message)s',
'datefmt': '%b %d %H:%M:%S',
},
},
'handlers': {
'SysLog': {
'level': 'INFO',
'class': 'logging.handlers.SysLogHandler',
'formatter': 'simple',
'address': ('logsN.papertrailapp.com', 30000),
'filters': ['require_hostname']
}
},
'loggers': {
'papertrail_logger': {
'handlers': ['SysLog'],
'level': 'INFO',
'propagate': True,
}
}
}
logging.config.dictConfig(LOGGING)
def get_logger_by_name(name: str = 'papertrail_logger'):
return logging.getLogger(name)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment