Guest User

Untitled

a guest
Jun 24th, 2018
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.87 KB | None | 0 0
  1. #!/usr/bin/env python3
  2.  
  3. import logging
  4. import subprocess
  5. import tempfile
  6. import sys
  7.  
  8. # Set-up logging to both console and a file log.
  9. logger = logging.getLogger()
  10. logger.handlers = []
  11. logger.setLevel(logging.DEBUG)
  12.  
  13. # Console logging will be only INFO or higher
  14. # This could be configured for CLI invocations
  15. console_handler = logging.StreamHandler()
  16. console_handler.setLevel(logging.INFO)
  17. console_handler.setFormatter(
  18. logging.Formatter('%(asctime)s %(levelname)-8s %(message)s')
  19. )
  20. logger.addHandler(console_handler)
  21.  
  22. # Adds log file handler. Everything DEBUG or higher is logged here
  23. # You could potentially have 1 log per benchpress invocation
  24. file_handler = logging.FileHandler(filename='benchpress.log')
  25. file_handler.setLevel(logging.DEBUG)
  26. file_handler.setFormatter(
  27. logging.Formatter(('%(asctime)s '
  28. '%(filename)s:%(lineno)d %(levelname)-8s %(message)s'))
  29. )
  30. logger.addHandler(file_handler)
  31.  
  32. # If you want to keep per-command log files, instead
  33. # of using temp files, you could give them a proper name and path.
  34. with tempfile.TemporaryFile() as temp_stdout, \
  35. tempfile.TemporaryFile() as temp_stderr:
  36.  
  37. cmd = sys.argv[1:] # bad practice, only use for cmd
  38. process = subprocess.Popen(cmd,
  39. stdin=subprocess.PIPE,
  40. stdout=temp_stdout,
  41. stderr=temp_stderr)
  42. process.wait()
  43.  
  44. temp_stdout.seek(0)
  45. stdout = temp_stdout.read().decode('utf8', 'ignore')
  46.  
  47. temp_stderr.seek(0)
  48. stderr = temp_stderr.read().decode('utf8', 'ignore')
  49.  
  50. status_code = process.returncode
  51.  
  52. output = '\nstdout:\n{}\nstderr:\n{}\nstatus_code: {}'
  53.  
  54. # Imaging this is the parser call
  55. msg = output.format(stdout, stderr, status_code)
  56.  
  57. # Here we log to log file only
  58. logging.debug(msg)
  59.  
  60. # Here we log to console and log file
  61. logging.info('cmd: {}\n'.format(cmd) + msg)
Add Comment
Please, Sign In to add comment