This file is indexed.

/usr/lib/python3/dist-packages/plainbox/impl/logging.py is in python3-plainbox 0.5.3-2.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
# This file is part of Checkbox.
#
# Copyright 2012, 2013 Canonical Ltd.
# Written by:
#   Zygmunt Krynicki <zygmunt.krynicki@canonical.com>
#
# Checkbox is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3,
# as published by the Free Software Foundation.

#
# Checkbox is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Checkbox.  If not, see <http://www.gnu.org/licenses/>.

"""
:mod:`plainbox.impl.logging` -- configuration for logging
=========================================================

.. warning::

    THIS MODULE DOES NOT HAVE STABLE PUBLIC API
"""

__all__ = ['setup_logging', 'adjust_logging']

import logging
import logging.config
import os
import sys

from plainbox.i18n import gettext as _
from plainbox.impl.color import ansi_on, ansi_off


logger = logging.getLogger("plainbox.logging")

# XXX: enable ansi escape sequences if sys.std{out,err} are both TTYs
#
# This is a bad place to take this decision (ideally we'd do that per log
# handler) but it's rather hard to do correctly (handlers know where stuff
# goes, formatters decide how stuff looks like) so this half solution is
# better than nothing.
if sys.stdout.isatty() and sys.stderr.isatty():
    ansi = ansi_on
else:
    ansi = ansi_off


class ANSIFormatter(logging.Formatter):
    """
    Formatter that allows to expand '{ansi}' (using new-style
    python formatting syntax) inside format descriptions.
    """

    def __init__(self, fmt=None, datefmt=None, style='%'):
        if fmt is not None:
            fmt = fmt.format(ansi=ansi)
        super(ANSIFormatter, self).__init__(fmt, datefmt, style)


class LevelFilter:
    """
    Log filter that accepts records in a certain level range
    """

    def __init__(self, min_level="NOTSET", max_level="CRITICAL"):
        self.min_level = logging._checkLevel(min_level)
        self.max_level = logging._checkLevel(max_level)

    def filter(self, record):
        if self.min_level <= record.levelno <= self.max_level:
            return 1
        else:
            return 0


