Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Add A Logging Handler to Django for sendxmpp
# mysite/mysite/django_sendxmpp_handler.py
from logging import Handler
from os import popen
from django.conf import settings
LOGGING_XMPP_CONFIG = settings.LOGGING_XMPP_CONFIG
class SENDXMPPHandler(Handler):
def emit(self, record):
try:
message = self.format(record)
shell_command = "echo '{}' | {} -u {} -j {} -p {} {} --tls-ca-path='/etc/ssl/certs'".format(
message,
LOGGING_XMPP_CONFIG['LOGGING_XMPP_COMMAND'],
LOGGING_XMPP_CONFIG['LOGGING_XMPP_SENDER'],
LOGGING_XMPP_CONFIG['LOGGING_XMPP_SERVER'],
LOGGING_XMPP_CONFIG['LOGGING_XMPP_PASSWORD'],
LOGGING_XMPP_CONFIG['LOGGING_XMPP_RECIPIENT']
)
if LOGGING_XMPP_CONFIG['LOGGING_XMPP_USE_TLS'] == '1':
shell_command += ' -t'
p = popen(shell_command, "w")
status = p.close()
if status:
print("sendxmpp_handler exit status", status)
except Exception:
self.handleError(record)
# mysite/mysite/logging_settings.py
from copy import deepcopy
from django.utils.log import DEFAULT_LOGGING
def init_logging_settings():
logging_dict = deepcopy(DEFAULT_LOGGING)
logging_dict['handlers']['send_xmpp'] = {
"level": "ERROR",
"class": "mysite.sendxmpp_handler.SENDXMPPHandler"
}
logging_dict['loggers']['django']['handlers'].append("send_xmpp")
return logging_dict
# mysite/mysite/settings.py
from .logging_settings import init_logging_settings
import os
from dotenv import load_dotenv
load_dotenv()
LOGGING_XMPP_CONFIG = {
'LOGGING_XMPP_SERVER': str(os.getenv('LOGGING_XMPP_SERVER')),
'LOGGING_XMPP_SENDER': str(os.getenv('LOGGING_XMPP_SENDER')),
'LOGGING_XMPP_PASSWORD': str(os.getenv('LOGGING_XMPP_PASSWORD')),
'LOGGING_XMPP_RECIPIENT': str(os.getenv('LOGGING_XMPP_RECIPIENT')),
# '/usr/bin/site_perl/sendxmpp' or maybe '/usr/bin/sendxmpp'
'LOGGING_XMPP_COMMAND': str(os.getenv('LOGGING_XMPP_COMMAND')),
'LOGGING_XMPP_USE_TLS': str(os.getenv('LOGGING_XMPP_USE_TLS'))
}
LOGGING = init_logging_settings()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment