Coverage for ebcpy/utils/__init__.py: 100%

20 statements  

« prev     ^ index     » next       coverage.py v7.4.4, created at 2024-09-19 12:21 +0000

1""" 

2Package containing utility functions used in different packages. 

3Contains a statistics analyzer and a visualizer. 

4""" 

5import logging 

6import os 

7from pathlib import Path 

8from typing import Union 

9 

10 

11def setup_logger(name: str, 

12 working_directory: Union[Path, str] = None, 

13 level=logging.DEBUG): 

14 """ 

15 Setup an class or module specific logger instance 

16 to ensure readable output for users. 

17 

18 :param str name: 

19 The name of the logger instance 

20 :param str,Path working_directory: 

21 The path where to store the logfile. 

22 If None is given, logs are not stored. 

23 :param str level: 

24 The logging level, default is DEBUG 

25 

26 .. versionadded:: 0.1.7 

27 """ 

28 logger = logging.getLogger(name=name) 

29 # Set log-level 

30 logger.setLevel(level=level) 

31 # Check if logger was already instantiated. If so, return already. 

32 if logger.handlers: 

33 return logger 

34 # Add handlers if not set already by logging.basicConfig and if path is specified 

35 formatter = logging.Formatter(fmt='%(asctime)s %(levelname)s %(name)s: %(message)s', 

36 datefmt='%d.%m.%Y-%H:%M:%S') 

37 if not logging.getLogger().hasHandlers(): 

38 console = logging.StreamHandler() 

39 console.setFormatter(fmt=formatter) 

40 logger.addHandler(hdlr=console) 

41 if working_directory is not None: 

42 os.makedirs(working_directory, exist_ok=True) 

43 file_handler = logging.FileHandler(filename=working_directory.joinpath(f"{name}.log")) 

44 file_handler.setFormatter(fmt=formatter) 

45 logger.addHandler(hdlr=file_handler) 

46 return logger