1
2import sys
3import os
4import logging
5
6
7def setup_custom_logger(name, log_path = None):
8    # first make sure path availabe
9#   if log_path is None:
10#       log_path = os.getcwd()+'/trex_log.log'
11#   else:
12#       directory = os.path.dirname(log_path)
13#       if not os.path.exists(directory):
14#           os.makedirs(directory)
15    logging.basicConfig(level   = logging.INFO,
16                        format  = '%(asctime)s %(name)-10s %(module)-20s %(levelname)-8s %(message)s',
17                        datefmt = '%m-%d %H:%M')
18#                       filename= log_path,
19#                       filemode= 'w')
20#
21#   # define a Handler which writes INFO messages or higher to the sys.stderr
22#   consoleLogger = logging.StreamHandler()
23#   consoleLogger.setLevel(logging.ERROR)
24#   # set a format which is simpler for console use
25#   formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
26#   # tell the handler to use this format
27#   consoleLogger.setFormatter(formatter)
28#
29#   # add the handler to the logger
30#   logging.getLogger(name).addHandler(consoleLogger)
31
32def setup_daemon_logger (name, log_path = None):
33    # first make sure path availabe
34    logging.basicConfig(level   = logging.INFO,
35                        format  = '%(asctime)s %(name)-10s %(module)-20s %(levelname)-8s %(message)s',
36                        datefmt = '%m-%d %H:%M',
37                        filename= log_path,
38                    filemode= 'w')
39
40class CustomLogger(object):
41
42    def __init__(self, log_filename):
43        # Store the original stdout and stderr
44        sys.stdout.flush()
45        sys.stderr.flush()
46
47        self.stdout_fd = os.dup(sys.stdout.fileno())
48        self.devnull = os.open('/dev/null', os.O_WRONLY)
49        self.log_file = open(log_filename, 'w')
50        self.silenced = False
51        self.pending_log_file_prints = 0
52
53    # silence all prints from stdout
54    def silence(self):
55        os.dup2(self.devnull, sys.stdout.fileno())
56        self.silenced = True
57
58    # restore stdout status
59    def restore(self):
60        sys.stdout.flush()
61        sys.stderr.flush()
62        # Restore normal stdout
63        os.dup2(self.stdout_fd, sys.stdout.fileno())
64        self.silenced = False
65
66    #print a message to the log (both stdout / log file)
67    def log(self, text, force = False, newline = True):
68        self.log_file.write((text + "\n") if newline else text)
69        self.pending_log_file_prints += 1
70
71        if (self.pending_log_file_prints >= 10):
72             self.log_file.flush()
73             self.pending_log_file_prints = 0
74
75        self.console(text, force, newline)
76
77    # print a message to the console alone
78    def console(self, text, force = False, newline = True):
79        _text = (text + "\n") if newline else text
80        # if we are silenced and not forced - go home
81        if self.silenced and not force:
82            return
83
84        if self.silenced:
85            os.write(self.stdout_fd, _text)
86        else:
87            sys.stdout.write(_text)
88
89        sys.stdout.flush()
90
91    # flush
92    def flush(self):
93        sys.stdout.flush()
94        self.log_file.flush()
95
96    def __exit__(self, type, value, traceback):
97        sys.stdout.flush()
98        self.log_file.flush()
99        os.close(self.devnull)
100        os.close(self.log_file)
101