Debian Codegraph @

in_toto/log.py

raw
1 # Copyright New York University and the in-toto contributors
2 # SPDX-License-Identifier: Apache-2.0
3
4 """
5 <Program Name>
6 log.py
7
8 <Author>
9 Lukas Puehringer <[email protected]>
10
11 <Started>
12 Oct 4, 2016
13
14 <Copyright>
15 See LICENSE for licensing information.
16
17 <Purpose>
18 Configures "in_toto" base logger, which can be used for debugging and user
19 feedback in in-toto command line interfaces and libraries.
20
21 Logging methods and levels are available through Python's logging module.
22
23 If the log level is set to 'logging.DEBUG' log messages include
24 additional information about the log statement. Moreover, calls to the
25 `error` method will also output a stacktrace (if available).
26 In all other log levels only the log message is shown without additional
27 info.
28
29 The default log level of the base logger is 'logging.WARNING', unless
30 'in_toto.settings.DEBUG' is 'True', in that case the default log level is
31 'logging.DEBUG'.
32
33 The default handler of the base logger is a 'StreamHandler', which writes all
34 log messages permitted by the used log level to 'sys.stderr'.
35
36
37 <Usage>
38 This module should be imported in '__init__.py' to configure the base logger.
39 Subsequently, command line interfaces should fetch the base logger by name
40 and customize the log level according to any passed command line arguments.
41 They can use the convenience method `setLevelVerboseOrQuiet` available on
42 the custom base logger, e.g.:
43
44 ```
45 import logging
46 LOG = logging.getLogger("in_toto")
47
48 # parse args ...
49
50 LOG.setLevelVerboseOrQuiet(args.verbose, args.quiet)
51
52 # call library function ...
53 ```
54
55 Library modules can then create loggers, passing the module name, which will
56 inherit the base logger's log level and format, e.g.:
57
58 ```
59 import logging
60 LOG = logging.getLogger(__name__)
61
62 LOG.warning("Shown per default.")
63
64 LOG.info("Only shown if, log level was set to <= logging.INFO, e.g. in cli.")
65
66 LOG.info("In debug mode it looks something like this)
67 # in_toto.runlib:400:INFO:In debug mode it looks something like this
68
69 ```
70
71 """
72 import logging
73 import sys
74
75 import in_toto.settings
76
77 # Different log message formats for different log levels
78 FORMAT_MESSAGE = "%(message)s"
79 FORMAT_DEBUG = "%(name)s:%(lineno)d:%(levelname)s:%(message)s"
80
81 # Cache default logger class, should be logging.Logger if not changed elsewhere
82 _LOGGER_CLASS = logging.getLoggerClass()
83
84
85 # Create logger subclass
86 class InTotoLogger(_LOGGER_CLASS):
87 """logger.Logging subclass, using providing custom error method and
88 convenience method for log levels."""
89
90 QUIET = logging.CRITICAL + 1
91
92 def error(self, msg):
93 """Show stacktrace depending on its availability and the logger's log
94 level, i.e. only show stacktrace in DEBUG level."""
95 show_stacktrace = self.level == logging.DEBUG and sys.exc_info() != (
96 None,
97 None,
98 None,
99 )
100 return super(InTotoLogger, self).error(msg, exc_info=show_stacktrace)
101
102 # Allow non snake_case function name for consistency with logging library
103 def setLevelVerboseOrQuiet(
104 self, verbose, quiet
105 ): # pylint: disable=invalid-name
106 """Convenience method to set the logger's verbosity level based on the
107 passed booleans verbose and quiet (useful for cli tools)."""
108 if verbose:
109 self.setLevel(logging.INFO)
110
111 elif quiet:
112 # TODO: Is it enough to use logging.CRITICAL + 1 to suppress all output?
113 # A saver way would be to use a NullHandler or Filters.
114 self.setLevel(self.QUIET)
115
116
117 # Temporarily change logger default class to instantiate an in-toto base logger
118 logging.setLoggerClass(InTotoLogger)
119 LOGGER = logging.getLogger("in_toto")
120 logging.setLoggerClass(_LOGGER_CLASS)
121
122 # In DEBUG mode we log all log types and add additional information,
123 # otherwise we only log warning, error and critical and only the message.
124 if in_toto.settings.DEBUG: # pragma: no cover
125 LEVEL = logging.DEBUG
126 FORMAT_STRING = FORMAT_DEBUG
127
128 else:
129 LEVEL = logging.WARNING
130 FORMAT_STRING = FORMAT_MESSAGE
131
132 # Add a StreamHandler with the chosen format to in-toto's base logger,
133 # which will write log messages to `sys.stderr`.
134 FORMATTER = logging.Formatter(FORMAT_STRING)
135 HANDLER = logging.StreamHandler()
136 HANDLER.setFormatter(FORMATTER)
137 LOGGER.addHandler(HANDLER)
138 LOGGER.setLevel(LEVEL)