Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/flask/logging.py: 44%

27 statements  

« prev     ^ index     » next       coverage.py v7.0.1, created at 2022-12-25 06:11 +0000

1import logging 

2import sys 

3import typing as t 

4 

5from werkzeug.local import LocalProxy 

6 

7from .globals import request 

8 

9if t.TYPE_CHECKING: # pragma: no cover 

10 from .app import Flask 

11 

12 

13@LocalProxy 

14def wsgi_errors_stream() -> t.TextIO: 

15 """Find the most appropriate error stream for the application. If a request 

16 is active, log to ``wsgi.errors``, otherwise use ``sys.stderr``. 

17 

18 If you configure your own :class:`logging.StreamHandler`, you may want to 

19 use this for the stream. If you are using file or dict configuration and 

20 can't import this directly, you can refer to it as 

21 ``ext://flask.logging.wsgi_errors_stream``. 

22 """ 

23 return request.environ["wsgi.errors"] if request else sys.stderr 

24 

25 

26def has_level_handler(logger: logging.Logger) -> bool: 

27 """Check if there is a handler in the logging chain that will handle the 

28 given logger's :meth:`effective level <~logging.Logger.getEffectiveLevel>`. 

29 """ 

30 level = logger.getEffectiveLevel() 

31 current = logger 

32 

33 while current: 

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

35 return True 

36 

37 if not current.propagate: 

38 break 

39 

40 current = current.parent # type: ignore 

41 

42 return False 

43 

44 

45#: Log messages to :func:`~flask.logging.wsgi_errors_stream` with the format 

46#: ``[%(asctime)s] %(levelname)s in %(module)s: %(message)s``. 

47default_handler = logging.StreamHandler(wsgi_errors_stream) # type: ignore 

48default_handler.setFormatter( 

49 logging.Formatter("[%(asctime)s] %(levelname)s in %(module)s: %(message)s") 

50) 

51 

52 

53def create_logger(app: "Flask") -> logging.Logger: 

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

55 

56 The logger name will be the same as 

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

58 

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

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

61 

62 If there is no handler for the logger's effective level, add a 

63 :class:`~logging.StreamHandler` for 

64 :func:`~flask.logging.wsgi_errors_stream` with a basic format. 

65 """ 

66 logger = logging.getLogger(app.name) 

67 

68 if app.debug and not logger.level: 

69 logger.setLevel(logging.DEBUG) 

70 

71 if not has_level_handler(logger): 

72 logger.addHandler(default_handler) 

73 

74 return logger