-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathlog_init.py
More file actions
33 lines (24 loc) · 901 Bytes
/
log_init.py
File metadata and controls
33 lines (24 loc) · 901 Bytes
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
""" Initialize log file for logging stdout and stderr to a file """
import sys
def log_init(log_file):
"""Redirect stdout and stderr to a log file."""
class Logger:
"""Class for logging."""
def __init__(self, filename):
self.log = open(filename, "a", encoding="utf-8") # pylint: disable=consider-using-with
self.terminal = sys.stdout
def write(self, message):
"""Write message to terminal and log file."""
self.terminal.write(message)
if self.log:
self.log.write(message)
def flush(self):
"""Flush terminal and log file."""
self.terminal.flush()
if self.log:
self.log.flush()
def __del__(self):
if self.log:
self.log.close()
sys.stdout = Logger(log_file)
sys.stderr = sys.stdout