Coverage for src/logging.py: 100%

21 statements  

« prev     ^ index     » next       coverage.py v7.3.0, created at 2024-10-10 12:25 +0000

1import logging 

2import pathlib 

3import sys 

4 

5 

6def load_logger(verbose=False, logfile='./www/build.txt', truncate_logfile=True) -> logging.Logger: # noqa: E501 

7 """ 

8 Load a logger with some sensible defaults. 

9 

10 ```python 

11 logger = src.load_logger() 

12 logger.info('starting program') 

13 ``` 

14 

15 Those defaults being: 

16 

17 1. Log to stderr with a simple formatter 

18 2. Write last build log to a file in the webroot. 

19 

20 Extra options: 

21 

22 - `logfile` path to the logfile 

23 - `truncate_logfile` whether to truncate the logfile or not 

24 """ 

25 

26 logger = logging.getLogger('blog') 

27 

28 # formatter 

29 formatter = logging.Formatter(fmt='blog: %(message)s') 

30 

31 # level 

32 if verbose: 

33 level = logging.DEBUG 

34 else: 

35 level = logging.INFO 

36 logger.setLevel(level) 

37 

38 # add stderr handler 

39 stderr_handler = logging.StreamHandler(stream=sys.stderr) 

40 stderr_handler.setFormatter(formatter) 

41 stderr_handler.setLevel(level) 

42 logger.addHandler(stderr_handler) 

43 

44 # add logfile handler 

45 file_handler = logging.FileHandler(str(logfile)) 

46 file_handler.setFormatter(formatter) 

47 file_handler.setLevel(level) 

48 logger.addHandler(file_handler) 

49 

50 # truncate log file 

51 with pathlib.Path(logfile).open('w') as f: 

52 f.write('') 

53 

54 return logger