class LoggingHelper:
    """
    Helper class that manages logging subsystem
    """

    def setup_logging(self):
        config_dict = self.DEFAULT_CONFIG
        # Ensure that the logging directory exists. This is important
        # because we're about to open some files there. If it can't be created
        # we fall back to a console-only config.
        if not os.path.exists(self.log_dir):
            # It seems that exists_ok is flaky
            try:
                os.makedirs(self.log_dir, exist_ok=True)
            except OSError as error:
                config_dict = self.DEFAULT_CONSOLE_ONLY_CONFIG
        # Apply the selected configuration. This overrides anything currently
        # defined for all of the logging subsystem in this python runtime
        logging.config.dictConfig(config_dict)

    def adjust_logging(self, level=None, trace_list=None, debug_console=False):
        # Bump logging on the root logger if requested
        if level is not None:
            logging.getLogger(None).setLevel(level)
            logger.debug(_("Enabled %r on root logger"), level)
            logging.getLogger("plainbox").setLevel(level)
        # Enable tracing on specified loggers
        if trace_list is not None:
            for name in trace_list:
                logging.getLogger(name).setLevel(logging.DEBUG)
                logger.debug(_("Enabled debugging on logger %r"), name)
        if debug_console and (level == 'DEBUG' or trace_list):
            # Enable DEBUG logging to console if explicitly requested
            logging.config.dictConfig(self.DEBUG_CONSOLE_CONFIG)

    @property
    def log_dir(self):
        """
        directory with all of the log files
        """
        xdg_cache_home = os.environ.get('XDG_CACHE_HOME') or \
            os.path.join(os.path.expanduser('~'), '.cache')
        return os.path.join(xdg_cache_home, 'plainbox', 'logs')

    @property
    def DEFAULT_FORMATTERS(self):
        """
        Reusable dictionary with the formatter configuration plainbox uses
        """
        return {
            "console_debug": {
                "()": "plainbox.impl.logging.ANSIFormatter",
                "format": (
                    "{ansi.f.BLACK}{ansi.s.BRIGHT}"
                    "%(levelname)s"
                    "{ansi.s.NORMAL}{ansi.f.RESET}"
                    " "
                    "{ansi.f.CYAN}{ansi.s.DIM}"
                    "%(name)s"
                    "{ansi.f.RESET}{ansi.s.NORMAL}"
                    ": "
                    "{ansi.s.DIM}"
                    "%(message)s"
                    "{ansi.s.NORMAL}"
                ),
            },
            "console_info": {
                "()": "plainbox.impl.logging.ANSIFormatter",
                "format": (
                    "{ansi.f.WHITE}{ansi.s.BRIGHT}"
                    "%(levelname)s"
                    "{ansi.s.NORMAL}{ansi.f.RESET}"
                    " "
                    "{ansi.f.CYAN}{ansi.s.BRIGHT}"
                    "%(name)s"
                    "{ansi.f.RESET}{ansi.s.NORMAL}"
                    ": "
                    "%(message)s"
                ),
            },
            "console_warning": {
                "()": "plainbox.impl.logging.ANSIFormatter",
                "format": (
                    "{ansi.f.YELLOW}{ansi.s.BRIGHT}"
                    "%(levelname)s"
                    "{ansi.f.RESET}{ansi.s.NORMAL}"
                    " "
                    "{ansi.f.CYAN}%(name)s{ansi.f.RESET}"
                    ": "
                    "{ansi.f.WHITE}%(message)s{ansi.f.RESET}"
                ),
            },
            "console_error": {
                "()": "plainbox.impl.logging.ANSIFormatter",
                "format": (
                    "{ansi.f.RED}{ansi.s.BRIGHT}"
                    "%(levelname)s"
                    "{ansi.f.RESET}{ansi.s.NORMAL}"
                    " "
                    "{ansi.f.CYAN}%(name)s{ansi.f.RESET}"
                    ": "
                    "{ansi.f.WHITE}%(message)s{ansi.f.RESET}"
                ),
            },
            "log_precise": {
                "format": (
                    "%(asctime)s "
                    "[pid:%(process)s, thread:%(threadName)s, "
                    "reltime:%(relativeCreated)dms] "
                    "%(levelname)s %(name)s: %(message)s"
                ),
                "datefmt": "%Y-%m-%d %H:%M:%S",
            },
        }

    @property
    def DEFAULT_FILTERS(self):
        """
        Reusable dictionary with the filter configuration plainbox uses
        """
        return {
            "only_debug": {
                "()": "plainbox.impl.logging.LevelFilter",
                "max_level": "DEBUG",
            },
            "only_info": {
                "()": "plainbox.impl.logging.LevelFilter",
                "min_level": "INFO",
                "max_level": "INFO",
            },
            "only_warnings": {
                "()": "plainbox.impl.logging.LevelFilter",
                "min_level": "WARNING",
                "max_level": "WARNING",
            },
        }

    @property
    def DEFAULT_HANDLERS(self):
        """
        Reusable dictionary with the handler configuration plainbox uses.
        This configuration assumes the log file locations exist and are
        writable.
        """
        return {
            "console_debug": {
                "class": "logging.StreamHandler",
                "stream": "ext://sys.stdout",
                "formatter": "console_debug",
                "filters": ["only_debug"],
                "level": 150,
            },
            "console_info": {
                "class": "logging.StreamHandler",
                "stream": "ext://sys.stdout",
                "formatter": "console_info",
                "filters": ["only_info"],
            },
            "console_warning": {
                "class": "logging.StreamHandler",
                "stream": "ext://sys.stderr",
                "formatter": "console_warning",
                "filters": ["only_warnings"],
            },
            "console_error": {
                "class": "logging.StreamHandler",
                "stream": "ext://sys.stderr",
                "formatter": "console_error",
                "level": "ERROR",
            },
            "logfile_debug": {
                "class": "logging.handlers.RotatingFileHandler",
                "filename": os.path.join(self.log_dir, "debug.log"),
                "maxBytes": 32 << 20,
                "backupCount": 3,
                "mode": "a",
                "formatter": "log_precise",
                "delay": True,
                "filters": ["only_debug"],
            },
            "logfile_error": {
                "class": "logging.handlers.RotatingFileHandler",
                "filename": os.path.join(self.log_dir, "error.log"),
                "backupCount": 3,
                "level": "ERROR",
                "mode": "a",
                "formatter": "log_precise",
                "delay": True,
            },
            "logfile_crash": {
                "class": "logging.handlers.RotatingFileHandler",
                "filename": os.path.join(self.log_dir, "crash.log"),
                "backupCount": 3,
                "level": "ERROR",
                "mode": "a",
                "formatter": "log_precise",
                "delay": True,
            },
        }

    @property
    def DEFAULT_CONSOLE_ONLY_HANDLERS(self):
        """
        Reusable dictionary with a handler configuration using only the
        console for output.
        """
        return {
            "console_debug": {
                "class": "logging.StreamHandler",
                "stream": "ext://sys.stdout",
                "formatter": "console_debug",
                "filters": ["only_debug"],
                "level": 150,
            },
            "console_info": {
                "class": "logging.StreamHandler",
                "stream": "ext://sys.stdout",
                "formatter": "console_info",
                "filters": ["only_info"],
            },
            "console_warning": {
                "class": "logging.StreamHandler",
                "stream": "ext://sys.stderr",
                "formatter": "console_warning",
                "filters": ["only_warnings"],
            },
            "console_error": {
                "class": "logging.StreamHandler",
                "stream": "ext://sys.stderr",
                "formatter": "console_error",
                "level": "ERROR",
            },
        }

    @property
    def DEFAULT_LOGGERS(self):
        """
        Reusable dictionary with the logger configuration plainbox uses.
        This configuration assumes the log file locations exist and are
        writable.
        """
        return {
            "plainbox": {
                "level": "WARNING",
                "handlers": [
                    "console_debug",
                    "console_info",
                    "console_warning",
                    "console_error",
                    "logfile_error",
                    "logfile_debug",
                ],
            },
            "plainbox.crashes": {
                "level": "ERROR",
                "handlers": ["logfile_crash"],
            },
        }

    @property
    def DEFAULT_CONSOLE_ONLY_LOGGERS(self):
        """
        Reusable dictionary with a logger configuration using only the
        console for output.
        """
        return {
            "plainbox": {
                "level": "WARNING",
                "handlers": [
                    "console_debug",
                    "console_info",
                    "console_warning",
                    "console_error",
                ],
            },
            "plainbox.crashes": {
                "level": "ERROR",
                "handlers": ["console_error"],
            },
        }

    @property
    def DEFAULT_CONFIG(self):
        """
        Plainbox logging configuration with logfiles and console.
        """
        return {
            "version": 1,
            "formatters": self.DEFAULT_FORMATTERS,
            "filters": self.DEFAULT_FILTERS,
            "handlers": self.DEFAULT_HANDLERS,
            "loggers": self.DEFAULT_LOGGERS,
            "root": {
                "level": "WARNING",
            },
            "incremental": False,
            "disable_existing_loggers": True,
        }

    @property
    def DEFAULT_CONSOLE_ONLY_CONFIG(self):
        """
        Plainbox logging configuration with console output only.
        """
        return {
            "version": 1,
            "formatters": self.DEFAULT_FORMATTERS,
            "filters": self.DEFAULT_FILTERS,
            "handlers": self.DEFAULT_CONSOLE_ONLY_HANDLERS,
            "loggers": self.DEFAULT_CONSOLE_ONLY_LOGGERS,
            "root": {
                "level": "WARNING",
            },
            "incremental": False,
            "disable_existing_loggers": True,
        }

    @property
    def DEBUG_CONSOLE_CONFIG(self):
        return {
            "version": 1,
            "handlers": {
                "console_debug": {
                    "level": "DEBUG",
                },
            },
            "incremental": True,
        }


# Instantiate the helper
_LoggingHelper = LoggingHelper()

# And expose two methods from it
setup_logging = _LoggingHelper.setup_logging
adjust_logging = _LoggingHelper.adjust_logging