a04eb674761c7dd55e26e0667cd88fa69280895f
[csit.git] / resources / libraries / python / FilteredLogger.py
1 # Copyright (c) 2019 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     "TRACE": logging.DEBUG // 2,
30     "DEBUG": logging.DEBUG,
31     "INFO": logging.INFO,
32     "HTML": logging.INFO,
33     "WARN": logging.WARN,
34     "ERROR": logging.ERROR,
35     "CRITICAL": logging.CRITICAL,
36     "NONE": logging.CRITICAL,
37 }
38
39 class FilteredLogger(object):
40     """Instances of this class have the similar API to robot.api.logger.
41
42     TODO: Support html argument?
43     TODO: Support console with a filtering switch?
44     """
45
46     def __init__(self, logger_module, min_level="INFO"):
47         """Remember the values, check min_level is known.
48
49         Use min_level of "CRITICAL" or "NONE" to disable logging entirely.
50
51         :param logger_module: robot.api.logger, or a compatible object.
52         :param min_level: Minimal level to log, lower levels are ignored.
53         :type logger_module: Object with .write(msg, level="INFO") signature.
54         :type min_level: str
55         :raises KeyError: If given min_level is not supported.
56         """
57         self.logger_module = logger_module
58         self.min_level_num = _LEVELS[min_level.upper()]
59
60     def write(self, message, farg=None, level="INFO"):
61         """Forwards the message to logger if min_level is reached.
62
63         Formatting using '%' operator is used when farg argument is suplied.
64
65         :param message: Message to log.
66         :param farg: Value for '%' operator, or None.
67         :param level: Level to possibly log with.
68         :type message: str
69         :type farg: NoneTye, or whatever '%' accepts: str, int, float, dict...
70         :type level: str
71         """
72         if _LEVELS[level.upper()] >= self.min_level_num:
73             if farg is not None:
74                 message = message % farg
75             self.logger_module.write(message, level=level)
76
77     def trace(self, message, farg=None):
78         """Forward the message using the ``TRACE`` level."""
79         self.write(message, farg=farg, level="TRACE")
80
81     def debug(self, message, farg=None):
82         """Forward the message using the ``DEBUG`` level."""
83         self.write(message, farg=farg, level="DEBUG")
84
85     def info(self, message, farg=None):
86         """Forward the message using the ``INFO`` level."""
87         self.write(message, farg=farg, level="INFO")
88
89     def warn(self, message, farg=None):
90         """Forward the message using the ``WARN`` level."""
91         self.write(message, farg=farg, level="WARN")
92
93     def error(self, message, farg=None):
94         """Forward the message using the ``ERROR`` level."""
95         self.write(message, farg=farg, level="ERROR")