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

1from __future__ import annotations 

2 

3import logging 

4import sys 

5import typing as t 

6 

7from werkzeug.local import LocalProxy 

8 

9from .globals import request 

10 

11if t.TYPE_CHECKING: # pragma: no cover 

12 from .sansio.app import App 

13 

14 

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``. 

19 

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 

26 

27 

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 

34 

35 while current: 

36 if any(handler.level <= level for handler in current.handlers): 

37 return True 

38 

39 if not current.propagate: 

40 break 

41 

42 current = current.parent # type: ignore 

43 

44 return False 

45 

46 

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) 

53 

54 

55def create_logger(app: App) -> logging.Logger: 

56 """Get the Flask app's logger and configure it if needed. 

57 

58 The logger name will be the same as 

59 :attr:`app.import_name <flask.Flask.name>`. 

60 

61 When :attr:`~flask.Flask.debug` is enabled, set the logger level to 

62 :data:`logging.DEBUG` if it is not set. 

63 

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) 

69 

70 if app.debug and not logger.level: 

71 logger.setLevel(logging.DEBUG) 

72 

73 if not has_level_handler(logger): 

74 logger.addHandler(default_handler) 

75 

76 return logger