Coretex
logging.py
1 # Copyright (C) 2023 Coretex LLC
2 
3 # This file is part of Coretex.ai
4 
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License as
7 # published by the Free Software Foundation, either version 3 of the
8 # License, or (at your option) any later version.
9 
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU Affero General Public License for more details.
14 
15 # You should have received a copy of the GNU Affero General Public License
16 # along with this program. If not, see <https://www.gnu.org/licenses/>.
17 
18 from typing import List, Optional
19 from pathlib import Path
20 
21 import sys
22 import logging
23 
24 from .formatter import CTXFormatter
25 from .severity import LogSeverity
26 from ..utils import createFileHandler
27 
28 
29 def createFormatter(
30  includeTime: bool = True,
31  includeLevel: bool = True,
32  includeColor: bool = True,
33  jsonOutput: bool = True
34 ) -> logging.Formatter:
35 
36  fmt: List[str] = []
37 
38  if includeTime:
39  fmt.append("%(asctime)s")
40 
41  if includeLevel:
42  fmt.append("%(levelname)s")
43 
44  if len(fmt) != 0:
45  fmt[-1] = fmt[-1] + ":"
46 
47  fmt.append("%(message)s")
48 
49  return CTXFormatter(
50  fmt = " ".join(fmt),
51  datefmt= "%Y-%m-%d %H:%M:%S",
52  style = "%",
53  color = includeColor,
54  jsonOutput = jsonOutput
55  )
56 
57 
58 def initializeLogger(
59  severity: LogSeverity,
60  logPath: Path,
61  streamHandler: Optional[logging.StreamHandler] = None,
62  jsonOutput: bool = False
63 ) -> None:
64 
65  """
66  Initializes python logging module
67 
68  Parameters
69  ----------
70  severity : LogSeverity
71  Severity level of the logger
72  logPath : Path
73  File path where logs will be stored
74  streamHandler: Optional[logging.StreamHandler] : bool
75  Stream handler which will be used for logging
76  If None default one will be used
77  """
78 
79  if streamHandler is None:
80  streamHandler = logging.StreamHandler(sys.stdout)
81  streamHandler.setLevel(severity.getLevel())
82 
83  streamHandler.setFormatter(createFormatter(
84  includeTime = False,
85  jsonOutput = jsonOutput
86  ))
87 
88  fileHandler = createFileHandler(logPath)
89  fileHandler.setLevel(logging.DEBUG)
90  fileHandler.setFormatter(createFormatter(includeColor = False, jsonOutput = False))
91 
92  logging.basicConfig(
93  level = logging.NOTSET,
94  force = True,
95  handlers = [
96  streamHandler,
97  fileHandler
98  ]
99  )