-
Notifications
You must be signed in to change notification settings - Fork 50
/
Copy pathlogger.py
73 lines (59 loc) · 2.28 KB
/
logger.py
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
67
68
69
70
71
72
73
import logging
import os
from pathlib import Path
import sys
import time
class Logger(object):
# Borrowed from: https://stackoverflow.com/questions/14906764/how-to-redirect-stdout-to-both-file-and-console-with-scripting
def __init__(self, log_address=''):
self.terminal = sys.stdout
self.log = open(log_address, "a")
def write(self, message):
self.terminal.write(message)
self.log.write(message)
def flush(self):
# this flush method is needed for python 3 compatibility.
# this handles the flush command by doing nothing.
# you might want to specify some extra behavior here.
pass
class StreamToLogger(object):
"""
Fake file-like stream object that redirects writes to a logger instance.
modified from: https://www.electricmonk.nl/log/2011/08/14/redirect-stdout-and-stderr-to-a-logger-in-python/
"""
def __init__(self, logger, log_level=logging.DEBUG):
self.logger = logger
self.log_level = log_level
self.linebuf = ''
def write(self, buf):
for line in buf.rstrip().splitlines():
self.logger.log(self.log_level, line.rstrip())
def flush(self):
pass
def set_log_file(log_file_name, short_mode=False):
if not os.path.isdir(Path(log_file_name).parent):
os.makedirs(Path(log_file_name).parent)
if short_mode:
logging.basicConfig(
format='[%(message)s',
level=logging.DEBUG,
handlers=[
logging.FileHandler(log_file_name),
logging.StreamHandler()
])
else:
logging.basicConfig(
format='[%(threadName)-12.12s] %(message)s',
level=logging.DEBUG,
handlers=[
logging.FileHandler(log_file_name),
logging.StreamHandler()
])
stdout_logger = logging.getLogger('STDOUT')
sl = StreamToLogger(stdout_logger, logging.DEBUG)
sys.stdout = sl
stderr_logger = logging.getLogger('STDERR')
sl = StreamToLogger(stderr_logger, logging.DEBUG)
sys.stderr = sl
logging.debug('---------------------------------{}--------------------------------'.format(time.ctime()))
logging.debug('----------------------------------start experiment------------------------------')