Commit 58ead554 authored by Trevor Cappallo's avatar Trevor Cappallo
Browse files

add stdout-cloning subprocess wrapper

parent 235e6271
......@@ -28,6 +28,20 @@ def __exit_handler(logger, addresses, critical_addresses):
logger.email_log(addresses)
#class MultiLineWrapper(logging.StreamHandler):
# def __init__(self, stream_handler):
# super(logging.StreamHandler, self).__init__(stream_handler)
# self.stream_handler = stream_handler
#
# def emit(self, record):
# print "-------", record
# super(MultiLineWrapper, self).emit(record)
#for line in record.split('\n'):
# self.stream_handler.emit(line)
# def flush(self):
# self.stream_handler.flush()
class OperationalLogger:
"""Main class for Operational Logging."""
......@@ -41,7 +55,7 @@ class OperationalLogger:
self.__error_buffer = StringIO.StringIO()
self.__critical_buffer = StringIO.StringIO()
if log_format is None:
log_format = '[%(asctime)s][%(levelname)5s][p%(process)d][%(filename)s:%(lineno)d]:%(message)s'
log_format = '[%(asctime)s][%(levelname)5s][p%(process)d][%(filename)s:%(lineno)d] %(message)s'
self.__log_format = log_format
if date_format is None:
date_format = '%Y/%m/%d %H:%M:%S'
......@@ -72,7 +86,7 @@ class OperationalLogger:
console = logging.StreamHandler(sys.stdout)
console.setLevel(console_level)
console.setFormatter(logging.Formatter(
fmt='[%(asctime)s][%(levelname)5s][%(filename)s:%(lineno)d]:%(message)s',
fmt='[%(asctime)s][%(levelname)5s][%(filename)s:%(lineno)d] %(message)s',
datefmt='%m/%d %H:%M:%S'
))
logging.getLogger(logger_name).addHandler(console)
......@@ -199,6 +213,25 @@ def logged_subprocess(arg_list):
logging.warning('Failure on {}'.format(' '.join(arg_list)))
return -1
def logged_sub(arg_list, logging_level=logging.INFO, **kwargs):
"""Pass arg_list to a subprocess call and log all output."""
# TODO: respect logging_level
logging.info('Child process of [p{}]'.format(os.getppid()))
logging.info('Attempting {}'.format(' '.join(arg_list)))
try:
results = ''
proc = subprocess.Popen(arg_list, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, **kwargs)
for line in iter(proc.stdout.readline, b''):
print " ::", line.rstrip()
results += line
except Exception as err:
logging.error('Unknown exception resulting from {}:{}'.format(' '.join(arg_list), str(err)))
else:
logging.info('Successfully completed {}'.format(' '.join(arg_list)))
long_info(results)
return 0
logging.warning('Failure on {}'.format(' '.join(arg_list)))
return -1
def stack_trace(logging_level=logging.ERROR):
"""Log a stack trace at the given level."""
......@@ -208,8 +241,9 @@ def stack_trace(logging_level=logging.ERROR):
if __name__ == '__main__':
default_logging(addresses=['tcappallo@veriskclimate.com'], from_address='tcappallo@veriskclimate.com')
#default_logging(addresses=['tcappallo@veriskclimate.com'], from_address='tcappallo@veriskclimate.com')
#default_logging(addresses=['msze@veriskclimate.com', 'msze@aer.com'], from_address='tcappallo@veriskclimate.com')
default_logging()
test = """Blah
foo
bar
......@@ -220,8 +254,11 @@ if __name__ == '__main__':
logging.debug('Fin')
logging.error('An error in testing, oh, no!!')
logging.critical('Put up the Jimsignal!')
long_error(test)
#long_error(test)
logging.error(test)
c = ['find', '.', '-name', '*.py']
logged_subprocess(c)
logged_sub(c)
try:
raise Exception("I AM ERROR.")
except Exception as err:
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment