Line length: Fix recent merges
[csit.git] / resources / libraries / python / FilteredLogger.py
1 # Copyright (c) 2021 Cisco and/or its affiliates.
2 # Licensed under the Apache License, Version 2.0 (the "License");
3 # you may not use this file except in compliance with the License.
4 # You may obtain a copy of the License at:
5 #
6 #     http://www.apache.org/licenses/LICENSE-2.0
7 #
8 # Unless required by applicable law or agreed to in writing, software
9 # distributed under the License is distributed on an "AS IS" BASIS,
10 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 # See the License for the specific language governing permissions and
12 # limitations under the License.
13
14 """Python library for customizing robot.api.logger
15
16 As robot.api.logger is a module, it is not easy to copy, edit or inherit from.
17 This module offers a class to wrap it.
18 The main point of the class is to lower verbosity of Robot logging,
19 especially when injected to third party code (such as vpp_papi.VPPApiClient).
20
21 Also, String formatting using '%' operator is supported.
22
23 Logger.console() is not supported.
24 """
25
26 import logging
27
28 _LEVELS = {
29     u"TRACE": logging.DEBUG // 2,
30     u"DEBUG": logging.DEBUG,
31     u"INFO": logging.INFO,
32     u"HTML": logging.INFO,
33     u"WARN": logging.WARN,
34     u"ERROR": logging.ERROR,
35     u"CRITICAL": logging.CRITICAL,
36     u"NONE": logging.CRITICAL,
37 }
38
39
40 class FilteredLogger:
41     """Instances of this class have the similar API to robot.api.logger.
42
43     TODO: Support html argument?
44     TODO: Support console with a filtering switch?
45     """
46
47     def __init__(self, logger_module, min_level="INFO"):
48         """Remember the values, check min_level is known.
49
50         Use min_level of "CRITICAL" or "NONE" to disable logging entirely.
51
52         :param logger_module: robot.api.logger, or a compatible object.
53         :param min_level: Minimal level to log, lower levels are ignored.
54         :type logger_module: Object with .write(msg, level="INFO") signature.
55         :type min_level: str
56         :raises KeyError: If given min_level is not supported.
57         """
58         self.logger_module = logger_module
59         self.min_level_num = _LEVELS[min_level.upper()]
60
61     def write(self, message, farg=None, level=u"INFO"):
62         """Forwards the message to logger if min_level is reached.
63
64         Formatting using '%' operator is used when farg argument is suplied.
65
66         :param message: Message to log.
67         :param farg: Value for '%' operator, or None.
68         :param level: Level to possibly log with.
69         :type message: str
70         :type farg: NoneTye, or whatever '%' accepts: str, int, float, dict...
71         :type level: str
72         """
73         if _LEVELS[level.upper()] >= self.min_level_num:
74             if farg is not None:
75                 message = message % farg
76             self.logger_module.write(message, level=level)
77
78     def trace(self, message, farg=None):
79         """Forward the message using the ``TRACE`` level."""
80         self.write(message, farg=farg, level=u"TRACE")
81
82     def debug(self, message, farg=None):
83         """Forward the message using the ``DEBUG`` level."""
84         self.write(message, farg=farg, level=u"DEBUG")
85
86     def info(self, message, farg=None):
87         """Forward the message using the ``INFO`` level."""
88         self.write(message, farg=farg, level=u"INFO")
89
90     def warn(self, message, farg=None):
91         """Forward the message using the ``WARN`` level."""
92         self.write(message, farg=farg, level=u"WARN")
93
94     def error(self, message, farg=None):
95         """Forward the message using the ``ERROR`` level."""
96         self.write(message, farg=farg, level=u"ERROR")