]> git.ipfire.org Git - nitsi.git/blob - src/nitsi/logger.py
Support also a file as base for the log file dir
[nitsi.git] / src / nitsi / logger.py
1 #!/usr/bin/python3
2
3 import logging
4 import os
5 import time
6
7 logger = logging.getLogger("nitsi.logger")
8
9 class Logger_Exeception(BaseException):
10 pass
11
12 # This function should create the necessary folders
13 # and touch the logging files
14 def init_logging(path):
15 logger.debug("Init logging directory")
16
17 try:
18 path = os.path.abspath(path)
19 except BaseException as e:
20 logger.error("Failed to get the absolute path for: {}".format(path))
21
22 if os.path.isdir(path):
23 log_dir = "{}/log".format(path)
24 elif os.path.isfile(path):
25 log_dir = "{}/{}.log".format(os.path.dirname(path), os.path.basename(path))
26
27
28 if not os.path.exists(log_dir):
29 os.mkdir(log_dir)
30
31 time_dir = log_dir + "/" + time.strftime("%Y-%m-%d_%H-%M-%S" ,time.gmtime(time.time()))
32
33 if os.path.exists(time_dir):
34 logger.error("Path {} alreday exist".format(time_dir))
35 raise Logger_Exeception
36 else:
37 os.mkdir(time_dir)
38
39 return time_dir
40
41
42 class TestFormatter(logging.Formatter):
43 def __init__(self, start_time=None, name=None, longest_machine_name=10):
44 super().__init__(fmt="[%(asctime)s] %(message)s")
45 logger.debug("Initiating TestFormatter for")
46 if start_time == None:
47 self.starttime = time.time()
48 else:
49 self.starttime = start_time
50
51 if name == None:
52 self.name = ""
53 else:
54 self.name = name
55
56 self.longest_machine_name = longest_machine_name
57
58 def converter(self, recordtime):
59
60 # This returns a timestamp relatively to the time when we started
61 # the test.
62
63 recordtime -= self.starttime
64
65 return time.gmtime(recordtime)
66
67 def format(self, record):
68 return "[{}][{:^{align}}] {}".format(self.formatTime(record),
69 self.name,
70 record.getMessage(),
71 align=self.longest_machine_name)
72
73 def formatTime(self, record, datefmt=None):
74 ct = self.converter(record.created)
75 t = time.strftime("%H:%M:%S", ct)
76 s = "{}.{:03d}".format(t, round(record.msecs,None))
77 return s
78
79
80 class Log_Formatter(logging.Formatter):
81 def __init__(self):
82 super().__init__(fmt="[%(asctime)s] [%(levelname)s] %(message)s")
83 logger.debug("Initiating Log_Formatter")
84
85 def format(self, record):
86 # We use 8 to align the levelname, because CRITICAL ist the longest name and has 8 chars
87 return "[{}][{:^}][{:^8}] {}".format(self.formatTime(record),
88 record.name,
89 record.levelname,
90 record.getMessage())
91
92 def formatTime(self, record, datefmt=None):
93 t = time.strftime("%H:%M:%S", time.gmtime(record.created))
94 s = "{}.{:03d}".format(t, round(record.msecs,None))
95 return s