Debian Codegraph @

docs/source/logging.rst

raw
1 Logging Handler
2 ===============
3
4 Rich supplies a :ref:`logging handler<logging>` which will format and colorize text written by Python's logging module.
5
6 Here's an example of how to set up a rich logger::
7
8 import logging
9 from rich.logging import RichHandler
10
11 FORMAT = "%(message)s"
12 logging.basicConfig(
13 level="NOTSET", format=FORMAT, datefmt="[%X]", handlers=[RichHandler()]
14 )
15
16 log = logging.getLogger("rich")
17 log.info("Hello, World!")
18
19 Rich logs won't render :ref:`console_markup` in logging by default as most libraries won't be aware of the need to escape literal square brackets, but you can enable it by setting ``markup=True`` on the handler. Alternatively you can enable it per log message by supplying the ``extra`` argument as follows::
20
21 log.error("[bold red blink]Server is shutting down![/]", extra={"markup": True})
22
23 Similarly, the highlighter may be overridden per log message::
24
25 log.error("123 will not be highlighted", extra={"highlighter": None})
26
27
28 Handle exceptions
29 -------------------
30
31 The :class:`~rich.logging.RichHandler` class may be configured to use Rich's :class:`~rich.traceback.Traceback` class to format exceptions, which provides more context than a built-in exception. To get beautiful exceptions in your logs set ``rich_tracebacks=True`` on the handler constructor::
32
33
34 import logging
35 from rich.logging import RichHandler
36
37 logging.basicConfig(
38 level="NOTSET",
39 format="%(message)s",
40 datefmt="[%X]",
41 handlers=[RichHandler(rich_tracebacks=True)]
42 )
43
44 log = logging.getLogger("rich")
45 try:
46 print(1 / 0)
47 except Exception:
48 log.exception("unable print!")
49
50
51 There are a number of other options you can use to configure logging output, see the :class:`~rich.logging.RichHandler` reference for details.
52
53 Suppressing Frames
54 ------------------
55
56 If you are working with a framework (click, django etc), you may only be interested in seeing the code from your own application within the traceback. You can exclude framework code by setting the `suppress` argument on `Traceback`, `install`, and `Console.print_exception`, which should be a list of modules or str paths.
57
58 Here's how you would exclude `click <https://click.palletsprojects.com/en/8.0.x/>`_ from Rich exceptions::
59
60 import click
61 import logging
62 from rich.logging import RichHandler
63
64 logging.basicConfig(
65 level="NOTSET",
66 format="%(message)s",
67 datefmt="[%X]",
68 handlers=[RichHandler(rich_tracebacks=True, tracebacks_suppress=[click])]
69 )
70
71 Suppressed frames will show the line and file only, without any code.