summaryrefslogtreecommitdiff
path: root/gerritbot/minilog.py
blob: 2b1771b490f12d0612dbcfa4a503a01085d53589 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#!/usr/bin/env python
#
# This file is part of the LibreOffice project.
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.

import logging
import threading
import subprocess

class LogThread(threading.Thread):
    def __init__(self, logger, level, extra, stream):
        threading.Thread.__init__(self)
        self.logger = logger
        self.level = level
        self.extra = extra
        self.stream = stream
        self.daemon = False
    def run(self):
        while True:
            outline = self.stream.readline()
            if len(outline) == 0:
                break;
            self.logger.log(self.level, outline[:-1], extra=self.extra)
        
def logged_call(args, logger, extra):
    p = subprocess.Popen(args=args, bufsize=1, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    outthread = LogThread(logger, logging.INFO, extra, p.stdout)
    errthread = LogThread(logger, logging.WARNING, extra, p.stderr)
    outthread.start()
    errthread.start()    
    p.wait()
    outthread.join()
    errthread.join()
    if p.returncode == 0:
        logger.info('call to "%s" succeeded.' % ' '.join(args), extra=extra)
    else:
        logger.error('call to "%s" returned: %d' % (' '.join(args), p.returncode), extra=extra)
        raise Exception('"%s" command returned non-null.' % ' '.join(args))