Skip to content

Instantly share code, notes, and snippets.

@8bitbuddhist
Created February 6, 2019 16:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 8bitbuddhist/8faf8ed6bbea8b90551ab9f38814b488 to your computer and use it in GitHub Desktop.
Save 8bitbuddhist/8faf8ed6bbea8b90551ab9f38814b488 to your computer and use it in GitHub Desktop.
Synthetic transaction monitoring demonstrating using WSGI
import gettext
import logging.handlers
from logging.handlers import SysLogHandler
import socket
class ContextFilter(logging.Filter):
hostname = socket.gethostname()
def filter(self, record):
record.hostname = ContextFilter.hostname
return True
# Initialize logging components
syslogHandler = SysLogHandler(address=('logsX.papertrailapp.com', XXXXX))
syslogHandler.addFilter(ContextFilter())
syslogFormat = '%(asctime)s %(hostname)s wsgi.py: [%(levelname)s] (%(funcName)s) %(message)s'
formatter = logging.Formatter(syslogFormat, datefmt='%b %d %H:%M:%S')
syslogHandler.setFormatter(formatter)
logger = logging.getLogger()
logger.addHandler(syslogHandler)
logger.setLevel(logging.DEBUG)
logger.debug('Starting WSGI app')
def application(environ, start_response):
logger.debug('Handling request. Environment vars: %s', environ)
# If the locale is not present in the URL, redirect the user
locale = environ['PATH_INFO'][1:3]
if not locale:
newlocale = environ['HTTP_ACCEPT_LANGUAGE'][0:2]
logger.info('Switching to locale: %s', newlocale)
start_response('302 Found',
[('Location', 'http://localhost:8000/' + newlocale)])
return [b'1']
logger.info('Locale: %s', locale)
try:
translation = gettext.translation('app', localedir='locale', languages=[locale])
translation.install()
output = _('Hello world!')
status = '200 OK'
logger.info('Got localization string: %s', output)
response_headers = [('Content-type', 'text/plain'), ('Content-Length', str(len(output)))]
start_response(status, response_headers)
return [bytes(output, 'utf-8')]
except OSError as e:
logger.exception('Localization error')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment