Skip to content

Instantly share code, notes, and snippets.

@gamesbook
Created September 6, 2017 13:07
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 gamesbook/0f5028f4eb0269f9a8530448da43f2ba to your computer and use it in GitHub Desktop.
Save gamesbook/0f5028f4eb0269f9a8530448da43f2ba to your computer and use it in GitHub Desktop.
Capture shell script output via Python logging to Sentry.io
# -*- coding: utf-8 -*-
"""Purpose: Capture shell script output via Python logging to Sentry.io.
Setup:
First export the SENTRY_DSN value in your .bashrc file. Then::
pip install raven --upgrade
pip install autoenv
echo "source bin/activate" > .env
Usage:
Run as an example::
python log_capture.py ls -al *.py
python log_capture.py ./test.sh first last
"""
from __future__ import print_function
# lib
import logging
import os
import subprocess
import shlex
import sys
# third
from raven import Client
from raven.conf import setup_logging
from raven.handlers.logging import SentryHandler
log = logging.getLogger(__name__)
logging.basicConfig(level=logging.DEBUG)
# sentry
dsn = os.getenv('SENTRY_DSN', None)
if dsn:
client = Client(dsn=dsn)
handler = SentryHandler(client, level=logging.WARN)
setup_logging(handler)
else:
log.warn({'msg': 'Unable to locate value for SENTRY_DSN'})
def run_shell_command(command_line):
"""Run a shell command and log the output."""
log.info({'msg': 'Subprocess "%s" Start' % command_line})
try:
command_line_process = subprocess.Popen(
shlex.split(command_line),
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
)
process_output, _ = command_line_process.communicate()
po = process_output.split('\n')
for p in po:
log.debug({'msg': p})
except (OSError, subprocess.CalledProcessError) as exception:
log.error({'error': 'Subprocess Exception:%s' % exception})
return False
except Exception as exception:
log.error({'error': 'Uncaught Exception:%s' % exception})
return False
else:
# no exception was raised
log.info({'msg': 'Subprocess "%s" End' % command_line})
#log.warn({'msg': 'Sentry test complete'}) # triggers sentry - TEST only!
return True
def main():
"""Create a shell command from params passed to program."""
_command = ' '.join(sys.argv[1:])
run_shell_command(_command)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment