tttoaster commited on
Commit
c1c47cb
1 Parent(s): d04ff26

Upload utils.py

Browse files
Files changed (1) hide show
  1. utils.py +83 -0
utils.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import datetime
2
+ import logging
3
+ import logging.handlers
4
+ import os
5
+ import sys
6
+
7
+ handler = None
8
+
9
+
10
+ def build_logger(logger_name, logger_dir):
11
+ global handler
12
+
13
+ formatter = logging.Formatter(
14
+ fmt="%(asctime)s | %(levelname)s | %(name)s | %(message)s",
15
+ datefmt="%Y-%m-%d %H:%M:%S",
16
+ )
17
+
18
+ # Set the format of root handlers
19
+ if not logging.getLogger().handlers:
20
+ logging.basicConfig(level=logging.INFO)
21
+ logging.getLogger().handlers[0].setFormatter(formatter)
22
+
23
+ # Redirect stdout and stderr to loggers
24
+ stdout_logger = logging.getLogger("stdout")
25
+ stdout_logger.setLevel(logging.INFO)
26
+ sl = StreamToLogger(stdout_logger, logging.INFO)
27
+ sys.stdout = sl
28
+
29
+ stderr_logger = logging.getLogger("stderr")
30
+ stderr_logger.setLevel(logging.ERROR)
31
+ sl = StreamToLogger(stderr_logger, logging.ERROR)
32
+ sys.stderr = sl
33
+
34
+ # Get logger
35
+ logger = logging.getLogger(logger_name)
36
+ logger.setLevel(logging.INFO)
37
+
38
+ # Add a file handler for all loggers
39
+ if handler is None:
40
+ os.makedirs(logger_dir, exist_ok=True)
41
+ filename = os.path.join(logger_dir, logger_name + '.log')
42
+ handler = logging.handlers.TimedRotatingFileHandler(filename, when='D', utc=True)
43
+ handler.setFormatter(formatter)
44
+
45
+ for name, item in logging.root.manager.loggerDict.items():
46
+ if isinstance(item, logging.Logger):
47
+ item.addHandler(handler)
48
+
49
+ return logger
50
+
51
+
52
+ class StreamToLogger(object):
53
+ """
54
+ Fake file-like stream object that redirects writes to a logger instance.
55
+ """
56
+
57
+ def __init__(self, logger, log_level=logging.INFO):
58
+ self.terminal = sys.stdout
59
+ self.logger = logger
60
+ self.log_level = log_level
61
+ self.linebuf = ''
62
+
63
+ def __getattr__(self, attr):
64
+ return getattr(self.terminal, attr)
65
+
66
+ def write(self, buf):
67
+ temp_linebuf = self.linebuf + buf
68
+ self.linebuf = ''
69
+ for line in temp_linebuf.splitlines(True):
70
+ # From the io.TextIOWrapper docs:
71
+ # On output, if newline is None, any '\n' characters written
72
+ # are translated to the system default line separator.
73
+ # By default sys.stdout.write() expects '\n' newlines and then
74
+ # translates them so this is still cross platform.
75
+ if line[-1] == '\n':
76
+ self.logger.log(self.log_level, line.rstrip())
77
+ else:
78
+ self.linebuf += line
79
+
80
+ def flush(self):
81
+ if self.linebuf != '':
82
+ self.logger.log(self.log_level, self.linebuf.rstrip())
83
+ self.linebuf = ''