1
1
import datetime
2
+ from enum import IntEnum
2
3
3
- # Replace this with more powerful logging library
4
+ class LOG_LEVEL (IntEnum ):
5
+ DEBUG = 0
6
+ INFO = 1
7
+ WARNING = 2
8
+ ERROR = 3
9
+
10
+ # TODO: see if there are better libraries available
4
11
class Logger :
5
- def __init__ (self , log_file_path ):
12
+ def __init__ (self , log_file_path : str , log_level : LOG_LEVEL = LOG_LEVEL . WARNING ):
6
13
self .log_file_path = log_file_path
14
+ self .log_level = log_level
7
15
8
- def log (self , msg ):
16
+ def debug (self , msg ):
17
+ if not self .__should_skip_logging (LOG_LEVEL .DEBUG ):
18
+ self .__write_log (self .__post_process_log_entry (msg , LOG_LEVEL .DEBUG ))
19
+
20
+ def info (self , msg ):
21
+ if not self .__should_skip_logging (LOG_LEVEL .INFO ):
22
+ self .__write_log (self .__post_process_log_entry (msg , LOG_LEVEL .INFO ))
23
+
24
+ def warning (self , msg ):
25
+ if not self .__should_skip_logging (LOG_LEVEL .WARNING ):
26
+ self .__write_log (self .__post_process_log_entry (msg , LOG_LEVEL .WARNING ))
27
+
28
+ def error (self , msg ):
29
+ if not self .__should_skip_logging (LOG_LEVEL .ERROR ):
30
+ self .__write_log (self .__post_process_log_entry (msg , LOG_LEVEL .ERROR ))
31
+
32
+ def __post_process_log_entry (self , msg : str , log_level : LOG_LEVEL ) -> str :
9
33
timestamp = datetime .datetime .now ().strftime ("%Y-%m-%d %H:%M:%S" )
34
+ return f"[{ log_level } ] { timestamp } - { msg } \n "
35
+
36
+ def __write_log (self , msg ):
10
37
with open (self .log_file_path , "a" ) as f :
11
- f .write (f"{ timestamp } - { msg } \n " )
38
+ f .write (msg )
39
+ # TODO: look for optimization opportunity here
40
+ f .flush ()
41
+
42
+ def __should_skip_logging (self , log_level : LOG_LEVEL ) -> bool :
43
+ return int (log_level ) < int (self .log_level )
0 commit comments