Use one time to which all serial connection output is relativ
[nitsi.git] / src / nitsi / logger.py
CommitLineData
d7036f7b
JS
1#!/usr/bin/python3
2
3import logging
4import os
5import time
6
7logger = logging.getLogger("nitsi.logger")
8
9class Logger_Exeception(BaseException):
10 pass
11
12# This function should create the necessary folders
13# and touch the logging files
14def init_logging(path):
15 logger.debug("Init logging directory")
16 if not os.path.isdir(path):
17 logger.error("{} is not a valid directory".format(path))
18
19 try:
20 path = os.path.abspath(path)
21 except BaseException as e:
22 logger.error("Failed to get the absolute path for: {}".format(path))
23
24 log_dir = "{}/log".format(path)
25
26 if not os.path.exists(log_dir):
27 os.mkdir(log_dir)
28
29 time_dir = log_dir + "/" + time.strftime("%Y-%m-%d_%H-%M-%S" ,time.gmtime(time.time()))
30
31 if os.path.exists(time_dir):
32 logger.error("Path {} alreday exist".format(time_dir))
33 raise Logger_Exeception
34 else:
35 os.mkdir(time_dir)
36
37 return time_dir
b4936764
JS
38
39
40class TestFormatter(logging.Formatter):
41 def __init__(self, start_time=None, name=None):
42 super().__init__(fmt="[%(asctime)s] %(message)s")
43 logger.debug("Initiating TestFormatter for")
44 if start_time == None:
45 self.starttime = time.time()
46 else:
47 self.starttime = start_time
48
49 if name == None:
50 self.name = ""
51 else:
52 self.name = name
53
54 def converter(self, recordtime):
55
56 # This returns a timestamp relatively to the time when we started
57 # the test.
58
59 recordtime -= self.starttime
60
61 return time.gmtime(recordtime)
62
63 def format(self, record):
64 return "[{}][{}] {}".format(self.formatTime(record), self.name, record.getMessage())
65
66 def formatTime(self, record, datefmt=None):
67 ct = self.converter(record.created)
68 t = time.strftime("%H:%M:%S", ct)
69 s = "{}.{:03d}".format(t, round(record.msecs,None))
70 return s