Fix osdf code after upgrading to py38
[optf/osdf.git] / osdf / logging / oof_mdc_context.py
1 # -------------------------------------------------------------------------
2 #   Copyright (c) 2020 AT&T Intellectual Property
3 #
4 #   Licensed under the Apache License, Version 2.0 (the "License");
5 #   you may not use this file except in compliance with the License.
6 #   You may obtain a copy of the License at
7 #
8 #       http://www.apache.org/licenses/LICENSE-2.0
9 #
10 #   Unless required by applicable law or agreed to in writing, software
11 #   distributed under the License is distributed on an "AS IS" BASIS,
12 #   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 #   See the License for the specific language governing permissions and
14 #   limitations under the License.
15 #
16 # -------------------------------------------------------------------------
17 #
18
19 import logging
20 import re
21 import sys
22
23 from onaplogging.marker import Marker
24 from onaplogging.marker import MARKER_TAG
25 from onaplogging.mdcContext import _replace_func_name
26 from onaplogging.mdcContext import fetchkeys
27 from onaplogging.mdcContext import findCaller as fc
28 from onaplogging.mdcContext import MDC
29
30 from osdf.utils.mdc_utils import set_error_details
31
32
33 def findCaller(self, stack_info=False, stacklevel=1):
34     """replacing onaplogging.mdcContext with this method to work with py3.8
35
36     """
37     return fc(stack_info)
38
39
40 def mdc_mapper():
41     """Convert the MDC dict into comma separated, name=value string
42
43     :return: string format
44     """
45     return ','.join(f'{k}={v}' for (k, v) in MDC.result().items() if k not in ['customField2'])
46
47
48 @fetchkeys
49 def info(self, msg, *args, **kwargs):
50     """Wrapper method for log.info is called
51
52     """
53     if self.isEnabledFor(logging.INFO):
54         MDC.put('customField2', mdc_mapper())
55         self._log(logging.INFO, no_sep(msg), args, **kwargs)
56
57
58 @fetchkeys
59 def debug(self, msg, *args, **kwargs):
60     """Wrapper method for log.debug is called
61
62     msg: log message
63     args: logging args
64     kwargs: all the optional args
65     """
66     if self.isEnabledFor(logging.DEBUG):
67         self._log(logging.DEBUG, no_sep(msg), args, **kwargs)
68
69
70 @fetchkeys
71 def warning(self, msg, *args, **kwargs):
72     """Wrapper method for log.warning is called
73
74     msg: log message
75     args: logging args
76     kwargs: all the optional args
77     """
78     if self.isEnabledFor(logging.WARNING):
79         self._log(logging.WARNING, no_sep(msg), args, **kwargs)
80
81
82 @fetchkeys
83 def exception(self, msg, *args, **kwargs):
84     """Wrapper method for log.exception is called
85
86     msg: log message
87     args: logging args
88     kwargs: all the optional args
89     """
90     kwargs['exc_info'] = 1
91     self.error(no_sep(msg), *args, **kwargs)
92
93
94 @fetchkeys
95 def critical(self, msg, *args, **kwargs):
96     """Wrapper method for log.critical
97
98     msg: log message
99     args: logging args
100     kwargs: all the optional args
101     """
102     if self.isEnabledFor(logging.CRITICAL):
103         self._log(logging.CRITICAL, no_sep(msg), args, **kwargs)
104
105
106 @fetchkeys
107 def error(self, msg, *args, **kwargs):
108     """Wrapper method for log.error is called
109
110     msg: log message
111     args: logging args
112     kwargs: all the optional args
113     """
114     if self.isEnabledFor(logging.ERROR):
115         if not MDC.get('errorCode'):
116             set_error_details(400, 'Internal Error')
117         MDC.put('customField2', mdc_mapper())
118         self._log(logging.ERROR, no_sep(msg), args, **kwargs)
119
120
121 @fetchkeys
122 def log(self, level, msg, *args, **kwargs):
123     """Wrapper method for log.log is called
124
125     msg: log message
126     args: logging args
127     kwargs: all the optional args
128     """
129     if not isinstance(level, int):
130         if logging.raiseExceptions:
131             raise TypeError("level must be an integer")
132         else:
133             return
134
135     if self.isEnabledFor(level):
136         self._log(level, no_sep(msg), args, **kwargs)
137
138
139 def handle(self, record):
140     """Wrapper method for log.handle is called
141
142     """
143     c_marker = getattr(self, MARKER_TAG, None)
144
145     if isinstance(c_marker, Marker):
146         setattr(record, MARKER_TAG, c_marker)
147
148     if (not self.disabled) and self.filter(record):
149         self.callHandlers(record)
150
151
152 def no_sep(message):
153     """This method will remove newline, | from the message
154
155     """
156     if message is None:
157         return ''
158     return re.sub(r'[\|\n]', ' ', str(message))
159
160
161 def patch_logging_mdc():
162     """The patch to add MDC ability in logging Record instance at runtime
163
164     """
165     local_module = sys.modules[__name__]
166     for attr in dir(logging.Logger):
167         if attr in _replace_func_name:
168             new_func = getattr(local_module, attr, None)
169             if new_func:
170                 setattr(logging.Logger, attr, new_func)