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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
|
#!/usr/bin/env python3
# This file is part of GNU TALER.
# Copyright (C) 2018 INRIA
#
# TALER is free software; you can redistribute it and/or modify it under the
# terms of the GNU Lesser General Public License as published by the Free Software
# Foundation; either version 2.1, or (at your option) any later version.
#
# TALER is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
# A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License along with
# GNU TALER; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
#
# @author Florian Dold
"""
Wrapper for programs that log to stderr. Redirects logs to a file specified by
a path with strfmt-style placeholders in it.
"""
from subprocess import Popen, PIPE
import sys
import os
import os.path
import signal
import time
def handler(signum, frame):
if p:
os.kill(p.pid, signum)
else:
sys.exit(-1)
def touchp(path):
dir = os.path.dirname(path)
if dir:
os.makedirs(dir, exist_ok=True)
if len(sys.argv) < 3:
print("Usage: {} logfile prog_and_args...".format(sys.argv[0]), file=sys.stderr)
sys.exit(-1)
p = None
catchable_sigs = set(signal.Signals) - {signal.SIGKILL, signal.SIGSTOP}
for sig in catchable_sigs:
signal.signal(sig, handler)
p = Popen(sys.argv[2:], stderr=PIPE, shell=False)
log = sys.argv[1]
last_name = None
while p.poll() is None:
full_name = time.strftime(log)
if full_name != last_name:
touchp(full_name)
last_name = full_name
last_read = p.stderr.readline()
if last_read == '':
break
with open(full_name, "ab") as f:
f.write(last_read)
status = p.wait()
sys.exit(status)
|