coloredlogs-ng 16.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1518 @@
1
+ # Colored terminal output for Python's logging module.
2
+ #
3
+ # Author: Peter Odding <peter@peterodding.com>
4
+ # Last Change: November 17, 2026
5
+ # URL: https://coloredlogs.readthedocs.io
6
+
7
+ """
8
+ Colored terminal output for Python's :mod:`logging` module.
9
+
10
+ .. contents::
11
+ :local:
12
+
13
+ Getting started
14
+ ===============
15
+
16
+ The easiest way to get started is by importing :mod:`coloredlogs` and calling
17
+ :mod:`coloredlogs.install()` (similar to :func:`logging.basicConfig()`):
18
+
19
+ >>> import coloredlogs, logging
20
+ >>> coloredlogs.install(level='DEBUG')
21
+ >>> logger = logging.getLogger('some.module.name')
22
+ >>> logger.info("this is an informational message")
23
+ 2015-10-22 19:13:52 peter-macbook some.module.name[28036] INFO this is an informational message
24
+
25
+ The :mod:`~coloredlogs.install()` function creates a :class:`ColoredFormatter`
26
+ that injects `ANSI escape sequences`_ into the log output.
27
+
28
+ .. _ANSI escape sequences: https://en.wikipedia.org/wiki/ANSI_escape_code#Colors
29
+
30
+ Environment variables
31
+ =====================
32
+
33
+ The following environment variables can be used to configure the
34
+ :mod:`coloredlogs` module without writing any code:
35
+
36
+ ============================= ============================ ==================================
37
+ Environment variable Default value Type of value
38
+ ============================= ============================ ==================================
39
+ ``$COLOREDLOGS_AUTO_INSTALL`` 'false' a boolean that controls whether
40
+ :func:`auto_install()` is called
41
+ ``$COLOREDLOGS_LOG_LEVEL`` 'INFO' a log level name
42
+ ``$COLOREDLOGS_LOG_FORMAT`` :data:`DEFAULT_LOG_FORMAT` a log format string
43
+ ``$COLOREDLOGS_DATE_FORMAT`` :data:`DEFAULT_DATE_FORMAT` a date/time format string
44
+ ``$COLOREDLOGS_LEVEL_STYLES`` :data:`DEFAULT_LEVEL_STYLES` see :func:`parse_encoded_styles()`
45
+ ``$COLOREDLOGS_FIELD_STYLES`` :data:`DEFAULT_FIELD_STYLES` see :func:`parse_encoded_styles()`
46
+ ============================= ============================ ==================================
47
+
48
+ If the environment variable `$NO_COLOR`_ is set (the value doesn't matter, even
49
+ an empty string will do) then :func:`coloredlogs.install()` will take this as a
50
+ hint that colors should not be used (unless the ``isatty=True`` override was
51
+ passed by the caller).
52
+
53
+ .. _$NO_COLOR: https://no-color.org/
54
+
55
+ Examples of customization
56
+ =========================
57
+
58
+ Here we'll take a look at some examples of how you can customize
59
+ :mod:`coloredlogs` using environment variables.
60
+
61
+ .. contents::
62
+ :local:
63
+
64
+ About the defaults
65
+ ------------------
66
+
67
+ Here's a screen shot of the default configuration for easy comparison with the
68
+ screen shots of the following customizations (this is the same screen shot that
69
+ is shown in the introduction):
70
+
71
+ .. image:: images/defaults.png
72
+ :alt: Screen shot of colored logging with defaults.
73
+
74
+ The screen shot above was taken from ``urxvt`` which doesn't support faint text
75
+ colors, otherwise the color of green used for `debug` messages would have
76
+ differed slightly from the color of green used for `spam` messages.
77
+
78
+ Apart from the `faint` style of the `spam` level, the default configuration of
79
+ `coloredlogs` sticks to the eight color palette defined by the original ANSI
80
+ standard, in order to provide a somewhat consistent experience across terminals
81
+ and terminal emulators.
82
+
83
+ Available text styles and colors
84
+ --------------------------------
85
+
86
+ Of course you are free to customize the default configuration, in this case you
87
+ can use any text style or color that you know is supported by your terminal.
88
+ You can use the ``humanfriendly --demo`` command to try out the supported text
89
+ styles and colors:
90
+
91
+ .. image:: http://humanfriendly.readthedocs.io/en/latest/_images/ansi-demo.png
92
+ :alt: Screen shot of the 'humanfriendly --demo' command.
93
+
94
+ Changing the log format
95
+ -----------------------
96
+
97
+ The simplest customization is to change the log format, for example:
98
+
99
+ .. literalinclude:: examples/custom-log-format.txt
100
+ :language: console
101
+
102
+ Here's what that looks like in a terminal (I always work in terminals with a
103
+ black background and white text):
104
+
105
+ .. image:: images/custom-log-format.png
106
+ :alt: Screen shot of colored logging with custom log format.
107
+
108
+ Changing the date/time format
109
+ -----------------------------
110
+
111
+ You can also change the date/time format, for example you can remove the date
112
+ part and leave only the time:
113
+
114
+ .. literalinclude:: examples/custom-datetime-format.txt
115
+ :language: console
116
+
117
+ Here's what it looks like in a terminal:
118
+
119
+ .. image:: images/custom-datetime-format.png
120
+ :alt: Screen shot of colored logging with custom date/time format.
121
+
122
+ Changing the colors/styles
123
+ --------------------------
124
+
125
+ Finally you can customize the colors and text styles that are used:
126
+
127
+ .. literalinclude:: examples/custom-colors.txt
128
+ :language: console
129
+
130
+ Here's an explanation of the features used here:
131
+
132
+ - The numbers used in ``$COLOREDLOGS_LEVEL_STYLES`` demonstrate the use of 256
133
+ color mode (the numbers refer to the 256 color mode palette which is fixed).
134
+
135
+ - The `success` level demonstrates the use of a text style (bold).
136
+
137
+ - The `critical` level demonstrates the use of a background color (red).
138
+
139
+ Of course none of this can be seen in the shell transcript quoted above, but
140
+ take a look at the following screen shot:
141
+
142
+ .. image:: images/custom-colors.png
143
+ :alt: Screen shot of colored logging with custom colors.
144
+
145
+ .. _notes about log levels:
146
+
147
+ Some notes about log levels
148
+ ===========================
149
+
150
+ With regards to the handling of log levels, the :mod:`coloredlogs` package
151
+ differs from Python's :mod:`logging` module in two aspects:
152
+
153
+ 1. While the :mod:`logging` module uses the default logging level
154
+ :data:`logging.WARNING`, the :mod:`coloredlogs` package has always used
155
+ :data:`logging.INFO` as its default log level.
156
+
157
+ 2. When logging to the terminal or system log is initialized by
158
+ :func:`install()` or :func:`.enable_system_logging()` the effective
159
+ level [#]_ of the selected logger [#]_ is compared against the requested
160
+ level [#]_ and if the effective level is more restrictive than the requested
161
+ level, the logger's level will be set to the requested level (this happens
162
+ in :func:`adjust_level()`). The reason for this is to work around a
163
+ combination of design choices in Python's :mod:`logging` module that can
164
+ easily confuse people who aren't already intimately familiar with it:
165
+
166
+ - All loggers are initialized with the level :data:`logging.NOTSET`.
167
+
168
+ - When a logger's level is set to :data:`logging.NOTSET` the
169
+ :func:`~logging.Logger.getEffectiveLevel()` method will
170
+ fall back to the level of the parent logger.
171
+
172
+ - The parent of all loggers is the root logger and the root logger has its
173
+ level set to :data:`logging.WARNING` by default (after importing the
174
+ :mod:`logging` module).
175
+
176
+ Effectively all user defined loggers inherit the default log level
177
+ :data:`logging.WARNING` from the root logger, which isn't very intuitive for
178
+ those who aren't already familiar with the hierarchical nature of the
179
+ :mod:`logging` module.
180
+
181
+ By avoiding this potentially confusing behavior (see `#14`_, `#18`_, `#21`_,
182
+ `#23`_ and `#24`_), while at the same time allowing the caller to specify a
183
+ logger object, my goal and hope is to provide sane defaults that can easily
184
+ be changed when the need arises.
185
+
186
+ .. [#] Refer to :func:`logging.Logger.getEffectiveLevel()` for details.
187
+ .. [#] The logger that is passed as an argument by the caller or the root
188
+ logger which is selected as a default when no logger is provided.
189
+ .. [#] The log level that is passed as an argument by the caller or the
190
+ default log level :data:`logging.INFO` when no level is provided.
191
+
192
+ .. _#14: https://github.com/xolox/python-coloredlogs/issues/14
193
+ .. _#18: https://github.com/xolox/python-coloredlogs/issues/18
194
+ .. _#21: https://github.com/xolox/python-coloredlogs/pull/21
195
+ .. _#23: https://github.com/xolox/python-coloredlogs/pull/23
196
+ .. _#24: https://github.com/xolox/python-coloredlogs/issues/24
197
+
198
+ Classes and functions
199
+ =====================
200
+ """
201
+
202
+ # Standard library modules.
203
+ import collections
204
+ import logging
205
+ import os
206
+ import re
207
+ import socket
208
+ import sys
209
+
210
+ # External dependencies.
211
+ from humanfriendly import coerce_boolean
212
+ from humanfriendly.compat import coerce_string, is_string, on_windows
213
+ from humanfriendly.terminal import ANSI_COLOR_CODES, ansi_wrap, enable_ansi_support, terminal_supports_colors
214
+ from humanfriendly.text import format, split
215
+
216
+ # Semi-standard module versioning.
217
+ __version__ = '16.0'
218
+
219
+ DEFAULT_LOG_LEVEL = logging.INFO
220
+ """The default log level for :mod:`coloredlogs` (:data:`logging.INFO`)."""
221
+
222
+ DEFAULT_LOG_FORMAT = '%(asctime)s %(hostname)s %(name)s[%(process)d] %(levelname)s %(message)s'
223
+ """The default log format for :class:`ColoredFormatter` objects (a string)."""
224
+
225
+ DEFAULT_DATE_FORMAT = '%Y-%m-%d %H:%M:%S'
226
+ """The default date/time format for :class:`ColoredFormatter` objects (a string)."""
227
+
228
+ CHROOT_FILES = ['/etc/debian_chroot']
229
+ """A list of filenames that indicate a chroot and contain the name of the chroot."""
230
+
231
+ DEFAULT_FIELD_STYLES = dict(
232
+ asctime=dict(color='green'),
233
+ hostname=dict(color='magenta'),
234
+ levelname=dict(color='black', bold=True),
235
+ name=dict(color='blue'),
236
+ programname=dict(color='cyan'),
237
+ username=dict(color='yellow'),
238
+ )
239
+ """Mapping of log format names to default font styles."""
240
+
241
+ DEFAULT_LEVEL_STYLES = dict(
242
+ spam=dict(color='green', faint=True),
243
+ debug=dict(color='green'),
244
+ verbose=dict(color='blue'),
245
+ info=dict(),
246
+ notice=dict(color='magenta'),
247
+ warning=dict(color='yellow'),
248
+ success=dict(color='green', bold=True),
249
+ error=dict(color='red'),
250
+ critical=dict(color='red', bold=True),
251
+ )
252
+ """Mapping of log level names to default font styles."""
253
+
254
+ DEFAULT_FORMAT_STYLE = '%'
255
+ """The default logging format style (a single character)."""
256
+
257
+ FORMAT_STYLE_PATTERNS = {
258
+ '%': r'%\((\w+)\)[#0 +-]*\d*(?:\.\d+)?[hlL]?[diouxXeEfFgGcrs%]',
259
+ '{': r'{(\w+)[^}]*}',
260
+ '$': r'\$(\w+)|\${(\w+)}',
261
+ }
262
+ """
263
+ A dictionary that maps the `style` characters ``%``, ``{`` and ``$`` (see the
264
+ documentation of the :class:`python3:logging.Formatter` class in Python 3.2+)
265
+ to strings containing regular expression patterns that can be used to parse
266
+ format strings in the corresponding style:
267
+
268
+ ``%``
269
+ A string containing a regular expression that matches a "percent conversion
270
+ specifier" as defined in the `String Formatting Operations`_ section of the
271
+ Python documentation. Here's an example of a logging format string in this
272
+ format: ``%(levelname)s:%(name)s:%(message)s``.
273
+
274
+ ``{``
275
+ A string containing a regular expression that matches a "replacement field" as
276
+ defined in the `Format String Syntax`_ section of the Python documentation.
277
+ Here's an example of a logging format string in this format:
278
+ ``{levelname}:{name}:{message}``.
279
+
280
+ ``$``
281
+ A string containing a regular expression that matches a "substitution
282
+ placeholder" as defined in the `Template Strings`_ section of the Python
283
+ documentation. Here's an example of a logging format string in this format:
284
+ ``$levelname:$name:$message``.
285
+
286
+ These regular expressions are used by :class:`FormatStringParser` to introspect
287
+ and manipulate logging format strings.
288
+
289
+ .. _String Formatting Operations: https://docs.python.org/2/library/stdtypes.html#string-formatting
290
+ .. _Format String Syntax: https://docs.python.org/2/library/string.html#formatstrings
291
+ .. _Template Strings: https://docs.python.org/3/library/string.html#template-strings
292
+ """
293
+
294
+
295
+ def auto_install():
296
+ """
297
+ Automatically call :func:`install()` when ``$COLOREDLOGS_AUTO_INSTALL`` is set.
298
+
299
+ The `coloredlogs` package includes a `path configuration file`_ that
300
+ automatically imports the :mod:`coloredlogs` module and calls
301
+ :func:`auto_install()` when the environment variable
302
+ ``$COLOREDLOGS_AUTO_INSTALL`` is set.
303
+
304
+ This function uses :func:`~humanfriendly.coerce_boolean()` to check whether
305
+ the value of ``$COLOREDLOGS_AUTO_INSTALL`` should be considered :data:`True`.
306
+
307
+ .. _path configuration file: https://docs.python.org/2/library/site.html#module-site
308
+ """
309
+ if coerce_boolean(os.environ.get('COLOREDLOGS_AUTO_INSTALL', 'false')):
310
+ install()
311
+
312
+
313
+ def install(level=None, **kw):
314
+ """
315
+ Enable colored terminal output for Python's :mod:`logging` module.
316
+
317
+ :param level: The default logging level (an integer or a string with a
318
+ level name, defaults to :data:`DEFAULT_LOG_LEVEL`).
319
+ :param logger: The logger to which the stream handler should be attached (a
320
+ :class:`~logging.Logger` object, defaults to the root logger).
321
+ :param fmt: Set the logging format (a string like those accepted by
322
+ :class:`~logging.Formatter`, defaults to
323
+ :data:`DEFAULT_LOG_FORMAT`).
324
+ :param datefmt: Set the date/time format (a string, defaults to
325
+ :data:`DEFAULT_DATE_FORMAT`).
326
+ :param style: One of the characters ``%``, ``{`` or ``$`` (defaults to
327
+ :data:`DEFAULT_FORMAT_STYLE`). See the documentation of the
328
+ :class:`python3:logging.Formatter` class in Python 3.2+. On
329
+ older Python versions only ``%`` is supported.
330
+ :param milliseconds: :data:`True` to show milliseconds like :mod:`logging`
331
+ does by default, :data:`False` to hide milliseconds
332
+ (the default is :data:`False`, see `#16`_).
333
+ :param level_styles: A dictionary with custom level styles (defaults to
334
+ :data:`DEFAULT_LEVEL_STYLES`).
335
+ :param field_styles: A dictionary with custom field styles (defaults to
336
+ :data:`DEFAULT_FIELD_STYLES`).
337
+ :param stream: The stream where log messages should be written to (a
338
+ file-like object). This defaults to :data:`None` which
339
+ means :class:`StandardErrorHandler` is used.
340
+ :param isatty: :data:`True` to use a :class:`ColoredFormatter`,
341
+ :data:`False` to use a normal :class:`~logging.Formatter`
342
+ (defaults to auto-detection using
343
+ :func:`~humanfriendly.terminal.terminal_supports_colors()`).
344
+ :param reconfigure: If :data:`True` (the default) multiple calls to
345
+ :func:`coloredlogs.install()` will each override
346
+ the previous configuration.
347
+ :param use_chroot: Refer to :class:`HostNameFilter`.
348
+ :param programname: Refer to :class:`ProgramNameFilter`.
349
+ :param username: Refer to :class:`UserNameFilter`.
350
+ :param syslog: If :data:`True` then :func:`.enable_system_logging()` will
351
+ be called without arguments (defaults to :data:`False`). The
352
+ `syslog` argument may also be a number or string, in this
353
+ case it is assumed to be a logging level which is passed on
354
+ to :func:`.enable_system_logging()`.
355
+
356
+ The :func:`coloredlogs.install()` function is similar to
357
+ :func:`logging.basicConfig()`, both functions take a lot of optional
358
+ keyword arguments but try to do the right thing by default:
359
+
360
+ 1. If `reconfigure` is :data:`True` (it is by default) and an existing
361
+ :class:`~logging.StreamHandler` is found that is connected to either
362
+ :data:`~sys.stdout` or :data:`~sys.stderr` the handler will be removed.
363
+ This means that first calling :func:`logging.basicConfig()` and then
364
+ calling :func:`coloredlogs.install()` will replace the stream handler
365
+ instead of adding a duplicate stream handler. If `reconfigure` is
366
+ :data:`False` and an existing handler is found no further steps are
367
+ taken (to avoid installing a duplicate stream handler).
368
+
369
+ 2. A :class:`~logging.StreamHandler` is created and connected to the stream
370
+ given by the `stream` keyword argument (:data:`sys.stderr` by
371
+ default). The stream handler's level is set to the value of the `level`
372
+ keyword argument.
373
+
374
+ 3. A :class:`ColoredFormatter` is created if the `isatty` keyword argument
375
+ allows it (or auto-detection allows it), otherwise a normal
376
+ :class:`~logging.Formatter` is created. The formatter is initialized
377
+ with the `fmt` and `datefmt` keyword arguments (or their computed
378
+ defaults).
379
+
380
+ The environment variable ``$NO_COLOR`` is taken as a hint by
381
+ auto-detection that colors should not be used.
382
+
383
+ 4. :func:`HostNameFilter.install()`, :func:`ProgramNameFilter.install()`
384
+ and :func:`UserNameFilter.install()` are called to enable the use of
385
+ additional fields in the log format.
386
+
387
+ 5. If the logger's level is too restrictive it is relaxed (refer to `notes
388
+ about log levels`_ for details).
389
+
390
+ 6. The formatter is added to the handler and the handler is added to the
391
+ logger.
392
+
393
+ .. _#16: https://github.com/xolox/python-coloredlogs/issues/16
394
+ """
395
+ logger = kw.get('logger') or logging.getLogger()
396
+ reconfigure = kw.get('reconfigure', True)
397
+ stream = kw.get('stream') or sys.stderr
398
+ style = check_style(kw.get('style') or DEFAULT_FORMAT_STYLE)
399
+ # Get the log level from an argument, environment variable or default and
400
+ # convert the names of log levels to numbers to enable numeric comparison.
401
+ if level is None:
402
+ level = os.environ.get('COLOREDLOGS_LOG_LEVEL', DEFAULT_LOG_LEVEL)
403
+ level = level_to_number(level)
404
+ # Remove any existing stream handler that writes to stdout or stderr, even
405
+ # if the stream handler wasn't created by coloredlogs because multiple
406
+ # stream handlers (in the same hierarchy) writing to stdout or stderr would
407
+ # create duplicate output. `None' is a synonym for the possibly dynamic
408
+ # value of the stderr attribute of the sys module.
409
+ match_streams = ([sys.stdout, sys.stderr]
410
+ if stream in [sys.stdout, sys.stderr, None]
411
+ else [stream])
412
+ match_handler = lambda handler: match_stream_handler(handler, match_streams)
413
+ handler, logger = replace_handler(logger, match_handler, reconfigure)
414
+ # Make sure reconfiguration is allowed or not relevant.
415
+ if not (handler and not reconfigure):
416
+ # Make it easy to enable system logging.
417
+ syslog_enabled = kw.get('syslog')
418
+ # We ignore the value `None' because it means the caller didn't opt in
419
+ # to system logging and `False' because it means the caller explicitly
420
+ # opted out of system logging.
421
+ if syslog_enabled not in (None, False):
422
+ from coloredlogs.syslog import enable_system_logging
423
+ if syslog_enabled is True:
424
+ # If the caller passed syslog=True then we leave the choice of
425
+ # default log level up to the coloredlogs.syslog module.
426
+ enable_system_logging()
427
+ else:
428
+ # Values other than (None, True, False) are assumed to
429
+ # represent a logging level for system logging.
430
+ enable_system_logging(level=syslog_enabled)
431
+ # Figure out whether we can use ANSI escape sequences.
432
+ use_colors = kw.get('isatty', None)
433
+ # In the following indented block the expression (use_colors is None)
434
+ # can be read as "auto detect is enabled and no reason has yet been
435
+ # found to automatically disable color support".
436
+ if use_colors or (use_colors is None):
437
+ # Respect the user's choice not to have colors.
438
+ if use_colors is None and 'NO_COLOR' in os.environ:
439
+ # For details on this see https://no-color.org/.
440
+ use_colors = False
441
+ # Try to enable Windows native ANSI support or Colorama?
442
+ if (use_colors or use_colors is None) and on_windows():
443
+ # This can fail, in which case ANSI escape sequences would end
444
+ # up being printed to the terminal in raw form. This is very
445
+ # user hostile, so to avoid this happening we disable color
446
+ # support on failure.
447
+ use_colors = enable_ansi_support()
448
+ # When auto detection is enabled, and so far we encountered no
449
+ # reason to disable color support, then we will enable color
450
+ # support if 'stream' is connected to a terminal.
451
+ if use_colors is None:
452
+ use_colors = terminal_supports_colors(stream)
453
+ # Create a stream handler and make sure to preserve any filters
454
+ # the current handler may have (if an existing handler is found).
455
+ filters = handler.filters if handler else None
456
+ if stream is sys.stderr:
457
+ handler = StandardErrorHandler()
458
+ else:
459
+ handler = logging.StreamHandler(stream)
460
+ handler.setLevel(level)
461
+ if filters:
462
+ handler.filters = filters
463
+ # Prepare the arguments to the formatter, allowing the caller to
464
+ # customize the values of `fmt', `datefmt' and `style' as desired.
465
+ formatter_options = dict(fmt=kw.get('fmt'), datefmt=kw.get('datefmt'))
466
+ # Only pass the `style' argument to the formatter when the caller
467
+ # provided an alternative logging format style. This prevents
468
+ # TypeError exceptions on Python versions before 3.2.
469
+ if style != DEFAULT_FORMAT_STYLE:
470
+ formatter_options['style'] = style
471
+ # Come up with a default log format?
472
+ if not formatter_options['fmt']:
473
+ # Use the log format defined by the environment variable
474
+ # $COLOREDLOGS_LOG_FORMAT or fall back to the default.
475
+ formatter_options['fmt'] = os.environ.get('COLOREDLOGS_LOG_FORMAT') or DEFAULT_LOG_FORMAT
476
+ # If the caller didn't specify a date/time format we'll use the format
477
+ # defined by the environment variable $COLOREDLOGS_DATE_FORMAT (or fall
478
+ # back to the default).
479
+ if not formatter_options['datefmt']:
480
+ formatter_options['datefmt'] = os.environ.get('COLOREDLOGS_DATE_FORMAT') or DEFAULT_DATE_FORMAT
481
+ # Python's logging module shows milliseconds by default through special
482
+ # handling in the logging.Formatter.formatTime() method [1]. Because
483
+ # coloredlogs always defines a `datefmt' it bypasses this special
484
+ # handling, which is fine because ever since publishing coloredlogs
485
+ # I've never needed millisecond precision ;-). However there are users
486
+ # of coloredlogs that do want milliseconds to be shown [2] so we
487
+ # provide a shortcut to make it easy.
488
+ #
489
+ # [1] https://stackoverflow.com/questions/6290739/python-logging-use-milliseconds-in-time-format
490
+ # [2] https://github.com/xolox/python-coloredlogs/issues/16
491
+ if kw.get('milliseconds'):
492
+ parser = FormatStringParser(style=style)
493
+ if not (parser.contains_field(formatter_options['fmt'], 'msecs')
494
+ or '%f' in formatter_options['datefmt']):
495
+ pattern = parser.get_pattern('asctime')
496
+ replacements = {'%': '%(msecs)03d', '{': '{msecs:03}', '$': '${msecs}'}
497
+ formatter_options['fmt'] = pattern.sub(
498
+ r'\g<0>,' + replacements[style],
499
+ formatter_options['fmt'],
500
+ )
501
+ # Do we need to make %(hostname) available to the formatter?
502
+ HostNameFilter.install(
503
+ fmt=formatter_options['fmt'],
504
+ handler=handler,
505
+ style=style,
506
+ use_chroot=kw.get('use_chroot', True),
507
+ )
508
+ # Do we need to make %(programname) available to the formatter?
509
+ ProgramNameFilter.install(
510
+ fmt=formatter_options['fmt'],
511
+ handler=handler,
512
+ programname=kw.get('programname'),
513
+ style=style,
514
+ )
515
+ # Do we need to make %(username) available to the formatter?
516
+ UserNameFilter.install(
517
+ fmt=formatter_options['fmt'],
518
+ handler=handler,
519
+ username=kw.get('username'),
520
+ style=style,
521
+ )
522
+ # Inject additional formatter arguments specific to ColoredFormatter?
523
+ if use_colors:
524
+ for name, environment_name in (('field_styles', 'COLOREDLOGS_FIELD_STYLES'),
525
+ ('level_styles', 'COLOREDLOGS_LEVEL_STYLES')):
526
+ value = kw.get(name)
527
+ if value is None:
528
+ # If no styles have been specified we'll fall back
529
+ # to the styles defined by the environment variable.
530
+ environment_value = os.environ.get(environment_name)
531
+ if environment_value is not None:
532
+ value = parse_encoded_styles(environment_value)
533
+ if value is not None:
534
+ formatter_options[name] = value
535
+ # Create a (possibly colored) formatter.
536
+ formatter_type = ColoredFormatter if use_colors else BasicFormatter
537
+ handler.setFormatter(formatter_type(**formatter_options))
538
+ # Adjust the level of the selected logger.
539
+ adjust_level(logger, level)
540
+ # Install the stream handler.
541
+ logger.addHandler(handler)
542
+
543
+
544
+ def check_style(value):
545
+ """
546
+ Validate a logging format style.
547
+
548
+ :param value: The logging format style to validate (any value).
549
+ :returns: The logging format character (a string of one character).
550
+ :raises: :exc:`~exceptions.ValueError` when the given style isn't supported.
551
+
552
+ This function accepts the logging format styles ``%``, ``{`` and ``$``.
553
+ """
554
+ if value not in FORMAT_STYLE_PATTERNS:
555
+ msg = "Unsupported logging format style! (%r)"
556
+ raise ValueError(format(msg, value))
557
+ return value
558
+
559
+
560
+ def increase_verbosity():
561
+ """
562
+ Increase the verbosity of the root handler by one defined level.
563
+
564
+ Understands custom logging levels like defined by my ``verboselogs``
565
+ module.
566
+ """
567
+ defined_levels = sorted(set(find_defined_levels().values()))
568
+ current_index = defined_levels.index(get_level())
569
+ selected_index = max(0, current_index - 1)
570
+ set_level(defined_levels[selected_index])
571
+
572
+
573
+ def decrease_verbosity():
574
+ """
575
+ Decrease the verbosity of the root handler by one defined level.
576
+
577
+ Understands custom logging levels like defined by my ``verboselogs``
578
+ module.
579
+ """
580
+ defined_levels = sorted(set(find_defined_levels().values()))
581
+ current_index = defined_levels.index(get_level())
582
+ selected_index = min(current_index + 1, len(defined_levels) - 1)
583
+ set_level(defined_levels[selected_index])
584
+
585
+
586
+ def is_verbose():
587
+ """
588
+ Check whether the log level of the root handler is set to a verbose level.
589
+
590
+ :returns: ``True`` if the root handler is verbose, ``False`` if not.
591
+ """
592
+ return get_level() < DEFAULT_LOG_LEVEL
593
+
594
+
595
+ def get_level():
596
+ """
597
+ Get the logging level of the root handler.
598
+
599
+ :returns: The logging level of the root handler (an integer) or
600
+ :data:`DEFAULT_LOG_LEVEL` (if no root handler exists).
601
+ """
602
+ handler, logger = find_handler(logging.getLogger(), match_stream_handler)
603
+ return handler.level if handler else DEFAULT_LOG_LEVEL
604
+
605
+
606
+ def set_level(level):
607
+ """
608
+ Set the logging level of the root handler.
609
+
610
+ :param level: The logging level to filter on (an integer or string).
611
+
612
+ If no root handler exists yet this automatically calls :func:`install()`.
613
+ """
614
+ handler, logger = find_handler(logging.getLogger(), match_stream_handler)
615
+ if handler and logger:
616
+ # Change the level of the existing handler.
617
+ handler.setLevel(level_to_number(level))
618
+ # Adjust the level of the selected logger.
619
+ adjust_level(logger, level)
620
+ else:
621
+ # Create a new handler with the given level.
622
+ install(level=level)
623
+
624
+
625
+ def adjust_level(logger, level):
626
+ """
627
+ Increase a logger's verbosity up to the requested level.
628
+
629
+ :param logger: The logger to change (a :class:`~logging.Logger` object).
630
+ :param level: The log level to enable (a string or number).
631
+
632
+ This function is used by functions like :func:`install()`,
633
+ :func:`increase_verbosity()` and :func:`.enable_system_logging()` to adjust
634
+ a logger's level so that log messages up to the requested log level are
635
+ propagated to the configured output handler(s).
636
+
637
+ It uses :func:`logging.Logger.getEffectiveLevel()` to check whether
638
+ `logger` propagates or swallows log messages of the requested `level` and
639
+ sets the logger's level to the requested level if it would otherwise
640
+ swallow log messages.
641
+
642
+ Effectively this function will "widen the scope of logging" when asked to
643
+ do so but it will never "narrow the scope of logging". This is because I am
644
+ convinced that filtering of log messages should (primarily) be decided by
645
+ handlers.
646
+ """
647
+ level = level_to_number(level)
648
+ if logger.getEffectiveLevel() > level:
649
+ logger.setLevel(level)
650
+
651
+
652
+ def find_defined_levels():
653
+ """
654
+ Find the defined logging levels.
655
+
656
+ :returns: A dictionary with level names as keys and integers as values.
657
+
658
+ Here's what the result looks like by default (when
659
+ no custom levels or level names have been defined):
660
+
661
+ >>> find_defined_levels()
662
+ {'NOTSET': 0,
663
+ 'DEBUG': 10,
664
+ 'INFO': 20,
665
+ 'WARN': 30,
666
+ 'WARNING': 30,
667
+ 'ERROR': 40,
668
+ 'FATAL': 50,
669
+ 'CRITICAL': 50}
670
+ """
671
+ defined_levels = {}
672
+ for name in dir(logging):
673
+ if name.isupper():
674
+ value = getattr(logging, name)
675
+ if isinstance(value, int):
676
+ defined_levels[name] = value
677
+ return defined_levels
678
+
679
+
680
+ def level_to_number(value):
681
+ """
682
+ Coerce a logging level name to a number.
683
+
684
+ :param value: A logging level (integer or string).
685
+ :returns: The number of the log level (an integer).
686
+
687
+ This function translates log level names into their numeric values..
688
+ """
689
+ if is_string(value):
690
+ try:
691
+ defined_levels = find_defined_levels()
692
+ value = defined_levels[value.upper()]
693
+ except KeyError:
694
+ # Don't fail on unsupported log levels.
695
+ value = DEFAULT_LOG_LEVEL
696
+ return value
697
+
698
+
699
+ def find_level_aliases():
700
+ """
701
+ Find log level names which are aliases of each other.
702
+
703
+ :returns: A dictionary that maps aliases to their canonical name.
704
+
705
+ .. note:: Canonical names are chosen to be the alias with the longest
706
+ string length so that e.g. ``WARN`` is an alias for ``WARNING``
707
+ instead of the other way around.
708
+
709
+ Here's what the result looks like by default (when
710
+ no custom levels or level names have been defined):
711
+
712
+ >>> from coloredlogs import find_level_aliases
713
+ >>> find_level_aliases()
714
+ {'WARN': 'WARNING', 'FATAL': 'CRITICAL'}
715
+ """
716
+ mapping = collections.defaultdict(list)
717
+ for name, value in find_defined_levels().items():
718
+ mapping[value].append(name)
719
+ aliases = {}
720
+ for value, names in mapping.items():
721
+ if len(names) > 1:
722
+ names = sorted(names, key=lambda n: len(n))
723
+ canonical_name = names.pop()
724
+ for alias in names:
725
+ aliases[alias] = canonical_name
726
+ return aliases
727
+
728
+
729
+ def parse_encoded_styles(text, normalize_key=None):
730
+ """
731
+ Parse text styles encoded in a string into a nested data structure.
732
+
733
+ :param text: The encoded styles (a string).
734
+ :returns: A dictionary in the structure of the :data:`DEFAULT_FIELD_STYLES`
735
+ and :data:`DEFAULT_LEVEL_STYLES` dictionaries.
736
+
737
+ Here's an example of how this function works:
738
+
739
+ >>> from coloredlogs import parse_encoded_styles
740
+ >>> from pprint import pprint
741
+ >>> encoded_styles = 'debug=green;warning=yellow;error=red;critical=red,bold'
742
+ >>> pprint(parse_encoded_styles(encoded_styles))
743
+ {'debug': {'color': 'green'},
744
+ 'warning': {'color': 'yellow'},
745
+ 'error': {'color': 'red'},
746
+ 'critical': {'bold': True, 'color': 'red'}}
747
+ """
748
+ parsed_styles = {}
749
+ for assignment in split(text, ';'):
750
+ name, _, styles = assignment.partition('=')
751
+ target = parsed_styles.setdefault(name, {})
752
+ for token in split(styles, ','):
753
+ # When this code was originally written, setting background colors
754
+ # wasn't supported yet, so there was no need to disambiguate
755
+ # between the text color and background color. This explains why
756
+ # a color name or number implies setting the text color (for
757
+ # backwards compatibility).
758
+ if token.isdigit():
759
+ target['color'] = int(token)
760
+ elif token in ANSI_COLOR_CODES:
761
+ target['color'] = token
762
+ elif '=' in token:
763
+ name, _, value = token.partition('=')
764
+ if name in ('color', 'background'):
765
+ if value.isdigit():
766
+ target[name] = int(value)
767
+ elif value in ANSI_COLOR_CODES:
768
+ target[name] = value
769
+ else:
770
+ target[token] = True
771
+ return parsed_styles
772
+
773
+
774
+ def find_hostname(use_chroot=True):
775
+ """
776
+ Find the host name to include in log messages.
777
+
778
+ :param use_chroot: Use the name of the chroot when inside a chroot?
779
+ (boolean, defaults to :data:`True`)
780
+ :returns: A suitable host name (a string).
781
+
782
+ Looks for :data:`CHROOT_FILES` that have a nonempty first line (taken to be
783
+ the chroot name). If none are found then :func:`socket.gethostname()` is
784
+ used as a fall back.
785
+ """
786
+ for chroot_file in CHROOT_FILES:
787
+ try:
788
+ with open(chroot_file) as handle:
789
+ first_line = next(handle)
790
+ name = first_line.strip()
791
+ if name:
792
+ return name
793
+ except Exception:
794
+ pass
795
+ return socket.gethostname()
796
+
797
+
798
+ def find_program_name():
799
+ """
800
+ Select a suitable program name to embed in log messages.
801
+
802
+ :returns: One of the following strings (in decreasing order of preference):
803
+
804
+ 1. The base name of the currently running Python program or
805
+ script (based on the value at index zero of :data:`sys.argv`).
806
+ 2. The base name of the Python executable (based on
807
+ :data:`sys.executable`).
808
+ 3. The string 'python'.
809
+ """
810
+ # Gotcha: sys.argv[0] is '-c' if Python is started with the -c option.
811
+ return ((os.path.basename(sys.argv[0]) if sys.argv and sys.argv[0] != '-c' else '')
812
+ or (os.path.basename(sys.executable) if sys.executable else '')
813
+ or 'python')
814
+
815
+
816
+ def find_username():
817
+ """
818
+ Find the username to include in log messages.
819
+
820
+ :returns: A suitable username (a string).
821
+
822
+ On UNIX systems this uses the :mod:`pwd` module which means ``root`` will
823
+ be reported when :man:`sudo` is used (as it should). If this fails (for
824
+ example on Windows) then :func:`getpass.getuser()` is used as a fall back.
825
+ """
826
+ try:
827
+ import pwd
828
+ uid = os.getuid()
829
+ entry = pwd.getpwuid(uid)
830
+ return entry.pw_name
831
+ except Exception:
832
+ import getpass
833
+ return getpass.getuser()
834
+
835
+
836
+ def replace_handler(logger, match_handler, reconfigure):
837
+ """
838
+ Prepare to replace a handler.
839
+
840
+ :param logger: Refer to :func:`find_handler()`.
841
+ :param match_handler: Refer to :func:`find_handler()`.
842
+ :param reconfigure: :data:`True` if an existing handler should be replaced,
843
+ :data:`False` otherwise.
844
+ :returns: A tuple of two values:
845
+
846
+ 1. The matched :class:`~logging.Handler` object or :data:`None`
847
+ if no handler was matched.
848
+ 2. The :class:`~logging.Logger` to which the matched handler was
849
+ attached or the logger given to :func:`replace_handler()`.
850
+ """
851
+ handler, other_logger = find_handler(logger, match_handler)
852
+ if handler and other_logger and reconfigure:
853
+ # Remove the existing handler from the logger that its attached to
854
+ # so that we can install a new handler that behaves differently.
855
+ other_logger.removeHandler(handler)
856
+ # Switch to the logger that the existing handler was attached to so
857
+ # that reconfiguration doesn't narrow the scope of logging.
858
+ logger = other_logger
859
+ return handler, logger
860
+
861
+
862
+ def find_handler(logger, match_handler):
863
+ """
864
+ Find a (specific type of) handler in the propagation tree of a logger.
865
+
866
+ :param logger: The logger to check (a :class:`~logging.Logger` object).
867
+ :param match_handler: A callable that receives a :class:`~logging.Handler`
868
+ object and returns :data:`True` to match a handler or
869
+ :data:`False` to skip that handler and continue
870
+ searching for a match.
871
+ :returns: A tuple of two values:
872
+
873
+ 1. The matched :class:`~logging.Handler` object or :data:`None`
874
+ if no handler was matched.
875
+ 2. The :class:`~logging.Logger` object to which the handler is
876
+ attached or :data:`None` if no handler was matched.
877
+
878
+ This function finds a logging handler (of the given type) attached to a
879
+ logger or one of its parents (see :func:`walk_propagation_tree()`). It uses
880
+ the undocumented :class:`~logging.Logger.handlers` attribute to find
881
+ handlers attached to a logger, however it won't raise an exception if the
882
+ attribute isn't available. The advantages of this approach are:
883
+
884
+ - This works regardless of whether :mod:`coloredlogs` attached the handler
885
+ or other Python code attached the handler.
886
+
887
+ - This will correctly recognize the situation where the given logger has no
888
+ handlers but :attr:`~logging.Logger.propagate` is enabled and the logger
889
+ has a parent logger that does have a handler attached.
890
+ """
891
+ for logger in walk_propagation_tree(logger):
892
+ for handler in getattr(logger, 'handlers', []):
893
+ if match_handler(handler):
894
+ return handler, logger
895
+ return None, None
896
+
897
+
898
+ def match_stream_handler(handler, streams=[]):
899
+ """
900
+ Identify stream handlers writing to the given streams(s).
901
+
902
+ :param handler: The :class:`~logging.Handler` class to check.
903
+ :param streams: A sequence of streams to match (defaults to matching
904
+ :data:`~sys.stdout` and :data:`~sys.stderr`).
905
+ :returns: :data:`True` if the handler is a :class:`~logging.StreamHandler`
906
+ logging to the given stream(s), :data:`False` otherwise.
907
+
908
+ This function can be used as a callback for :func:`find_handler()`.
909
+ """
910
+ return (isinstance(handler, logging.StreamHandler)
911
+ and getattr(handler, 'stream') in (streams or (sys.stdout, sys.stderr)))
912
+
913
+
914
+ def walk_propagation_tree(logger):
915
+ """
916
+ Walk through the propagation hierarchy of the given logger.
917
+
918
+ :param logger: The logger whose hierarchy to walk (a
919
+ :class:`~logging.Logger` object).
920
+ :returns: A generator of :class:`~logging.Logger` objects.
921
+
922
+ .. note:: This uses the undocumented :class:`logging.Logger.parent`
923
+ attribute to find higher level loggers, however it won't
924
+ raise an exception if the attribute isn't available.
925
+ """
926
+ while isinstance(logger, logging.Logger):
927
+ # Yield the logger to our caller.
928
+ yield logger
929
+ # Check if the logger has propagation enabled.
930
+ if logger.propagate:
931
+ # Continue with the parent logger. We use getattr() because the
932
+ # `parent' attribute isn't documented so properly speaking we
933
+ # shouldn't break if it's not available.
934
+ logger = getattr(logger, 'parent', None)
935
+ else:
936
+ # The propagation chain stops here.
937
+ logger = None
938
+
939
+
940
+ class BasicFormatter(logging.Formatter):
941
+
942
+ """
943
+ Log :class:`~logging.Formatter` that supports ``%f`` for millisecond formatting.
944
+
945
+ This class extends :class:`~logging.Formatter` to enable the use of ``%f``
946
+ for millisecond formatting in date/time strings, to allow for the type of
947
+ flexibility requested in issue `#45`_.
948
+
949
+ .. _#45: https://github.com/xolox/python-coloredlogs/issues/45
950
+ """
951
+
952
+ def formatTime(self, record, datefmt=None):
953
+ """
954
+ Format the date/time of a log record.
955
+
956
+ :param record: A :class:`~logging.LogRecord` object.
957
+ :param datefmt: A date/time format string (defaults to :data:`DEFAULT_DATE_FORMAT`).
958
+ :returns: The formatted date/time (a string).
959
+
960
+ This method overrides :func:`~logging.Formatter.formatTime()` to set
961
+ `datefmt` to :data:`DEFAULT_DATE_FORMAT` when the caller hasn't
962
+ specified a date format.
963
+
964
+ When `datefmt` contains the token ``%f`` it will be replaced by the
965
+ value of ``%(msecs)03d`` (refer to issue `#45`_ for use cases).
966
+ """
967
+ # The default value of the following argument is defined here so
968
+ # that Sphinx doesn't embed the default value in the generated
969
+ # documentation (because the result is awkward to read).
970
+ datefmt = datefmt or DEFAULT_DATE_FORMAT
971
+ # Replace %f with the value of %(msecs)03d.
972
+ if '%f' in datefmt:
973
+ datefmt = datefmt.replace('%f', '%03d' % record.msecs)
974
+ # Delegate the actual date/time formatting to the base formatter.
975
+ return logging.Formatter.formatTime(self, record, datefmt)
976
+
977
+
978
+ class ColoredFormatter(BasicFormatter):
979
+
980
+ """
981
+ Log :class:`~logging.Formatter` that uses `ANSI escape sequences`_ to create colored logs.
982
+
983
+ :class:`ColoredFormatter` inherits from :class:`BasicFormatter` to enable
984
+ the use of ``%f`` for millisecond formatting in date/time strings.
985
+
986
+ .. note:: If you want to use :class:`ColoredFormatter` on Windows then you
987
+ need to call :func:`~humanfriendly.terminal.enable_ansi_support()`.
988
+ This is done for you when you call :func:`coloredlogs.install()`.
989
+ """
990
+
991
+ def __init__(self, fmt=None, datefmt=None, style=DEFAULT_FORMAT_STYLE, level_styles=None, field_styles=None):
992
+ """
993
+ Initialize a :class:`ColoredFormatter` object.
994
+
995
+ :param fmt: A log format string (defaults to :data:`DEFAULT_LOG_FORMAT`).
996
+ :param datefmt: A date/time format string (defaults to :data:`None`,
997
+ but see the documentation of
998
+ :func:`BasicFormatter.formatTime()`).
999
+ :param style: One of the characters ``%``, ``{`` or ``$`` (defaults to
1000
+ :data:`DEFAULT_FORMAT_STYLE`)
1001
+ :param level_styles: A dictionary with custom level styles
1002
+ (defaults to :data:`DEFAULT_LEVEL_STYLES`).
1003
+ :param field_styles: A dictionary with custom field styles
1004
+ (defaults to :data:`DEFAULT_FIELD_STYLES`).
1005
+ :raises: Refer to :func:`check_style()`.
1006
+
1007
+ This initializer uses :func:`colorize_format()` to inject ANSI escape
1008
+ sequences in the log format string before it is passed to the
1009
+ initializer of the base class.
1010
+ """
1011
+ self.nn = NameNormalizer()
1012
+ # The default values of the following arguments are defined here so
1013
+ # that Sphinx doesn't embed the default values in the generated
1014
+ # documentation (because the result is awkward to read).
1015
+ fmt = fmt or DEFAULT_LOG_FORMAT
1016
+ self.level_styles = self.nn.normalize_keys(DEFAULT_LEVEL_STYLES if level_styles is None else level_styles)
1017
+ self.field_styles = self.nn.normalize_keys(DEFAULT_FIELD_STYLES if field_styles is None else field_styles)
1018
+ # Rewrite the format string to inject ANSI escape sequences.
1019
+ kw = dict(fmt=self.colorize_format(fmt, style), datefmt=datefmt)
1020
+ # If we were given a non-default logging format style we pass it on
1021
+ # to our superclass. At this point check_style() will have already
1022
+ # complained that the use of alternative logging format styles
1023
+ # requires Python 3.2 or newer.
1024
+ if style != DEFAULT_FORMAT_STYLE:
1025
+ kw['style'] = style
1026
+ # Initialize the superclass with the rewritten format string.
1027
+ logging.Formatter.__init__(self, **kw)
1028
+
1029
+ def colorize_format(self, fmt, style=DEFAULT_FORMAT_STYLE):
1030
+ """
1031
+ Rewrite a logging format string to inject ANSI escape sequences.
1032
+
1033
+ :param fmt: The log format string.
1034
+ :param style: One of the characters ``%``, ``{`` or ``$`` (defaults to
1035
+ :data:`DEFAULT_FORMAT_STYLE`).
1036
+ :returns: The logging format string with ANSI escape sequences.
1037
+
1038
+ This method takes a logging format string like the ones you give to
1039
+ :class:`logging.Formatter` and processes it as follows:
1040
+
1041
+ 1. First the logging format string is separated into formatting
1042
+ directives versus surrounding text (according to the given `style`).
1043
+
1044
+ 2. Then formatting directives and surrounding text are grouped
1045
+ based on whitespace delimiters (in the surrounding text).
1046
+
1047
+ 3. For each group styling is selected as follows:
1048
+
1049
+ 1. If the group contains a single formatting directive that has
1050
+ a style defined then the whole group is styled accordingly.
1051
+
1052
+ 2. If the group contains multiple formatting directives that
1053
+ have styles defined then each formatting directive is styled
1054
+ individually and surrounding text isn't styled.
1055
+
1056
+ As an example consider the default log format (:data:`DEFAULT_LOG_FORMAT`)::
1057
+
1058
+ %(asctime)s %(hostname)s %(name)s[%(process)d] %(levelname)s %(message)s
1059
+
1060
+ The default field styles (:data:`DEFAULT_FIELD_STYLES`) define a style for the
1061
+ `name` field but not for the `process` field, however because both fields
1062
+ are part of the same whitespace delimited token they'll be highlighted
1063
+ together in the style defined for the `name` field.
1064
+ """
1065
+ result = []
1066
+ parser = FormatStringParser(style=style)
1067
+ for group in parser.get_grouped_pairs(fmt):
1068
+ applicable_styles = [self.nn.get(self.field_styles, token.name) for token in group if token.name]
1069
+ if sum(map(bool, applicable_styles)) == 1:
1070
+ # If exactly one (1) field style is available for the group of
1071
+ # tokens then all of the tokens will be styled the same way.
1072
+ # This provides a limited form of backwards compatibility with
1073
+ # the (intended) behavior of coloredlogs before the release of
1074
+ # version 10.
1075
+ result.append(ansi_wrap(
1076
+ ''.join(token.text for token in group),
1077
+ **next(s for s in applicable_styles if s)
1078
+ ))
1079
+ else:
1080
+ for token in group:
1081
+ text = token.text
1082
+ if token.name:
1083
+ field_styles = self.nn.get(self.field_styles, token.name)
1084
+ if field_styles:
1085
+ text = ansi_wrap(text, **field_styles)
1086
+ result.append(text)
1087
+ return ''.join(result)
1088
+
1089
+ def format(self, record):
1090
+ """
1091
+ Apply level-specific styling to log records.
1092
+
1093
+ :param record: A :class:`~logging.LogRecord` object.
1094
+ :returns: The result of :func:`logging.Formatter.format()`.
1095
+
1096
+ This method injects ANSI escape sequences that are specific to the
1097
+ level of each log record (because such logic cannot be expressed in the
1098
+ syntax of a log format string). It works by making a copy of the log
1099
+ record, changing the `msg` field inside the copy and passing the copy
1100
+ into the :func:`~logging.Formatter.format()` method of the base
1101
+ class.
1102
+ """
1103
+ style = self.nn.get(self.level_styles, record.levelname)
1104
+ # After the introduction of the `Empty' class it was reported in issue
1105
+ # 33 that format() can be called when `Empty' has already been garbage
1106
+ # collected. This explains the (otherwise rather out of place) `Empty
1107
+ # is not None' check in the following `if' statement. The reasoning
1108
+ # here is that it's much better to log a message without formatting
1109
+ # then to raise an exception ;-).
1110
+ #
1111
+ # For more details refer to issue 33 on GitHub:
1112
+ # https://github.com/xolox/python-coloredlogs/issues/33
1113
+ if style and Empty is not None:
1114
+ # Due to the way that Python's logging module is structured and
1115
+ # documented the only (IMHO) clean way to customize its behavior is
1116
+ # to change incoming LogRecord objects before they get to the base
1117
+ # formatter. However we don't want to break other formatters and
1118
+ # handlers, so we copy the log record.
1119
+ #
1120
+ # In the past this used copy.copy() but as reported in issue 29
1121
+ # (which is reproducible) this can cause deadlocks. The following
1122
+ # Python voodoo is intended to accomplish the same thing as
1123
+ # copy.copy() without all of the generalization and overhead that
1124
+ # we don't need for our -very limited- use case.
1125
+ #
1126
+ # For more details refer to issue 29 on GitHub:
1127
+ # https://github.com/xolox/python-coloredlogs/issues/29
1128
+ copy = Empty()
1129
+ copy.__class__ = record.__class__
1130
+ copy.__dict__.update(record.__dict__)
1131
+ copy.msg = ansi_wrap(coerce_string(record.msg), **style)
1132
+ record = copy
1133
+ # Delegate the remaining formatting to the base formatter.
1134
+ return logging.Formatter.format(self, record)
1135
+
1136
+
1137
+ class Empty(object):
1138
+ """An empty class used to copy :class:`~logging.LogRecord` objects without reinitializing them."""
1139
+
1140
+
1141
+ class HostNameFilter(logging.Filter):
1142
+
1143
+ """
1144
+ Log filter to enable the ``%(hostname)s`` format.
1145
+
1146
+ Python's :mod:`logging` module doesn't expose the system's host name while
1147
+ I consider this to be a valuable addition. Fortunately it's very easy to
1148
+ expose additional fields in format strings: :func:`filter()` simply sets
1149
+ the ``hostname`` attribute of each :class:`~logging.LogRecord` object it
1150
+ receives and this is enough to enable the use of the ``%(hostname)s``
1151
+ expression in format strings.
1152
+
1153
+ You can install this log filter as follows::
1154
+
1155
+ >>> import coloredlogs, logging
1156
+ >>> handler = logging.StreamHandler()
1157
+ >>> handler.addFilter(coloredlogs.HostNameFilter())
1158
+ >>> handler.setFormatter(logging.Formatter('[%(hostname)s] %(message)s'))
1159
+ >>> logger = logging.getLogger()
1160
+ >>> logger.addHandler(handler)
1161
+ >>> logger.setLevel(logging.INFO)
1162
+ >>> logger.info("Does it work?")
1163
+ [peter-macbook] Does it work?
1164
+
1165
+ Of course :func:`coloredlogs.install()` does all of this for you :-).
1166
+ """
1167
+
1168
+ @classmethod
1169
+ def install(cls, handler, fmt=None, use_chroot=True, style=DEFAULT_FORMAT_STYLE):
1170
+ """
1171
+ Install the :class:`HostNameFilter` on a log handler (only if needed).
1172
+
1173
+ :param fmt: The log format string to check for ``%(hostname)``.
1174
+ :param style: One of the characters ``%``, ``{`` or ``$`` (defaults to
1175
+ :data:`DEFAULT_FORMAT_STYLE`).
1176
+ :param handler: The logging handler on which to install the filter.
1177
+ :param use_chroot: Refer to :func:`find_hostname()`.
1178
+
1179
+ If `fmt` is given the filter will only be installed if `fmt` uses the
1180
+ ``hostname`` field. If `fmt` is not given the filter is installed
1181
+ unconditionally.
1182
+ """
1183
+ if fmt:
1184
+ parser = FormatStringParser(style=style)
1185
+ if not parser.contains_field(fmt, 'hostname'):
1186
+ return
1187
+ handler.addFilter(cls(use_chroot))
1188
+
1189
+ def __init__(self, use_chroot=True):
1190
+ """
1191
+ Initialize a :class:`HostNameFilter` object.
1192
+
1193
+ :param use_chroot: Refer to :func:`find_hostname()`.
1194
+ """
1195
+ self.hostname = find_hostname(use_chroot)
1196
+
1197
+ def filter(self, record):
1198
+ """Set each :class:`~logging.LogRecord`'s `hostname` field."""
1199
+ # Modify the record.
1200
+ record.hostname = self.hostname
1201
+ # Don't filter the record.
1202
+ return 1
1203
+
1204
+
1205
+ class ProgramNameFilter(logging.Filter):
1206
+
1207
+ """
1208
+ Log filter to enable the ``%(programname)s`` format.
1209
+
1210
+ Python's :mod:`logging` module doesn't expose the name of the currently
1211
+ running program while I consider this to be a useful addition. Fortunately
1212
+ it's very easy to expose additional fields in format strings:
1213
+ :func:`filter()` simply sets the ``programname`` attribute of each
1214
+ :class:`~logging.LogRecord` object it receives and this is enough to enable
1215
+ the use of the ``%(programname)s`` expression in format strings.
1216
+
1217
+ Refer to :class:`HostNameFilter` for an example of how to manually install
1218
+ these log filters.
1219
+ """
1220
+
1221
+ @classmethod
1222
+ def install(cls, handler, fmt, programname=None, style=DEFAULT_FORMAT_STYLE):
1223
+ """
1224
+ Install the :class:`ProgramNameFilter` (only if needed).
1225
+
1226
+ :param fmt: The log format string to check for ``%(programname)``.
1227
+ :param style: One of the characters ``%``, ``{`` or ``$`` (defaults to
1228
+ :data:`DEFAULT_FORMAT_STYLE`).
1229
+ :param handler: The logging handler on which to install the filter.
1230
+ :param programname: Refer to :func:`__init__()`.
1231
+
1232
+ If `fmt` is given the filter will only be installed if `fmt` uses the
1233
+ ``programname`` field. If `fmt` is not given the filter is installed
1234
+ unconditionally.
1235
+ """
1236
+ if fmt:
1237
+ parser = FormatStringParser(style=style)
1238
+ if not parser.contains_field(fmt, 'programname'):
1239
+ return
1240
+ handler.addFilter(cls(programname))
1241
+
1242
+ def __init__(self, programname=None):
1243
+ """
1244
+ Initialize a :class:`ProgramNameFilter` object.
1245
+
1246
+ :param programname: The program name to use (defaults to the result of
1247
+ :func:`find_program_name()`).
1248
+ """
1249
+ self.programname = programname or find_program_name()
1250
+
1251
+ def filter(self, record):
1252
+ """Set each :class:`~logging.LogRecord`'s `programname` field."""
1253
+ # Modify the record.
1254
+ record.programname = self.programname
1255
+ # Don't filter the record.
1256
+ return 1
1257
+
1258
+
1259
+ class UserNameFilter(logging.Filter):
1260
+
1261
+ """
1262
+ Log filter to enable the ``%(username)s`` format.
1263
+
1264
+ Python's :mod:`logging` module doesn't expose the username of the currently
1265
+ logged in user as requested in `#76`_. Given that :class:`HostNameFilter`
1266
+ and :class:`ProgramNameFilter` are already provided by `coloredlogs` it
1267
+ made sense to provide :class:`UserNameFilter` as well.
1268
+
1269
+ Refer to :class:`HostNameFilter` for an example of how to manually install
1270
+ these log filters.
1271
+
1272
+ .. _#76: https://github.com/xolox/python-coloredlogs/issues/76
1273
+ """
1274
+
1275
+ @classmethod
1276
+ def install(cls, handler, fmt, username=None, style=DEFAULT_FORMAT_STYLE):
1277
+ """
1278
+ Install the :class:`UserNameFilter` (only if needed).
1279
+
1280
+ :param fmt: The log format string to check for ``%(username)``.
1281
+ :param style: One of the characters ``%``, ``{`` or ``$`` (defaults to
1282
+ :data:`DEFAULT_FORMAT_STYLE`).
1283
+ :param handler: The logging handler on which to install the filter.
1284
+ :param username: Refer to :func:`__init__()`.
1285
+
1286
+ If `fmt` is given the filter will only be installed if `fmt` uses the
1287
+ ``username`` field. If `fmt` is not given the filter is installed
1288
+ unconditionally.
1289
+ """
1290
+ if fmt:
1291
+ parser = FormatStringParser(style=style)
1292
+ if not parser.contains_field(fmt, 'username'):
1293
+ return
1294
+ handler.addFilter(cls(username))
1295
+
1296
+ def __init__(self, username=None):
1297
+ """
1298
+ Initialize a :class:`UserNameFilter` object.
1299
+
1300
+ :param username: The username to use (defaults to the
1301
+ result of :func:`find_username()`).
1302
+ """
1303
+ self.username = username or find_username()
1304
+
1305
+ def filter(self, record):
1306
+ """Set each :class:`~logging.LogRecord`'s `username` field."""
1307
+ # Modify the record.
1308
+ record.username = self.username
1309
+ # Don't filter the record.
1310
+ return 1
1311
+
1312
+
1313
+ class StandardErrorHandler(logging.StreamHandler):
1314
+
1315
+ """
1316
+ A :class:`~logging.StreamHandler` that gets the value of :data:`sys.stderr` for each log message.
1317
+
1318
+ The :class:`StandardErrorHandler` class enables `monkey patching of
1319
+ sys.stderr <https://github.com/xolox/python-coloredlogs/pull/31>`_. It's
1320
+ basically the same as the ``logging._StderrHandler`` class present in
1321
+ Python 3 but it will be available regardless of Python version. This
1322
+ handler is used by :func:`coloredlogs.install()` to improve compatibility
1323
+ with the Python standard library.
1324
+ """
1325
+
1326
+ def __init__(self, level=logging.NOTSET):
1327
+ """Initialize a :class:`StandardErrorHandler` object."""
1328
+ logging.Handler.__init__(self, level)
1329
+
1330
+ @property
1331
+ def stream(self):
1332
+ """Get the value of :data:`sys.stderr` (a file-like object)."""
1333
+ return sys.stderr
1334
+
1335
+
1336
+ class FormatStringParser(object):
1337
+
1338
+ """
1339
+ Shallow logging format string parser.
1340
+
1341
+ This class enables introspection and manipulation of logging format strings
1342
+ in the three styles supported by the :mod:`logging` module starting from
1343
+ Python 3.2 (``%``, ``{`` and ``$``).
1344
+ """
1345
+
1346
+ def __init__(self, style=DEFAULT_FORMAT_STYLE):
1347
+ """
1348
+ Initialize a :class:`FormatStringParser` object.
1349
+
1350
+ :param style: One of the characters ``%``, ``{`` or ``$`` (defaults to
1351
+ :data:`DEFAULT_FORMAT_STYLE`).
1352
+ :raises: Refer to :func:`check_style()`.
1353
+ """
1354
+ self.style = check_style(style)
1355
+ self.capturing_pattern = FORMAT_STYLE_PATTERNS[style]
1356
+ # Remove the capture group around the mapping key / field name.
1357
+ self.raw_pattern = self.capturing_pattern.replace(r'(\w+)', r'\w+')
1358
+ # After removing the inner capture group we add an outer capture group
1359
+ # to make the pattern suitable for simple tokenization using re.split().
1360
+ self.tokenize_pattern = re.compile('(%s)' % self.raw_pattern, re.VERBOSE)
1361
+ # Compile a regular expression for finding field names.
1362
+ self.name_pattern = re.compile(self.capturing_pattern, re.VERBOSE)
1363
+
1364
+ def contains_field(self, format_string, field_name):
1365
+ """
1366
+ Get the field names referenced by a format string.
1367
+
1368
+ :param format_string: The logging format string.
1369
+ :returns: A list of strings with field names.
1370
+ """
1371
+ return field_name in self.get_field_names(format_string)
1372
+
1373
+ def get_field_names(self, format_string):
1374
+ """
1375
+ Get the field names referenced by a format string.
1376
+
1377
+ :param format_string: The logging format string.
1378
+ :returns: A list of strings with field names.
1379
+ """
1380
+ return self.name_pattern.findall(format_string)
1381
+
1382
+ def get_grouped_pairs(self, format_string):
1383
+ """
1384
+ Group the results of :func:`get_pairs()` separated by whitespace.
1385
+
1386
+ :param format_string: The logging format string.
1387
+ :returns: A list of lists of :class:`FormatStringToken` objects.
1388
+ """
1389
+ # Step 1: Split simple tokens (without a name) into
1390
+ # their whitespace parts and non-whitespace parts.
1391
+ separated = []
1392
+ pattern = re.compile(r'(\s+)')
1393
+ for token in self.get_pairs(format_string):
1394
+ if token.name:
1395
+ separated.append(token)
1396
+ else:
1397
+ separated.extend(
1398
+ FormatStringToken(name=None, text=text)
1399
+ for text in pattern.split(token.text) if text
1400
+ )
1401
+ # Step 2: Group tokens together based on whitespace.
1402
+ current_group = []
1403
+ grouped_pairs = []
1404
+ for token in separated:
1405
+ if token.text.isspace():
1406
+ if current_group:
1407
+ grouped_pairs.append(current_group)
1408
+ grouped_pairs.append([token])
1409
+ current_group = []
1410
+ else:
1411
+ current_group.append(token)
1412
+ if current_group:
1413
+ grouped_pairs.append(current_group)
1414
+ return grouped_pairs
1415
+
1416
+ def get_pairs(self, format_string):
1417
+ """
1418
+ Tokenize a logging format string and extract field names from tokens.
1419
+
1420
+ :param format_string: The logging format string.
1421
+ :returns: A generator of :class:`FormatStringToken` objects.
1422
+ """
1423
+ for token in self.get_tokens(format_string):
1424
+ match = self.name_pattern.search(token)
1425
+ name = match.group(1) if match else None
1426
+ yield FormatStringToken(name=name, text=token)
1427
+
1428
+ def get_pattern(self, field_name):
1429
+ """
1430
+ Get a regular expression to match a formatting directive that references the given field name.
1431
+
1432
+ :param field_name: The name of the field to match (a string).
1433
+ :returns: A compiled regular expression object.
1434
+ """
1435
+ return re.compile(self.raw_pattern.replace(r'\w+', field_name), re.VERBOSE)
1436
+
1437
+ def get_tokens(self, format_string):
1438
+ """
1439
+ Tokenize a logging format string.
1440
+
1441
+ :param format_string: The logging format string.
1442
+ :returns: A list of strings with formatting directives separated from surrounding text.
1443
+ """
1444
+ return [t for t in self.tokenize_pattern.split(format_string) if t]
1445
+
1446
+
1447
+ class FormatStringToken(collections.namedtuple('FormatStringToken', 'text, name')):
1448
+
1449
+ """
1450
+ A named tuple for the results of :func:`FormatStringParser.get_pairs()`.
1451
+
1452
+ .. attribute:: name
1453
+
1454
+ The field name referenced in `text` (a string). If `text` doesn't
1455
+ contain a formatting directive this will be :data:`None`.
1456
+
1457
+ .. attribute:: text
1458
+
1459
+ The text extracted from the logging format string (a string).
1460
+ """
1461
+
1462
+
1463
+ class NameNormalizer(object):
1464
+
1465
+ """Responsible for normalizing field and level names."""
1466
+
1467
+ def __init__(self):
1468
+ """Initialize a :class:`NameNormalizer` object."""
1469
+ self.aliases = {k.lower(): v.lower() for k, v in find_level_aliases().items()}
1470
+
1471
+ def normalize_name(self, name):
1472
+ """
1473
+ Normalize a field or level name.
1474
+
1475
+ :param name: The field or level name (a string).
1476
+ :returns: The normalized name (a string).
1477
+
1478
+ Transforms all strings to lowercase and resolves level name aliases
1479
+ (refer to :func:`find_level_aliases()`) to their canonical name:
1480
+
1481
+ >>> from coloredlogs import NameNormalizer
1482
+ >>> from humanfriendly import format_table
1483
+ >>> nn = NameNormalizer()
1484
+ >>> sample_names = ['DEBUG', 'INFO', 'WARN', 'WARNING', 'ERROR', 'FATAL', 'CRITICAL']
1485
+ >>> print(format_table([(n, nn.normalize_name(n)) for n in sample_names]))
1486
+ -----------------------
1487
+ | DEBUG | debug |
1488
+ | INFO | info |
1489
+ | WARN | warning |
1490
+ | WARNING | warning |
1491
+ | ERROR | error |
1492
+ | FATAL | critical |
1493
+ | CRITICAL | critical |
1494
+ -----------------------
1495
+ """
1496
+ name = name.lower()
1497
+ if name in self.aliases:
1498
+ name = self.aliases[name]
1499
+ return name
1500
+
1501
+ def normalize_keys(self, value):
1502
+ """
1503
+ Normalize the keys of a dictionary using :func:`normalize_name()`.
1504
+
1505
+ :param value: The dictionary to normalize.
1506
+ :returns: A dictionary with normalized keys.
1507
+ """
1508
+ return {self.normalize_name(k): v for k, v in value.items()}
1509
+
1510
+ def get(self, normalized_dict, name):
1511
+ """
1512
+ Get a value from a dictionary after normalizing the key.
1513
+
1514
+ :param normalized_dict: A dictionary produced by :func:`normalize_keys()`.
1515
+ :param name: A key to normalize and get from the dictionary.
1516
+ :returns: The value of the normalized key (if any).
1517
+ """
1518
+ return normalized_dict.get(self.normalize_name(name))