Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/flask/logging.py: 93%
28 statements
« prev ^ index » next coverage.py v7.3.2, created at 2023-12-09 07:17 +0000
« prev ^ index » next coverage.py v7.3.2, created at 2023-12-09 07:17 +0000
1from __future__ import annotations
3import logging
4import sys
5import typing as t
7from werkzeug.local import LocalProxy
9from .globals import request
11if t.TYPE_CHECKING: # pragma: no cover
12 from .sansio.app import App
15@LocalProxy
16def wsgi_errors_stream() -> t.TextIO:
17 """Find the most appropriate error stream for the application. If a request
18 is active, log to ``wsgi.errors``, otherwise use ``sys.stderr``.
20 If you configure your own :class:`logging.StreamHandler`, you may want to
21 use this for the stream. If you are using file or dict configuration and
22 can't import this directly, you can refer to it as
23 ``ext://flask.logging.wsgi_errors_stream``.
24 """
25 return request.environ["wsgi.errors"] if request else sys.stderr
28def has_level_handler(logger: logging.Logger) -> bool:
29 """Check if there is a handler in the logging chain that will handle the
30 given logger's :meth:`effective level <~logging.Logger.getEffectiveLevel>`.
31 """
32 level = logger.getEffectiveLevel()
33 current = logger
35 while current:
36 if any(handler.level <= level for handler in current.handlers):
37 return True
39 if not current.propagate:
40 break
42 current = current.parent # type: ignore
44 return False
47#: Log messages to :func:`~flask.logging.wsgi_errors_stream` with the format
48#: ``[%(asctime)s] %(levelname)s in %(module)s: %(message)s``.
49default_handler = logging.StreamHandler(wsgi_errors_stream) # type: ignore
50default_handler.setFormatter(
51 logging.Formatter("[%(asctime)s] %(levelname)s in %(module)s: %(message)s")
52)
55def create_logger(app: App) -> logging.Logger:
56 """Get the Flask app's logger and configure it if needed.
58 The logger name will be the same as
59 :attr:`app.import_name <flask.Flask.name>`.
61 When :attr:`~flask.Flask.debug` is enabled, set the logger level to
62 :data:`logging.DEBUG` if it is not set.
64 If there is no handler for the logger's effective level, add a
65 :class:`~logging.StreamHandler` for
66 :func:`~flask.logging.wsgi_errors_stream` with a basic format.
67 """
68 logger = logging.getLogger(app.name)
70 if app.debug and not logger.level:
71 logger.setLevel(logging.DEBUG)
73 if not has_level_handler(logger):
74 logger.addHandler(default_handler)
76 return logger