ZTWHHH commited on
Commit
f67ec27
·
verified ·
1 Parent(s): 2cf3c01

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. valley/lib/python3.10/importlib/__init__.py +176 -0
  2. valley/lib/python3.10/importlib/__pycache__/__init__.cpython-310.pyc +0 -0
  3. valley/lib/python3.10/importlib/__pycache__/_abc.cpython-310.pyc +0 -0
  4. valley/lib/python3.10/importlib/__pycache__/_bootstrap.cpython-310.pyc +0 -0
  5. valley/lib/python3.10/importlib/__pycache__/_bootstrap_external.cpython-310.pyc +0 -0
  6. valley/lib/python3.10/importlib/__pycache__/_common.cpython-310.pyc +0 -0
  7. valley/lib/python3.10/importlib/__pycache__/machinery.cpython-310.pyc +0 -0
  8. valley/lib/python3.10/importlib/__pycache__/readers.cpython-310.pyc +0 -0
  9. valley/lib/python3.10/importlib/__pycache__/resources.cpython-310.pyc +0 -0
  10. valley/lib/python3.10/importlib/machinery.py +19 -0
  11. valley/lib/python3.10/importlib/metadata/_adapters.py +68 -0
  12. valley/lib/python3.10/importlib/readers.py +123 -0
  13. valley/lib/python3.10/logging/__init__.py +2261 -0
  14. valley/lib/python3.10/logging/__pycache__/__init__.cpython-310.pyc +0 -0
  15. valley/lib/python3.10/logging/__pycache__/config.cpython-310.pyc +0 -0
  16. valley/lib/python3.10/logging/__pycache__/handlers.cpython-310.pyc +0 -0
  17. valley/lib/python3.10/logging/config.py +947 -0
  18. valley/lib/python3.10/logging/handlers.py +1587 -0
  19. valley/lib/python3.10/turtledemo/__init__.py +14 -0
  20. valley/lib/python3.10/turtledemo/__main__.py +398 -0
  21. valley/lib/python3.10/turtledemo/__pycache__/__init__.cpython-310.pyc +0 -0
  22. valley/lib/python3.10/turtledemo/__pycache__/__main__.cpython-310.pyc +0 -0
  23. valley/lib/python3.10/turtledemo/__pycache__/bytedesign.cpython-310.pyc +0 -0
  24. valley/lib/python3.10/turtledemo/__pycache__/chaos.cpython-310.pyc +0 -0
  25. valley/lib/python3.10/turtledemo/__pycache__/clock.cpython-310.pyc +0 -0
  26. valley/lib/python3.10/turtledemo/__pycache__/colormixer.cpython-310.pyc +0 -0
  27. valley/lib/python3.10/turtledemo/__pycache__/forest.cpython-310.pyc +0 -0
  28. valley/lib/python3.10/turtledemo/__pycache__/fractalcurves.cpython-310.pyc +0 -0
  29. valley/lib/python3.10/turtledemo/__pycache__/lindenmayer.cpython-310.pyc +0 -0
  30. valley/lib/python3.10/turtledemo/__pycache__/minimal_hanoi.cpython-310.pyc +0 -0
  31. valley/lib/python3.10/turtledemo/__pycache__/nim.cpython-310.pyc +0 -0
  32. valley/lib/python3.10/turtledemo/__pycache__/paint.cpython-310.pyc +0 -0
  33. valley/lib/python3.10/turtledemo/__pycache__/peace.cpython-310.pyc +0 -0
  34. valley/lib/python3.10/turtledemo/__pycache__/penrose.cpython-310.pyc +0 -0
  35. valley/lib/python3.10/turtledemo/__pycache__/planet_and_moon.cpython-310.pyc +0 -0
  36. valley/lib/python3.10/turtledemo/__pycache__/rosette.cpython-310.pyc +0 -0
  37. valley/lib/python3.10/turtledemo/__pycache__/round_dance.cpython-310.pyc +0 -0
  38. valley/lib/python3.10/turtledemo/__pycache__/sorting_animate.cpython-310.pyc +0 -0
  39. valley/lib/python3.10/turtledemo/__pycache__/tree.cpython-310.pyc +0 -0
  40. valley/lib/python3.10/turtledemo/__pycache__/two_canvases.cpython-310.pyc +0 -0
  41. valley/lib/python3.10/turtledemo/__pycache__/yinyang.cpython-310.pyc +0 -0
  42. valley/lib/python3.10/turtledemo/bytedesign.py +161 -0
  43. valley/lib/python3.10/turtledemo/chaos.py +59 -0
  44. valley/lib/python3.10/turtledemo/clock.py +131 -0
  45. valley/lib/python3.10/turtledemo/colormixer.py +58 -0
  46. valley/lib/python3.10/turtledemo/forest.py +108 -0
  47. valley/lib/python3.10/turtledemo/fractalcurves.py +138 -0
  48. valley/lib/python3.10/turtledemo/lindenmayer.py +119 -0
  49. valley/lib/python3.10/turtledemo/minimal_hanoi.py +79 -0
  50. valley/lib/python3.10/turtledemo/nim.py +226 -0
valley/lib/python3.10/importlib/__init__.py ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """A pure Python implementation of import."""
2
+ __all__ = ['__import__', 'import_module', 'invalidate_caches', 'reload']
3
+
4
+ # Bootstrap help #####################################################
5
+
6
+ # Until bootstrapping is complete, DO NOT import any modules that attempt
7
+ # to import importlib._bootstrap (directly or indirectly). Since this
8
+ # partially initialised package would be present in sys.modules, those
9
+ # modules would get an uninitialised copy of the source version, instead
10
+ # of a fully initialised version (either the frozen one or the one
11
+ # initialised below if the frozen one is not available).
12
+ import _imp # Just the builtin component, NOT the full Python module
13
+ import sys
14
+
15
+ try:
16
+ import _frozen_importlib as _bootstrap
17
+ except ImportError:
18
+ from . import _bootstrap
19
+ _bootstrap._setup(sys, _imp)
20
+ else:
21
+ # importlib._bootstrap is the built-in import, ensure we don't create
22
+ # a second copy of the module.
23
+ _bootstrap.__name__ = 'importlib._bootstrap'
24
+ _bootstrap.__package__ = 'importlib'
25
+ try:
26
+ _bootstrap.__file__ = __file__.replace('__init__.py', '_bootstrap.py')
27
+ except NameError:
28
+ # __file__ is not guaranteed to be defined, e.g. if this code gets
29
+ # frozen by a tool like cx_Freeze.
30
+ pass
31
+ sys.modules['importlib._bootstrap'] = _bootstrap
32
+
33
+ try:
34
+ import _frozen_importlib_external as _bootstrap_external
35
+ except ImportError:
36
+ from . import _bootstrap_external
37
+ _bootstrap_external._set_bootstrap_module(_bootstrap)
38
+ _bootstrap._bootstrap_external = _bootstrap_external
39
+ else:
40
+ _bootstrap_external.__name__ = 'importlib._bootstrap_external'
41
+ _bootstrap_external.__package__ = 'importlib'
42
+ try:
43
+ _bootstrap_external.__file__ = __file__.replace('__init__.py', '_bootstrap_external.py')
44
+ except NameError:
45
+ # __file__ is not guaranteed to be defined, e.g. if this code gets
46
+ # frozen by a tool like cx_Freeze.
47
+ pass
48
+ sys.modules['importlib._bootstrap_external'] = _bootstrap_external
49
+
50
+ # To simplify imports in test code
51
+ _pack_uint32 = _bootstrap_external._pack_uint32
52
+ _unpack_uint32 = _bootstrap_external._unpack_uint32
53
+
54
+ # Fully bootstrapped at this point, import whatever you like, circular
55
+ # dependencies and startup overhead minimisation permitting :)
56
+
57
+ import warnings
58
+
59
+
60
+ # Public API #########################################################
61
+
62
+ from ._bootstrap import __import__
63
+
64
+
65
+ def invalidate_caches():
66
+ """Call the invalidate_caches() method on all meta path finders stored in
67
+ sys.meta_path (where implemented)."""
68
+ for finder in sys.meta_path:
69
+ if hasattr(finder, 'invalidate_caches'):
70
+ finder.invalidate_caches()
71
+
72
+
73
+ def find_loader(name, path=None):
74
+ """Return the loader for the specified module.
75
+
76
+ This is a backward-compatible wrapper around find_spec().
77
+
78
+ This function is deprecated in favor of importlib.util.find_spec().
79
+
80
+ """
81
+ warnings.warn('Deprecated since Python 3.4 and slated for removal in '
82
+ 'Python 3.12; use importlib.util.find_spec() instead',
83
+ DeprecationWarning, stacklevel=2)
84
+ try:
85
+ loader = sys.modules[name].__loader__
86
+ if loader is None:
87
+ raise ValueError('{}.__loader__ is None'.format(name))
88
+ else:
89
+ return loader
90
+ except KeyError:
91
+ pass
92
+ except AttributeError:
93
+ raise ValueError('{}.__loader__ is not set'.format(name)) from None
94
+
95
+ spec = _bootstrap._find_spec(name, path)
96
+ # We won't worry about malformed specs (missing attributes).
97
+ if spec is None:
98
+ return None
99
+ if spec.loader is None:
100
+ if spec.submodule_search_locations is None:
101
+ raise ImportError('spec for {} missing loader'.format(name),
102
+ name=name)
103
+ raise ImportError('namespace packages do not have loaders',
104
+ name=name)
105
+ return spec.loader
106
+
107
+
108
+ def import_module(name, package=None):
109
+ """Import a module.
110
+
111
+ The 'package' argument is required when performing a relative import. It
112
+ specifies the package to use as the anchor point from which to resolve the
113
+ relative import to an absolute import.
114
+
115
+ """
116
+ level = 0
117
+ if name.startswith('.'):
118
+ if not package:
119
+ msg = ("the 'package' argument is required to perform a relative "
120
+ "import for {!r}")
121
+ raise TypeError(msg.format(name))
122
+ for character in name:
123
+ if character != '.':
124
+ break
125
+ level += 1
126
+ return _bootstrap._gcd_import(name[level:], package, level)
127
+
128
+
129
+ _RELOADING = {}
130
+
131
+
132
+ def reload(module):
133
+ """Reload the module and return it.
134
+
135
+ The module must have been successfully imported before.
136
+
137
+ """
138
+ try:
139
+ name = module.__spec__.name
140
+ except AttributeError:
141
+ try:
142
+ name = module.__name__
143
+ except AttributeError:
144
+ raise TypeError("reload() argument must be a module")
145
+
146
+ if sys.modules.get(name) is not module:
147
+ msg = "module {} not in sys.modules"
148
+ raise ImportError(msg.format(name), name=name)
149
+ if name in _RELOADING:
150
+ return _RELOADING[name]
151
+ _RELOADING[name] = module
152
+ try:
153
+ parent_name = name.rpartition('.')[0]
154
+ if parent_name:
155
+ try:
156
+ parent = sys.modules[parent_name]
157
+ except KeyError:
158
+ msg = "parent {!r} not in sys.modules"
159
+ raise ImportError(msg.format(parent_name),
160
+ name=parent_name) from None
161
+ else:
162
+ pkgpath = parent.__path__
163
+ else:
164
+ pkgpath = None
165
+ target = module
166
+ spec = module.__spec__ = _bootstrap._find_spec(name, pkgpath, target)
167
+ if spec is None:
168
+ raise ModuleNotFoundError(f"spec not found for the module {name!r}", name=name)
169
+ _bootstrap._exec(spec, module)
170
+ # The module may have replaced itself in sys.modules!
171
+ return sys.modules[name]
172
+ finally:
173
+ try:
174
+ del _RELOADING[name]
175
+ except KeyError:
176
+ pass
valley/lib/python3.10/importlib/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (4.06 kB). View file
 
valley/lib/python3.10/importlib/__pycache__/_abc.cpython-310.pyc ADDED
Binary file (2.23 kB). View file
 
valley/lib/python3.10/importlib/__pycache__/_bootstrap.cpython-310.pyc ADDED
Binary file (30.4 kB). View file
 
valley/lib/python3.10/importlib/__pycache__/_bootstrap_external.cpython-310.pyc ADDED
Binary file (44.6 kB). View file
 
valley/lib/python3.10/importlib/__pycache__/_common.cpython-310.pyc ADDED
Binary file (2.96 kB). View file
 
valley/lib/python3.10/importlib/__pycache__/machinery.cpython-310.pyc ADDED
Binary file (1.2 kB). View file
 
valley/lib/python3.10/importlib/__pycache__/readers.cpython-310.pyc ADDED
Binary file (5.18 kB). View file
 
valley/lib/python3.10/importlib/__pycache__/resources.cpython-310.pyc ADDED
Binary file (5.62 kB). View file
 
valley/lib/python3.10/importlib/machinery.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The machinery of importlib: finders, loaders, hooks, etc."""
2
+
3
+ from ._bootstrap import ModuleSpec
4
+ from ._bootstrap import BuiltinImporter
5
+ from ._bootstrap import FrozenImporter
6
+ from ._bootstrap_external import (SOURCE_SUFFIXES, DEBUG_BYTECODE_SUFFIXES,
7
+ OPTIMIZED_BYTECODE_SUFFIXES, BYTECODE_SUFFIXES,
8
+ EXTENSION_SUFFIXES)
9
+ from ._bootstrap_external import WindowsRegistryFinder
10
+ from ._bootstrap_external import PathFinder
11
+ from ._bootstrap_external import FileFinder
12
+ from ._bootstrap_external import SourceFileLoader
13
+ from ._bootstrap_external import SourcelessFileLoader
14
+ from ._bootstrap_external import ExtensionFileLoader
15
+
16
+
17
+ def all_suffixes():
18
+ """Returns a list of all recognized module suffixes for this process"""
19
+ return SOURCE_SUFFIXES + BYTECODE_SUFFIXES + EXTENSION_SUFFIXES
valley/lib/python3.10/importlib/metadata/_adapters.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ import textwrap
3
+ import email.message
4
+
5
+ from ._text import FoldedCase
6
+
7
+
8
+ class Message(email.message.Message):
9
+ multiple_use_keys = set(
10
+ map(
11
+ FoldedCase,
12
+ [
13
+ 'Classifier',
14
+ 'Obsoletes-Dist',
15
+ 'Platform',
16
+ 'Project-URL',
17
+ 'Provides-Dist',
18
+ 'Provides-Extra',
19
+ 'Requires-Dist',
20
+ 'Requires-External',
21
+ 'Supported-Platform',
22
+ 'Dynamic',
23
+ ],
24
+ )
25
+ )
26
+ """
27
+ Keys that may be indicated multiple times per PEP 566.
28
+ """
29
+
30
+ def __new__(cls, orig: email.message.Message):
31
+ res = super().__new__(cls)
32
+ vars(res).update(vars(orig))
33
+ return res
34
+
35
+ def __init__(self, *args, **kwargs):
36
+ self._headers = self._repair_headers()
37
+
38
+ # suppress spurious error from mypy
39
+ def __iter__(self):
40
+ return super().__iter__()
41
+
42
+ def _repair_headers(self):
43
+ def redent(value):
44
+ "Correct for RFC822 indentation"
45
+ if not value or '\n' not in value:
46
+ return value
47
+ return textwrap.dedent(' ' * 8 + value)
48
+
49
+ headers = [(key, redent(value)) for key, value in vars(self)['_headers']]
50
+ if self._payload:
51
+ headers.append(('Description', self.get_payload()))
52
+ return headers
53
+
54
+ @property
55
+ def json(self):
56
+ """
57
+ Convert PackageMetadata to a JSON-compatible format
58
+ per PEP 0566.
59
+ """
60
+
61
+ def transform(key):
62
+ value = self.get_all(key) if key in self.multiple_use_keys else self[key]
63
+ if key == 'Keywords':
64
+ value = re.split(r'\s+', value)
65
+ tk = key.lower().replace('-', '_')
66
+ return tk, value
67
+
68
+ return dict(map(transform, map(FoldedCase, self)))
valley/lib/python3.10/importlib/readers.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import collections
2
+ import zipfile
3
+ import pathlib
4
+ from . import abc
5
+
6
+
7
+ def remove_duplicates(items):
8
+ return iter(collections.OrderedDict.fromkeys(items))
9
+
10
+
11
+ class FileReader(abc.TraversableResources):
12
+ def __init__(self, loader):
13
+ self.path = pathlib.Path(loader.path).parent
14
+
15
+ def resource_path(self, resource):
16
+ """
17
+ Return the file system path to prevent
18
+ `resources.path()` from creating a temporary
19
+ copy.
20
+ """
21
+ return str(self.path.joinpath(resource))
22
+
23
+ def files(self):
24
+ return self.path
25
+
26
+
27
+ class ZipReader(abc.TraversableResources):
28
+ def __init__(self, loader, module):
29
+ _, _, name = module.rpartition('.')
30
+ self.prefix = loader.prefix.replace('\\', '/') + name + '/'
31
+ self.archive = loader.archive
32
+
33
+ def open_resource(self, resource):
34
+ try:
35
+ return super().open_resource(resource)
36
+ except KeyError as exc:
37
+ raise FileNotFoundError(exc.args[0])
38
+
39
+ def is_resource(self, path):
40
+ # workaround for `zipfile.Path.is_file` returning true
41
+ # for non-existent paths.
42
+ target = self.files().joinpath(path)
43
+ return target.is_file() and target.exists()
44
+
45
+ def files(self):
46
+ return zipfile.Path(self.archive, self.prefix)
47
+
48
+
49
+ class MultiplexedPath(abc.Traversable):
50
+ """
51
+ Given a series of Traversable objects, implement a merged
52
+ version of the interface across all objects. Useful for
53
+ namespace packages which may be multihomed at a single
54
+ name.
55
+ """
56
+
57
+ def __init__(self, *paths):
58
+ self._paths = list(map(pathlib.Path, remove_duplicates(paths)))
59
+ if not self._paths:
60
+ message = 'MultiplexedPath must contain at least one path'
61
+ raise FileNotFoundError(message)
62
+ if not all(path.is_dir() for path in self._paths):
63
+ raise NotADirectoryError('MultiplexedPath only supports directories')
64
+
65
+ def iterdir(self):
66
+ visited = []
67
+ for path in self._paths:
68
+ for file in path.iterdir():
69
+ if file.name in visited:
70
+ continue
71
+ visited.append(file.name)
72
+ yield file
73
+
74
+ def read_bytes(self):
75
+ raise FileNotFoundError(f'{self} is not a file')
76
+
77
+ def read_text(self, *args, **kwargs):
78
+ raise FileNotFoundError(f'{self} is not a file')
79
+
80
+ def is_dir(self):
81
+ return True
82
+
83
+ def is_file(self):
84
+ return False
85
+
86
+ def joinpath(self, child):
87
+ # first try to find child in current paths
88
+ for file in self.iterdir():
89
+ if file.name == child:
90
+ return file
91
+ # if it does not exist, construct it with the first path
92
+ return self._paths[0] / child
93
+
94
+ __truediv__ = joinpath
95
+
96
+ def open(self, *args, **kwargs):
97
+ raise FileNotFoundError(f'{self} is not a file')
98
+
99
+ @property
100
+ def name(self):
101
+ return self._paths[0].name
102
+
103
+ def __repr__(self):
104
+ paths = ', '.join(f"'{path}'" for path in self._paths)
105
+ return f'MultiplexedPath({paths})'
106
+
107
+
108
+ class NamespaceReader(abc.TraversableResources):
109
+ def __init__(self, namespace_path):
110
+ if 'NamespacePath' not in str(namespace_path):
111
+ raise ValueError('Invalid path')
112
+ self.path = MultiplexedPath(*list(namespace_path))
113
+
114
+ def resource_path(self, resource):
115
+ """
116
+ Return the file system path to prevent
117
+ `resources.path()` from creating a temporary
118
+ copy.
119
+ """
120
+ return str(self.path.joinpath(resource))
121
+
122
+ def files(self):
123
+ return self.path
valley/lib/python3.10/logging/__init__.py ADDED
@@ -0,0 +1,2261 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2001-2019 by Vinay Sajip. All Rights Reserved.
2
+ #
3
+ # Permission to use, copy, modify, and distribute this software and its
4
+ # documentation for any purpose and without fee is hereby granted,
5
+ # provided that the above copyright notice appear in all copies and that
6
+ # both that copyright notice and this permission notice appear in
7
+ # supporting documentation, and that the name of Vinay Sajip
8
+ # not be used in advertising or publicity pertaining to distribution
9
+ # of the software without specific, written prior permission.
10
+ # VINAY SAJIP DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
11
+ # ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
12
+ # VINAY SAJIP BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
13
+ # ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
14
+ # IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
15
+ # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16
+
17
+ """
18
+ Logging package for Python. Based on PEP 282 and comments thereto in
19
+ comp.lang.python.
20
+
21
+ Copyright (C) 2001-2019 Vinay Sajip. All Rights Reserved.
22
+
23
+ To use, simply 'import logging' and log away!
24
+ """
25
+
26
+ import sys, os, time, io, re, traceback, warnings, weakref, collections.abc
27
+
28
+ from string import Template
29
+ from string import Formatter as StrFormatter
30
+
31
+
32
+ __all__ = ['BASIC_FORMAT', 'BufferingFormatter', 'CRITICAL', 'DEBUG', 'ERROR',
33
+ 'FATAL', 'FileHandler', 'Filter', 'Formatter', 'Handler', 'INFO',
34
+ 'LogRecord', 'Logger', 'LoggerAdapter', 'NOTSET', 'NullHandler',
35
+ 'StreamHandler', 'WARN', 'WARNING', 'addLevelName', 'basicConfig',
36
+ 'captureWarnings', 'critical', 'debug', 'disable', 'error',
37
+ 'exception', 'fatal', 'getLevelName', 'getLogger', 'getLoggerClass',
38
+ 'info', 'log', 'makeLogRecord', 'setLoggerClass', 'shutdown',
39
+ 'warn', 'warning', 'getLogRecordFactory', 'setLogRecordFactory',
40
+ 'lastResort', 'raiseExceptions']
41
+
42
+ import threading
43
+
44
+ __author__ = "Vinay Sajip <vinay_sajip@red-dove.com>"
45
+ __status__ = "production"
46
+ # The following module attributes are no longer updated.
47
+ __version__ = "0.5.1.2"
48
+ __date__ = "07 February 2010"
49
+
50
+ #---------------------------------------------------------------------------
51
+ # Miscellaneous module data
52
+ #---------------------------------------------------------------------------
53
+
54
+ #
55
+ #_startTime is used as the base when calculating the relative time of events
56
+ #
57
+ _startTime = time.time()
58
+
59
+ #
60
+ #raiseExceptions is used to see if exceptions during handling should be
61
+ #propagated
62
+ #
63
+ raiseExceptions = True
64
+
65
+ #
66
+ # If you don't want threading information in the log, set this to zero
67
+ #
68
+ logThreads = True
69
+
70
+ #
71
+ # If you don't want multiprocessing information in the log, set this to zero
72
+ #
73
+ logMultiprocessing = True
74
+
75
+ #
76
+ # If you don't want process information in the log, set this to zero
77
+ #
78
+ logProcesses = True
79
+
80
+ #---------------------------------------------------------------------------
81
+ # Level related stuff
82
+ #---------------------------------------------------------------------------
83
+ #
84
+ # Default levels and level names, these can be replaced with any positive set
85
+ # of values having corresponding names. There is a pseudo-level, NOTSET, which
86
+ # is only really there as a lower limit for user-defined levels. Handlers and
87
+ # loggers are initialized with NOTSET so that they will log all messages, even
88
+ # at user-defined levels.
89
+ #
90
+
91
+ CRITICAL = 50
92
+ FATAL = CRITICAL
93
+ ERROR = 40
94
+ WARNING = 30
95
+ WARN = WARNING
96
+ INFO = 20
97
+ DEBUG = 10
98
+ NOTSET = 0
99
+
100
+ _levelToName = {
101
+ CRITICAL: 'CRITICAL',
102
+ ERROR: 'ERROR',
103
+ WARNING: 'WARNING',
104
+ INFO: 'INFO',
105
+ DEBUG: 'DEBUG',
106
+ NOTSET: 'NOTSET',
107
+ }
108
+ _nameToLevel = {
109
+ 'CRITICAL': CRITICAL,
110
+ 'FATAL': FATAL,
111
+ 'ERROR': ERROR,
112
+ 'WARN': WARNING,
113
+ 'WARNING': WARNING,
114
+ 'INFO': INFO,
115
+ 'DEBUG': DEBUG,
116
+ 'NOTSET': NOTSET,
117
+ }
118
+
119
+ def getLevelName(level):
120
+ """
121
+ Return the textual or numeric representation of logging level 'level'.
122
+
123
+ If the level is one of the predefined levels (CRITICAL, ERROR, WARNING,
124
+ INFO, DEBUG) then you get the corresponding string. If you have
125
+ associated levels with names using addLevelName then the name you have
126
+ associated with 'level' is returned.
127
+
128
+ If a numeric value corresponding to one of the defined levels is passed
129
+ in, the corresponding string representation is returned.
130
+
131
+ If a string representation of the level is passed in, the corresponding
132
+ numeric value is returned.
133
+
134
+ If no matching numeric or string value is passed in, the string
135
+ 'Level %s' % level is returned.
136
+ """
137
+ # See Issues #22386, #27937 and #29220 for why it's this way
138
+ result = _levelToName.get(level)
139
+ if result is not None:
140
+ return result
141
+ result = _nameToLevel.get(level)
142
+ if result is not None:
143
+ return result
144
+ return "Level %s" % level
145
+
146
+ def addLevelName(level, levelName):
147
+ """
148
+ Associate 'levelName' with 'level'.
149
+
150
+ This is used when converting levels to text during message formatting.
151
+ """
152
+ _acquireLock()
153
+ try: #unlikely to cause an exception, but you never know...
154
+ _levelToName[level] = levelName
155
+ _nameToLevel[levelName] = level
156
+ finally:
157
+ _releaseLock()
158
+
159
+ if hasattr(sys, '_getframe'):
160
+ currentframe = lambda: sys._getframe(3)
161
+ else: #pragma: no cover
162
+ def currentframe():
163
+ """Return the frame object for the caller's stack frame."""
164
+ try:
165
+ raise Exception
166
+ except Exception:
167
+ return sys.exc_info()[2].tb_frame.f_back
168
+
169
+ #
170
+ # _srcfile is used when walking the stack to check when we've got the first
171
+ # caller stack frame, by skipping frames whose filename is that of this
172
+ # module's source. It therefore should contain the filename of this module's
173
+ # source file.
174
+ #
175
+ # Ordinarily we would use __file__ for this, but frozen modules don't always
176
+ # have __file__ set, for some reason (see Issue #21736). Thus, we get the
177
+ # filename from a handy code object from a function defined in this module.
178
+ # (There's no particular reason for picking addLevelName.)
179
+ #
180
+
181
+ _srcfile = os.path.normcase(addLevelName.__code__.co_filename)
182
+
183
+ # _srcfile is only used in conjunction with sys._getframe().
184
+ # To provide compatibility with older versions of Python, set _srcfile
185
+ # to None if _getframe() is not available; this value will prevent
186
+ # findCaller() from being called. You can also do this if you want to avoid
187
+ # the overhead of fetching caller information, even when _getframe() is
188
+ # available.
189
+ #if not hasattr(sys, '_getframe'):
190
+ # _srcfile = None
191
+
192
+
193
+ def _checkLevel(level):
194
+ if isinstance(level, int):
195
+ rv = level
196
+ elif str(level) == level:
197
+ if level not in _nameToLevel:
198
+ raise ValueError("Unknown level: %r" % level)
199
+ rv = _nameToLevel[level]
200
+ else:
201
+ raise TypeError("Level not an integer or a valid string: %r"
202
+ % (level,))
203
+ return rv
204
+
205
+ #---------------------------------------------------------------------------
206
+ # Thread-related stuff
207
+ #---------------------------------------------------------------------------
208
+
209
+ #
210
+ #_lock is used to serialize access to shared data structures in this module.
211
+ #This needs to be an RLock because fileConfig() creates and configures
212
+ #Handlers, and so might arbitrary user threads. Since Handler code updates the
213
+ #shared dictionary _handlers, it needs to acquire the lock. But if configuring,
214
+ #the lock would already have been acquired - so we need an RLock.
215
+ #The same argument applies to Loggers and Manager.loggerDict.
216
+ #
217
+ _lock = threading.RLock()
218
+
219
+ def _acquireLock():
220
+ """
221
+ Acquire the module-level lock for serializing access to shared data.
222
+
223
+ This should be released with _releaseLock().
224
+ """
225
+ if _lock:
226
+ _lock.acquire()
227
+
228
+ def _releaseLock():
229
+ """
230
+ Release the module-level lock acquired by calling _acquireLock().
231
+ """
232
+ if _lock:
233
+ _lock.release()
234
+
235
+
236
+ # Prevent a held logging lock from blocking a child from logging.
237
+
238
+ if not hasattr(os, 'register_at_fork'): # Windows and friends.
239
+ def _register_at_fork_reinit_lock(instance):
240
+ pass # no-op when os.register_at_fork does not exist.
241
+ else:
242
+ # A collection of instances with a _at_fork_reinit method (logging.Handler)
243
+ # to be called in the child after forking. The weakref avoids us keeping
244
+ # discarded Handler instances alive.
245
+ _at_fork_reinit_lock_weakset = weakref.WeakSet()
246
+
247
+ def _register_at_fork_reinit_lock(instance):
248
+ _acquireLock()
249
+ try:
250
+ _at_fork_reinit_lock_weakset.add(instance)
251
+ finally:
252
+ _releaseLock()
253
+
254
+ def _after_at_fork_child_reinit_locks():
255
+ for handler in _at_fork_reinit_lock_weakset:
256
+ handler._at_fork_reinit()
257
+
258
+ # _acquireLock() was called in the parent before forking.
259
+ # The lock is reinitialized to unlocked state.
260
+ _lock._at_fork_reinit()
261
+
262
+ os.register_at_fork(before=_acquireLock,
263
+ after_in_child=_after_at_fork_child_reinit_locks,
264
+ after_in_parent=_releaseLock)
265
+
266
+
267
+ #---------------------------------------------------------------------------
268
+ # The logging record
269
+ #---------------------------------------------------------------------------
270
+
271
+ class LogRecord(object):
272
+ """
273
+ A LogRecord instance represents an event being logged.
274
+
275
+ LogRecord instances are created every time something is logged. They
276
+ contain all the information pertinent to the event being logged. The
277
+ main information passed in is in msg and args, which are combined
278
+ using str(msg) % args to create the message field of the record. The
279
+ record also includes information such as when the record was created,
280
+ the source line where the logging call was made, and any exception
281
+ information to be logged.
282
+ """
283
+ def __init__(self, name, level, pathname, lineno,
284
+ msg, args, exc_info, func=None, sinfo=None, **kwargs):
285
+ """
286
+ Initialize a logging record with interesting information.
287
+ """
288
+ ct = time.time()
289
+ self.name = name
290
+ self.msg = msg
291
+ #
292
+ # The following statement allows passing of a dictionary as a sole
293
+ # argument, so that you can do something like
294
+ # logging.debug("a %(a)d b %(b)s", {'a':1, 'b':2})
295
+ # Suggested by Stefan Behnel.
296
+ # Note that without the test for args[0], we get a problem because
297
+ # during formatting, we test to see if the arg is present using
298
+ # 'if self.args:'. If the event being logged is e.g. 'Value is %d'
299
+ # and if the passed arg fails 'if self.args:' then no formatting
300
+ # is done. For example, logger.warning('Value is %d', 0) would log
301
+ # 'Value is %d' instead of 'Value is 0'.
302
+ # For the use case of passing a dictionary, this should not be a
303
+ # problem.
304
+ # Issue #21172: a request was made to relax the isinstance check
305
+ # to hasattr(args[0], '__getitem__'). However, the docs on string
306
+ # formatting still seem to suggest a mapping object is required.
307
+ # Thus, while not removing the isinstance check, it does now look
308
+ # for collections.abc.Mapping rather than, as before, dict.
309
+ if (args and len(args) == 1 and isinstance(args[0], collections.abc.Mapping)
310
+ and args[0]):
311
+ args = args[0]
312
+ self.args = args
313
+ self.levelname = getLevelName(level)
314
+ self.levelno = level
315
+ self.pathname = pathname
316
+ try:
317
+ self.filename = os.path.basename(pathname)
318
+ self.module = os.path.splitext(self.filename)[0]
319
+ except (TypeError, ValueError, AttributeError):
320
+ self.filename = pathname
321
+ self.module = "Unknown module"
322
+ self.exc_info = exc_info
323
+ self.exc_text = None # used to cache the traceback text
324
+ self.stack_info = sinfo
325
+ self.lineno = lineno
326
+ self.funcName = func
327
+ self.created = ct
328
+ self.msecs = int((ct - int(ct)) * 1000) + 0.0 # see gh-89047
329
+ self.relativeCreated = (self.created - _startTime) * 1000
330
+ if logThreads:
331
+ self.thread = threading.get_ident()
332
+ self.threadName = threading.current_thread().name
333
+ else: # pragma: no cover
334
+ self.thread = None
335
+ self.threadName = None
336
+ if not logMultiprocessing: # pragma: no cover
337
+ self.processName = None
338
+ else:
339
+ self.processName = 'MainProcess'
340
+ mp = sys.modules.get('multiprocessing')
341
+ if mp is not None:
342
+ # Errors may occur if multiprocessing has not finished loading
343
+ # yet - e.g. if a custom import hook causes third-party code
344
+ # to run when multiprocessing calls import. See issue 8200
345
+ # for an example
346
+ try:
347
+ self.processName = mp.current_process().name
348
+ except Exception: #pragma: no cover
349
+ pass
350
+ if logProcesses and hasattr(os, 'getpid'):
351
+ self.process = os.getpid()
352
+ else:
353
+ self.process = None
354
+
355
+ def __repr__(self):
356
+ return '<LogRecord: %s, %s, %s, %s, "%s">'%(self.name, self.levelno,
357
+ self.pathname, self.lineno, self.msg)
358
+
359
+ def getMessage(self):
360
+ """
361
+ Return the message for this LogRecord.
362
+
363
+ Return the message for this LogRecord after merging any user-supplied
364
+ arguments with the message.
365
+ """
366
+ msg = str(self.msg)
367
+ if self.args:
368
+ msg = msg % self.args
369
+ return msg
370
+
371
+ #
372
+ # Determine which class to use when instantiating log records.
373
+ #
374
+ _logRecordFactory = LogRecord
375
+
376
+ def setLogRecordFactory(factory):
377
+ """
378
+ Set the factory to be used when instantiating a log record.
379
+
380
+ :param factory: A callable which will be called to instantiate
381
+ a log record.
382
+ """
383
+ global _logRecordFactory
384
+ _logRecordFactory = factory
385
+
386
+ def getLogRecordFactory():
387
+ """
388
+ Return the factory to be used when instantiating a log record.
389
+ """
390
+
391
+ return _logRecordFactory
392
+
393
+ def makeLogRecord(dict):
394
+ """
395
+ Make a LogRecord whose attributes are defined by the specified dictionary,
396
+ This function is useful for converting a logging event received over
397
+ a socket connection (which is sent as a dictionary) into a LogRecord
398
+ instance.
399
+ """
400
+ rv = _logRecordFactory(None, None, "", 0, "", (), None, None)
401
+ rv.__dict__.update(dict)
402
+ return rv
403
+
404
+
405
+ #---------------------------------------------------------------------------
406
+ # Formatter classes and functions
407
+ #---------------------------------------------------------------------------
408
+ _str_formatter = StrFormatter()
409
+ del StrFormatter
410
+
411
+
412
+ class PercentStyle(object):
413
+
414
+ default_format = '%(message)s'
415
+ asctime_format = '%(asctime)s'
416
+ asctime_search = '%(asctime)'
417
+ validation_pattern = re.compile(r'%\(\w+\)[#0+ -]*(\*|\d+)?(\.(\*|\d+))?[diouxefgcrsa%]', re.I)
418
+
419
+ def __init__(self, fmt, *, defaults=None):
420
+ self._fmt = fmt or self.default_format
421
+ self._defaults = defaults
422
+
423
+ def usesTime(self):
424
+ return self._fmt.find(self.asctime_search) >= 0
425
+
426
+ def validate(self):
427
+ """Validate the input format, ensure it matches the correct style"""
428
+ if not self.validation_pattern.search(self._fmt):
429
+ raise ValueError("Invalid format '%s' for '%s' style" % (self._fmt, self.default_format[0]))
430
+
431
+ def _format(self, record):
432
+ if defaults := self._defaults:
433
+ values = defaults | record.__dict__
434
+ else:
435
+ values = record.__dict__
436
+ return self._fmt % values
437
+
438
+ def format(self, record):
439
+ try:
440
+ return self._format(record)
441
+ except KeyError as e:
442
+ raise ValueError('Formatting field not found in record: %s' % e)
443
+
444
+
445
+ class StrFormatStyle(PercentStyle):
446
+ default_format = '{message}'
447
+ asctime_format = '{asctime}'
448
+ asctime_search = '{asctime'
449
+
450
+ fmt_spec = re.compile(r'^(.?[<>=^])?[+ -]?#?0?(\d+|{\w+})?[,_]?(\.(\d+|{\w+}))?[bcdefgnosx%]?$', re.I)
451
+ field_spec = re.compile(r'^(\d+|\w+)(\.\w+|\[[^]]+\])*$')
452
+
453
+ def _format(self, record):
454
+ if defaults := self._defaults:
455
+ values = defaults | record.__dict__
456
+ else:
457
+ values = record.__dict__
458
+ return self._fmt.format(**values)
459
+
460
+ def validate(self):
461
+ """Validate the input format, ensure it is the correct string formatting style"""
462
+ fields = set()
463
+ try:
464
+ for _, fieldname, spec, conversion in _str_formatter.parse(self._fmt):
465
+ if fieldname:
466
+ if not self.field_spec.match(fieldname):
467
+ raise ValueError('invalid field name/expression: %r' % fieldname)
468
+ fields.add(fieldname)
469
+ if conversion and conversion not in 'rsa':
470
+ raise ValueError('invalid conversion: %r' % conversion)
471
+ if spec and not self.fmt_spec.match(spec):
472
+ raise ValueError('bad specifier: %r' % spec)
473
+ except ValueError as e:
474
+ raise ValueError('invalid format: %s' % e)
475
+ if not fields:
476
+ raise ValueError('invalid format: no fields')
477
+
478
+
479
+ class StringTemplateStyle(PercentStyle):
480
+ default_format = '${message}'
481
+ asctime_format = '${asctime}'
482
+ asctime_search = '${asctime}'
483
+
484
+ def __init__(self, *args, **kwargs):
485
+ super().__init__(*args, **kwargs)
486
+ self._tpl = Template(self._fmt)
487
+
488
+ def usesTime(self):
489
+ fmt = self._fmt
490
+ return fmt.find('$asctime') >= 0 or fmt.find(self.asctime_search) >= 0
491
+
492
+ def validate(self):
493
+ pattern = Template.pattern
494
+ fields = set()
495
+ for m in pattern.finditer(self._fmt):
496
+ d = m.groupdict()
497
+ if d['named']:
498
+ fields.add(d['named'])
499
+ elif d['braced']:
500
+ fields.add(d['braced'])
501
+ elif m.group(0) == '$':
502
+ raise ValueError('invalid format: bare \'$\' not allowed')
503
+ if not fields:
504
+ raise ValueError('invalid format: no fields')
505
+
506
+ def _format(self, record):
507
+ if defaults := self._defaults:
508
+ values = defaults | record.__dict__
509
+ else:
510
+ values = record.__dict__
511
+ return self._tpl.substitute(**values)
512
+
513
+
514
+ BASIC_FORMAT = "%(levelname)s:%(name)s:%(message)s"
515
+
516
+ _STYLES = {
517
+ '%': (PercentStyle, BASIC_FORMAT),
518
+ '{': (StrFormatStyle, '{levelname}:{name}:{message}'),
519
+ '$': (StringTemplateStyle, '${levelname}:${name}:${message}'),
520
+ }
521
+
522
+ class Formatter(object):
523
+ """
524
+ Formatter instances are used to convert a LogRecord to text.
525
+
526
+ Formatters need to know how a LogRecord is constructed. They are
527
+ responsible for converting a LogRecord to (usually) a string which can
528
+ be interpreted by either a human or an external system. The base Formatter
529
+ allows a formatting string to be specified. If none is supplied, the
530
+ style-dependent default value, "%(message)s", "{message}", or
531
+ "${message}", is used.
532
+
533
+ The Formatter can be initialized with a format string which makes use of
534
+ knowledge of the LogRecord attributes - e.g. the default value mentioned
535
+ above makes use of the fact that the user's message and arguments are pre-
536
+ formatted into a LogRecord's message attribute. Currently, the useful
537
+ attributes in a LogRecord are described by:
538
+
539
+ %(name)s Name of the logger (logging channel)
540
+ %(levelno)s Numeric logging level for the message (DEBUG, INFO,
541
+ WARNING, ERROR, CRITICAL)
542
+ %(levelname)s Text logging level for the message ("DEBUG", "INFO",
543
+ "WARNING", "ERROR", "CRITICAL")
544
+ %(pathname)s Full pathname of the source file where the logging
545
+ call was issued (if available)
546
+ %(filename)s Filename portion of pathname
547
+ %(module)s Module (name portion of filename)
548
+ %(lineno)d Source line number where the logging call was issued
549
+ (if available)
550
+ %(funcName)s Function name
551
+ %(created)f Time when the LogRecord was created (time.time()
552
+ return value)
553
+ %(asctime)s Textual time when the LogRecord was created
554
+ %(msecs)d Millisecond portion of the creation time
555
+ %(relativeCreated)d Time in milliseconds when the LogRecord was created,
556
+ relative to the time the logging module was loaded
557
+ (typically at application startup time)
558
+ %(thread)d Thread ID (if available)
559
+ %(threadName)s Thread name (if available)
560
+ %(process)d Process ID (if available)
561
+ %(message)s The result of record.getMessage(), computed just as
562
+ the record is emitted
563
+ """
564
+
565
+ converter = time.localtime
566
+
567
+ def __init__(self, fmt=None, datefmt=None, style='%', validate=True, *,
568
+ defaults=None):
569
+ """
570
+ Initialize the formatter with specified format strings.
571
+
572
+ Initialize the formatter either with the specified format string, or a
573
+ default as described above. Allow for specialized date formatting with
574
+ the optional datefmt argument. If datefmt is omitted, you get an
575
+ ISO8601-like (or RFC 3339-like) format.
576
+
577
+ Use a style parameter of '%', '{' or '$' to specify that you want to
578
+ use one of %-formatting, :meth:`str.format` (``{}``) formatting or
579
+ :class:`string.Template` formatting in your format string.
580
+
581
+ .. versionchanged:: 3.2
582
+ Added the ``style`` parameter.
583
+ """
584
+ if style not in _STYLES:
585
+ raise ValueError('Style must be one of: %s' % ','.join(
586
+ _STYLES.keys()))
587
+ self._style = _STYLES[style][0](fmt, defaults=defaults)
588
+ if validate:
589
+ self._style.validate()
590
+
591
+ self._fmt = self._style._fmt
592
+ self.datefmt = datefmt
593
+
594
+ default_time_format = '%Y-%m-%d %H:%M:%S'
595
+ default_msec_format = '%s,%03d'
596
+
597
+ def formatTime(self, record, datefmt=None):
598
+ """
599
+ Return the creation time of the specified LogRecord as formatted text.
600
+
601
+ This method should be called from format() by a formatter which
602
+ wants to make use of a formatted time. This method can be overridden
603
+ in formatters to provide for any specific requirement, but the
604
+ basic behaviour is as follows: if datefmt (a string) is specified,
605
+ it is used with time.strftime() to format the creation time of the
606
+ record. Otherwise, an ISO8601-like (or RFC 3339-like) format is used.
607
+ The resulting string is returned. This function uses a user-configurable
608
+ function to convert the creation time to a tuple. By default,
609
+ time.localtime() is used; to change this for a particular formatter
610
+ instance, set the 'converter' attribute to a function with the same
611
+ signature as time.localtime() or time.gmtime(). To change it for all
612
+ formatters, for example if you want all logging times to be shown in GMT,
613
+ set the 'converter' attribute in the Formatter class.
614
+ """
615
+ ct = self.converter(record.created)
616
+ if datefmt:
617
+ s = time.strftime(datefmt, ct)
618
+ else:
619
+ s = time.strftime(self.default_time_format, ct)
620
+ if self.default_msec_format:
621
+ s = self.default_msec_format % (s, record.msecs)
622
+ return s
623
+
624
+ def formatException(self, ei):
625
+ """
626
+ Format and return the specified exception information as a string.
627
+
628
+ This default implementation just uses
629
+ traceback.print_exception()
630
+ """
631
+ sio = io.StringIO()
632
+ tb = ei[2]
633
+ # See issues #9427, #1553375. Commented out for now.
634
+ #if getattr(self, 'fullstack', False):
635
+ # traceback.print_stack(tb.tb_frame.f_back, file=sio)
636
+ traceback.print_exception(ei[0], ei[1], tb, None, sio)
637
+ s = sio.getvalue()
638
+ sio.close()
639
+ if s[-1:] == "\n":
640
+ s = s[:-1]
641
+ return s
642
+
643
+ def usesTime(self):
644
+ """
645
+ Check if the format uses the creation time of the record.
646
+ """
647
+ return self._style.usesTime()
648
+
649
+ def formatMessage(self, record):
650
+ return self._style.format(record)
651
+
652
+ def formatStack(self, stack_info):
653
+ """
654
+ This method is provided as an extension point for specialized
655
+ formatting of stack information.
656
+
657
+ The input data is a string as returned from a call to
658
+ :func:`traceback.print_stack`, but with the last trailing newline
659
+ removed.
660
+
661
+ The base implementation just returns the value passed in.
662
+ """
663
+ return stack_info
664
+
665
+ def format(self, record):
666
+ """
667
+ Format the specified record as text.
668
+
669
+ The record's attribute dictionary is used as the operand to a
670
+ string formatting operation which yields the returned string.
671
+ Before formatting the dictionary, a couple of preparatory steps
672
+ are carried out. The message attribute of the record is computed
673
+ using LogRecord.getMessage(). If the formatting string uses the
674
+ time (as determined by a call to usesTime(), formatTime() is
675
+ called to format the event time. If there is exception information,
676
+ it is formatted using formatException() and appended to the message.
677
+ """
678
+ record.message = record.getMessage()
679
+ if self.usesTime():
680
+ record.asctime = self.formatTime(record, self.datefmt)
681
+ s = self.formatMessage(record)
682
+ if record.exc_info:
683
+ # Cache the traceback text to avoid converting it multiple times
684
+ # (it's constant anyway)
685
+ if not record.exc_text:
686
+ record.exc_text = self.formatException(record.exc_info)
687
+ if record.exc_text:
688
+ if s[-1:] != "\n":
689
+ s = s + "\n"
690
+ s = s + record.exc_text
691
+ if record.stack_info:
692
+ if s[-1:] != "\n":
693
+ s = s + "\n"
694
+ s = s + self.formatStack(record.stack_info)
695
+ return s
696
+
697
+ #
698
+ # The default formatter to use when no other is specified
699
+ #
700
+ _defaultFormatter = Formatter()
701
+
702
+ class BufferingFormatter(object):
703
+ """
704
+ A formatter suitable for formatting a number of records.
705
+ """
706
+ def __init__(self, linefmt=None):
707
+ """
708
+ Optionally specify a formatter which will be used to format each
709
+ individual record.
710
+ """
711
+ if linefmt:
712
+ self.linefmt = linefmt
713
+ else:
714
+ self.linefmt = _defaultFormatter
715
+
716
+ def formatHeader(self, records):
717
+ """
718
+ Return the header string for the specified records.
719
+ """
720
+ return ""
721
+
722
+ def formatFooter(self, records):
723
+ """
724
+ Return the footer string for the specified records.
725
+ """
726
+ return ""
727
+
728
+ def format(self, records):
729
+ """
730
+ Format the specified records and return the result as a string.
731
+ """
732
+ rv = ""
733
+ if len(records) > 0:
734
+ rv = rv + self.formatHeader(records)
735
+ for record in records:
736
+ rv = rv + self.linefmt.format(record)
737
+ rv = rv + self.formatFooter(records)
738
+ return rv
739
+
740
+ #---------------------------------------------------------------------------
741
+ # Filter classes and functions
742
+ #---------------------------------------------------------------------------
743
+
744
+ class Filter(object):
745
+ """
746
+ Filter instances are used to perform arbitrary filtering of LogRecords.
747
+
748
+ Loggers and Handlers can optionally use Filter instances to filter
749
+ records as desired. The base filter class only allows events which are
750
+ below a certain point in the logger hierarchy. For example, a filter
751
+ initialized with "A.B" will allow events logged by loggers "A.B",
752
+ "A.B.C", "A.B.C.D", "A.B.D" etc. but not "A.BB", "B.A.B" etc. If
753
+ initialized with the empty string, all events are passed.
754
+ """
755
+ def __init__(self, name=''):
756
+ """
757
+ Initialize a filter.
758
+
759
+ Initialize with the name of the logger which, together with its
760
+ children, will have its events allowed through the filter. If no
761
+ name is specified, allow every event.
762
+ """
763
+ self.name = name
764
+ self.nlen = len(name)
765
+
766
+ def filter(self, record):
767
+ """
768
+ Determine if the specified record is to be logged.
769
+
770
+ Returns True if the record should be logged, or False otherwise.
771
+ If deemed appropriate, the record may be modified in-place.
772
+ """
773
+ if self.nlen == 0:
774
+ return True
775
+ elif self.name == record.name:
776
+ return True
777
+ elif record.name.find(self.name, 0, self.nlen) != 0:
778
+ return False
779
+ return (record.name[self.nlen] == ".")
780
+
781
+ class Filterer(object):
782
+ """
783
+ A base class for loggers and handlers which allows them to share
784
+ common code.
785
+ """
786
+ def __init__(self):
787
+ """
788
+ Initialize the list of filters to be an empty list.
789
+ """
790
+ self.filters = []
791
+
792
+ def addFilter(self, filter):
793
+ """
794
+ Add the specified filter to this handler.
795
+ """
796
+ if not (filter in self.filters):
797
+ self.filters.append(filter)
798
+
799
+ def removeFilter(self, filter):
800
+ """
801
+ Remove the specified filter from this handler.
802
+ """
803
+ if filter in self.filters:
804
+ self.filters.remove(filter)
805
+
806
+ def filter(self, record):
807
+ """
808
+ Determine if a record is loggable by consulting all the filters.
809
+
810
+ The default is to allow the record to be logged; any filter can veto
811
+ this and the record is then dropped. Returns a zero value if a record
812
+ is to be dropped, else non-zero.
813
+
814
+ .. versionchanged:: 3.2
815
+
816
+ Allow filters to be just callables.
817
+ """
818
+ rv = True
819
+ for f in self.filters:
820
+ if hasattr(f, 'filter'):
821
+ result = f.filter(record)
822
+ else:
823
+ result = f(record) # assume callable - will raise if not
824
+ if not result:
825
+ rv = False
826
+ break
827
+ return rv
828
+
829
+ #---------------------------------------------------------------------------
830
+ # Handler classes and functions
831
+ #---------------------------------------------------------------------------
832
+
833
+ _handlers = weakref.WeakValueDictionary() #map of handler names to handlers
834
+ _handlerList = [] # added to allow handlers to be removed in reverse of order initialized
835
+
836
+ def _removeHandlerRef(wr):
837
+ """
838
+ Remove a handler reference from the internal cleanup list.
839
+ """
840
+ # This function can be called during module teardown, when globals are
841
+ # set to None. It can also be called from another thread. So we need to
842
+ # pre-emptively grab the necessary globals and check if they're None,
843
+ # to prevent race conditions and failures during interpreter shutdown.
844
+ acquire, release, handlers = _acquireLock, _releaseLock, _handlerList
845
+ if acquire and release and handlers:
846
+ acquire()
847
+ try:
848
+ if wr in handlers:
849
+ handlers.remove(wr)
850
+ finally:
851
+ release()
852
+
853
+ def _addHandlerRef(handler):
854
+ """
855
+ Add a handler to the internal cleanup list using a weak reference.
856
+ """
857
+ _acquireLock()
858
+ try:
859
+ _handlerList.append(weakref.ref(handler, _removeHandlerRef))
860
+ finally:
861
+ _releaseLock()
862
+
863
+ class Handler(Filterer):
864
+ """
865
+ Handler instances dispatch logging events to specific destinations.
866
+
867
+ The base handler class. Acts as a placeholder which defines the Handler
868
+ interface. Handlers can optionally use Formatter instances to format
869
+ records as desired. By default, no formatter is specified; in this case,
870
+ the 'raw' message as determined by record.message is logged.
871
+ """
872
+ def __init__(self, level=NOTSET):
873
+ """
874
+ Initializes the instance - basically setting the formatter to None
875
+ and the filter list to empty.
876
+ """
877
+ Filterer.__init__(self)
878
+ self._name = None
879
+ self.level = _checkLevel(level)
880
+ self.formatter = None
881
+ self._closed = False
882
+ # Add the handler to the global _handlerList (for cleanup on shutdown)
883
+ _addHandlerRef(self)
884
+ self.createLock()
885
+
886
+ def get_name(self):
887
+ return self._name
888
+
889
+ def set_name(self, name):
890
+ _acquireLock()
891
+ try:
892
+ if self._name in _handlers:
893
+ del _handlers[self._name]
894
+ self._name = name
895
+ if name:
896
+ _handlers[name] = self
897
+ finally:
898
+ _releaseLock()
899
+
900
+ name = property(get_name, set_name)
901
+
902
+ def createLock(self):
903
+ """
904
+ Acquire a thread lock for serializing access to the underlying I/O.
905
+ """
906
+ self.lock = threading.RLock()
907
+ _register_at_fork_reinit_lock(self)
908
+
909
+ def _at_fork_reinit(self):
910
+ self.lock._at_fork_reinit()
911
+
912
+ def acquire(self):
913
+ """
914
+ Acquire the I/O thread lock.
915
+ """
916
+ if self.lock:
917
+ self.lock.acquire()
918
+
919
+ def release(self):
920
+ """
921
+ Release the I/O thread lock.
922
+ """
923
+ if self.lock:
924
+ self.lock.release()
925
+
926
+ def setLevel(self, level):
927
+ """
928
+ Set the logging level of this handler. level must be an int or a str.
929
+ """
930
+ self.level = _checkLevel(level)
931
+
932
+ def format(self, record):
933
+ """
934
+ Format the specified record.
935
+
936
+ If a formatter is set, use it. Otherwise, use the default formatter
937
+ for the module.
938
+ """
939
+ if self.formatter:
940
+ fmt = self.formatter
941
+ else:
942
+ fmt = _defaultFormatter
943
+ return fmt.format(record)
944
+
945
+ def emit(self, record):
946
+ """
947
+ Do whatever it takes to actually log the specified logging record.
948
+
949
+ This version is intended to be implemented by subclasses and so
950
+ raises a NotImplementedError.
951
+ """
952
+ raise NotImplementedError('emit must be implemented '
953
+ 'by Handler subclasses')
954
+
955
+ def handle(self, record):
956
+ """
957
+ Conditionally emit the specified logging record.
958
+
959
+ Emission depends on filters which may have been added to the handler.
960
+ Wrap the actual emission of the record with acquisition/release of
961
+ the I/O thread lock. Returns whether the filter passed the record for
962
+ emission.
963
+ """
964
+ rv = self.filter(record)
965
+ if rv:
966
+ self.acquire()
967
+ try:
968
+ self.emit(record)
969
+ finally:
970
+ self.release()
971
+ return rv
972
+
973
+ def setFormatter(self, fmt):
974
+ """
975
+ Set the formatter for this handler.
976
+ """
977
+ self.formatter = fmt
978
+
979
+ def flush(self):
980
+ """
981
+ Ensure all logging output has been flushed.
982
+
983
+ This version does nothing and is intended to be implemented by
984
+ subclasses.
985
+ """
986
+ pass
987
+
988
+ def close(self):
989
+ """
990
+ Tidy up any resources used by the handler.
991
+
992
+ This version removes the handler from an internal map of handlers,
993
+ _handlers, which is used for handler lookup by name. Subclasses
994
+ should ensure that this gets called from overridden close()
995
+ methods.
996
+ """
997
+ #get the module data lock, as we're updating a shared structure.
998
+ _acquireLock()
999
+ try: #unlikely to raise an exception, but you never know...
1000
+ self._closed = True
1001
+ if self._name and self._name in _handlers:
1002
+ del _handlers[self._name]
1003
+ finally:
1004
+ _releaseLock()
1005
+
1006
+ def handleError(self, record):
1007
+ """
1008
+ Handle errors which occur during an emit() call.
1009
+
1010
+ This method should be called from handlers when an exception is
1011
+ encountered during an emit() call. If raiseExceptions is false,
1012
+ exceptions get silently ignored. This is what is mostly wanted
1013
+ for a logging system - most users will not care about errors in
1014
+ the logging system, they are more interested in application errors.
1015
+ You could, however, replace this with a custom handler if you wish.
1016
+ The record which was being processed is passed in to this method.
1017
+ """
1018
+ if raiseExceptions and sys.stderr: # see issue 13807
1019
+ t, v, tb = sys.exc_info()
1020
+ try:
1021
+ sys.stderr.write('--- Logging error ---\n')
1022
+ traceback.print_exception(t, v, tb, None, sys.stderr)
1023
+ sys.stderr.write('Call stack:\n')
1024
+ # Walk the stack frame up until we're out of logging,
1025
+ # so as to print the calling context.
1026
+ frame = tb.tb_frame
1027
+ while (frame and os.path.dirname(frame.f_code.co_filename) ==
1028
+ __path__[0]):
1029
+ frame = frame.f_back
1030
+ if frame:
1031
+ traceback.print_stack(frame, file=sys.stderr)
1032
+ else:
1033
+ # couldn't find the right stack frame, for some reason
1034
+ sys.stderr.write('Logged from file %s, line %s\n' % (
1035
+ record.filename, record.lineno))
1036
+ # Issue 18671: output logging message and arguments
1037
+ try:
1038
+ sys.stderr.write('Message: %r\n'
1039
+ 'Arguments: %s\n' % (record.msg,
1040
+ record.args))
1041
+ except RecursionError: # See issue 36272
1042
+ raise
1043
+ except Exception:
1044
+ sys.stderr.write('Unable to print the message and arguments'
1045
+ ' - possible formatting error.\nUse the'
1046
+ ' traceback above to help find the error.\n'
1047
+ )
1048
+ except OSError: #pragma: no cover
1049
+ pass # see issue 5971
1050
+ finally:
1051
+ del t, v, tb
1052
+
1053
+ def __repr__(self):
1054
+ level = getLevelName(self.level)
1055
+ return '<%s (%s)>' % (self.__class__.__name__, level)
1056
+
1057
+ class StreamHandler(Handler):
1058
+ """
1059
+ A handler class which writes logging records, appropriately formatted,
1060
+ to a stream. Note that this class does not close the stream, as
1061
+ sys.stdout or sys.stderr may be used.
1062
+ """
1063
+
1064
+ terminator = '\n'
1065
+
1066
+ def __init__(self, stream=None):
1067
+ """
1068
+ Initialize the handler.
1069
+
1070
+ If stream is not specified, sys.stderr is used.
1071
+ """
1072
+ Handler.__init__(self)
1073
+ if stream is None:
1074
+ stream = sys.stderr
1075
+ self.stream = stream
1076
+
1077
+ def flush(self):
1078
+ """
1079
+ Flushes the stream.
1080
+ """
1081
+ self.acquire()
1082
+ try:
1083
+ if self.stream and hasattr(self.stream, "flush"):
1084
+ self.stream.flush()
1085
+ finally:
1086
+ self.release()
1087
+
1088
+ def emit(self, record):
1089
+ """
1090
+ Emit a record.
1091
+
1092
+ If a formatter is specified, it is used to format the record.
1093
+ The record is then written to the stream with a trailing newline. If
1094
+ exception information is present, it is formatted using
1095
+ traceback.print_exception and appended to the stream. If the stream
1096
+ has an 'encoding' attribute, it is used to determine how to do the
1097
+ output to the stream.
1098
+ """
1099
+ try:
1100
+ msg = self.format(record)
1101
+ stream = self.stream
1102
+ # issue 35046: merged two stream.writes into one.
1103
+ stream.write(msg + self.terminator)
1104
+ self.flush()
1105
+ except RecursionError: # See issue 36272
1106
+ raise
1107
+ except Exception:
1108
+ self.handleError(record)
1109
+
1110
+ def setStream(self, stream):
1111
+ """
1112
+ Sets the StreamHandler's stream to the specified value,
1113
+ if it is different.
1114
+
1115
+ Returns the old stream, if the stream was changed, or None
1116
+ if it wasn't.
1117
+ """
1118
+ if stream is self.stream:
1119
+ result = None
1120
+ else:
1121
+ result = self.stream
1122
+ self.acquire()
1123
+ try:
1124
+ self.flush()
1125
+ self.stream = stream
1126
+ finally:
1127
+ self.release()
1128
+ return result
1129
+
1130
+ def __repr__(self):
1131
+ level = getLevelName(self.level)
1132
+ name = getattr(self.stream, 'name', '')
1133
+ # bpo-36015: name can be an int
1134
+ name = str(name)
1135
+ if name:
1136
+ name += ' '
1137
+ return '<%s %s(%s)>' % (self.__class__.__name__, name, level)
1138
+
1139
+
1140
+ class FileHandler(StreamHandler):
1141
+ """
1142
+ A handler class which writes formatted logging records to disk files.
1143
+ """
1144
+ def __init__(self, filename, mode='a', encoding=None, delay=False, errors=None):
1145
+ """
1146
+ Open the specified file and use it as the stream for logging.
1147
+ """
1148
+ # Issue #27493: add support for Path objects to be passed in
1149
+ filename = os.fspath(filename)
1150
+ #keep the absolute path, otherwise derived classes which use this
1151
+ #may come a cropper when the current directory changes
1152
+ self.baseFilename = os.path.abspath(filename)
1153
+ self.mode = mode
1154
+ self.encoding = encoding
1155
+ if "b" not in mode:
1156
+ self.encoding = io.text_encoding(encoding)
1157
+ self.errors = errors
1158
+ self.delay = delay
1159
+ # bpo-26789: FileHandler keeps a reference to the builtin open()
1160
+ # function to be able to open or reopen the file during Python
1161
+ # finalization.
1162
+ self._builtin_open = open
1163
+ if delay:
1164
+ #We don't open the stream, but we still need to call the
1165
+ #Handler constructor to set level, formatter, lock etc.
1166
+ Handler.__init__(self)
1167
+ self.stream = None
1168
+ else:
1169
+ StreamHandler.__init__(self, self._open())
1170
+
1171
+ def close(self):
1172
+ """
1173
+ Closes the stream.
1174
+ """
1175
+ self.acquire()
1176
+ try:
1177
+ try:
1178
+ if self.stream:
1179
+ try:
1180
+ self.flush()
1181
+ finally:
1182
+ stream = self.stream
1183
+ self.stream = None
1184
+ if hasattr(stream, "close"):
1185
+ stream.close()
1186
+ finally:
1187
+ # Issue #19523: call unconditionally to
1188
+ # prevent a handler leak when delay is set
1189
+ # Also see Issue #42378: we also rely on
1190
+ # self._closed being set to True there
1191
+ StreamHandler.close(self)
1192
+ finally:
1193
+ self.release()
1194
+
1195
+ def _open(self):
1196
+ """
1197
+ Open the current base file with the (original) mode and encoding.
1198
+ Return the resulting stream.
1199
+ """
1200
+ open_func = self._builtin_open
1201
+ return open_func(self.baseFilename, self.mode,
1202
+ encoding=self.encoding, errors=self.errors)
1203
+
1204
+ def emit(self, record):
1205
+ """
1206
+ Emit a record.
1207
+
1208
+ If the stream was not opened because 'delay' was specified in the
1209
+ constructor, open it before calling the superclass's emit.
1210
+
1211
+ If stream is not open, current mode is 'w' and `_closed=True`, record
1212
+ will not be emitted (see Issue #42378).
1213
+ """
1214
+ if self.stream is None:
1215
+ if self.mode != 'w' or not self._closed:
1216
+ self.stream = self._open()
1217
+ if self.stream:
1218
+ StreamHandler.emit(self, record)
1219
+
1220
+ def __repr__(self):
1221
+ level = getLevelName(self.level)
1222
+ return '<%s %s (%s)>' % (self.__class__.__name__, self.baseFilename, level)
1223
+
1224
+
1225
+ class _StderrHandler(StreamHandler):
1226
+ """
1227
+ This class is like a StreamHandler using sys.stderr, but always uses
1228
+ whatever sys.stderr is currently set to rather than the value of
1229
+ sys.stderr at handler construction time.
1230
+ """
1231
+ def __init__(self, level=NOTSET):
1232
+ """
1233
+ Initialize the handler.
1234
+ """
1235
+ Handler.__init__(self, level)
1236
+
1237
+ @property
1238
+ def stream(self):
1239
+ return sys.stderr
1240
+
1241
+
1242
+ _defaultLastResort = _StderrHandler(WARNING)
1243
+ lastResort = _defaultLastResort
1244
+
1245
+ #---------------------------------------------------------------------------
1246
+ # Manager classes and functions
1247
+ #---------------------------------------------------------------------------
1248
+
1249
+ class PlaceHolder(object):
1250
+ """
1251
+ PlaceHolder instances are used in the Manager logger hierarchy to take
1252
+ the place of nodes for which no loggers have been defined. This class is
1253
+ intended for internal use only and not as part of the public API.
1254
+ """
1255
+ def __init__(self, alogger):
1256
+ """
1257
+ Initialize with the specified logger being a child of this placeholder.
1258
+ """
1259
+ self.loggerMap = { alogger : None }
1260
+
1261
+ def append(self, alogger):
1262
+ """
1263
+ Add the specified logger as a child of this placeholder.
1264
+ """
1265
+ if alogger not in self.loggerMap:
1266
+ self.loggerMap[alogger] = None
1267
+
1268
+ #
1269
+ # Determine which class to use when instantiating loggers.
1270
+ #
1271
+
1272
+ def setLoggerClass(klass):
1273
+ """
1274
+ Set the class to be used when instantiating a logger. The class should
1275
+ define __init__() such that only a name argument is required, and the
1276
+ __init__() should call Logger.__init__()
1277
+ """
1278
+ if klass != Logger:
1279
+ if not issubclass(klass, Logger):
1280
+ raise TypeError("logger not derived from logging.Logger: "
1281
+ + klass.__name__)
1282
+ global _loggerClass
1283
+ _loggerClass = klass
1284
+
1285
+ def getLoggerClass():
1286
+ """
1287
+ Return the class to be used when instantiating a logger.
1288
+ """
1289
+ return _loggerClass
1290
+
1291
+ class Manager(object):
1292
+ """
1293
+ There is [under normal circumstances] just one Manager instance, which
1294
+ holds the hierarchy of loggers.
1295
+ """
1296
+ def __init__(self, rootnode):
1297
+ """
1298
+ Initialize the manager with the root node of the logger hierarchy.
1299
+ """
1300
+ self.root = rootnode
1301
+ self.disable = 0
1302
+ self.emittedNoHandlerWarning = False
1303
+ self.loggerDict = {}
1304
+ self.loggerClass = None
1305
+ self.logRecordFactory = None
1306
+
1307
+ @property
1308
+ def disable(self):
1309
+ return self._disable
1310
+
1311
+ @disable.setter
1312
+ def disable(self, value):
1313
+ self._disable = _checkLevel(value)
1314
+
1315
+ def getLogger(self, name):
1316
+ """
1317
+ Get a logger with the specified name (channel name), creating it
1318
+ if it doesn't yet exist. This name is a dot-separated hierarchical
1319
+ name, such as "a", "a.b", "a.b.c" or similar.
1320
+
1321
+ If a PlaceHolder existed for the specified name [i.e. the logger
1322
+ didn't exist but a child of it did], replace it with the created
1323
+ logger and fix up the parent/child references which pointed to the
1324
+ placeholder to now point to the logger.
1325
+ """
1326
+ rv = None
1327
+ if not isinstance(name, str):
1328
+ raise TypeError('A logger name must be a string')
1329
+ _acquireLock()
1330
+ try:
1331
+ if name in self.loggerDict:
1332
+ rv = self.loggerDict[name]
1333
+ if isinstance(rv, PlaceHolder):
1334
+ ph = rv
1335
+ rv = (self.loggerClass or _loggerClass)(name)
1336
+ rv.manager = self
1337
+ self.loggerDict[name] = rv
1338
+ self._fixupChildren(ph, rv)
1339
+ self._fixupParents(rv)
1340
+ else:
1341
+ rv = (self.loggerClass or _loggerClass)(name)
1342
+ rv.manager = self
1343
+ self.loggerDict[name] = rv
1344
+ self._fixupParents(rv)
1345
+ finally:
1346
+ _releaseLock()
1347
+ return rv
1348
+
1349
+ def setLoggerClass(self, klass):
1350
+ """
1351
+ Set the class to be used when instantiating a logger with this Manager.
1352
+ """
1353
+ if klass != Logger:
1354
+ if not issubclass(klass, Logger):
1355
+ raise TypeError("logger not derived from logging.Logger: "
1356
+ + klass.__name__)
1357
+ self.loggerClass = klass
1358
+
1359
+ def setLogRecordFactory(self, factory):
1360
+ """
1361
+ Set the factory to be used when instantiating a log record with this
1362
+ Manager.
1363
+ """
1364
+ self.logRecordFactory = factory
1365
+
1366
+ def _fixupParents(self, alogger):
1367
+ """
1368
+ Ensure that there are either loggers or placeholders all the way
1369
+ from the specified logger to the root of the logger hierarchy.
1370
+ """
1371
+ name = alogger.name
1372
+ i = name.rfind(".")
1373
+ rv = None
1374
+ while (i > 0) and not rv:
1375
+ substr = name[:i]
1376
+ if substr not in self.loggerDict:
1377
+ self.loggerDict[substr] = PlaceHolder(alogger)
1378
+ else:
1379
+ obj = self.loggerDict[substr]
1380
+ if isinstance(obj, Logger):
1381
+ rv = obj
1382
+ else:
1383
+ assert isinstance(obj, PlaceHolder)
1384
+ obj.append(alogger)
1385
+ i = name.rfind(".", 0, i - 1)
1386
+ if not rv:
1387
+ rv = self.root
1388
+ alogger.parent = rv
1389
+
1390
+ def _fixupChildren(self, ph, alogger):
1391
+ """
1392
+ Ensure that children of the placeholder ph are connected to the
1393
+ specified logger.
1394
+ """
1395
+ name = alogger.name
1396
+ namelen = len(name)
1397
+ for c in ph.loggerMap.keys():
1398
+ #The if means ... if not c.parent.name.startswith(nm)
1399
+ if c.parent.name[:namelen] != name:
1400
+ alogger.parent = c.parent
1401
+ c.parent = alogger
1402
+
1403
+ def _clear_cache(self):
1404
+ """
1405
+ Clear the cache for all loggers in loggerDict
1406
+ Called when level changes are made
1407
+ """
1408
+
1409
+ _acquireLock()
1410
+ for logger in self.loggerDict.values():
1411
+ if isinstance(logger, Logger):
1412
+ logger._cache.clear()
1413
+ self.root._cache.clear()
1414
+ _releaseLock()
1415
+
1416
+ #---------------------------------------------------------------------------
1417
+ # Logger classes and functions
1418
+ #---------------------------------------------------------------------------
1419
+
1420
+ class Logger(Filterer):
1421
+ """
1422
+ Instances of the Logger class represent a single logging channel. A
1423
+ "logging channel" indicates an area of an application. Exactly how an
1424
+ "area" is defined is up to the application developer. Since an
1425
+ application can have any number of areas, logging channels are identified
1426
+ by a unique string. Application areas can be nested (e.g. an area
1427
+ of "input processing" might include sub-areas "read CSV files", "read
1428
+ XLS files" and "read Gnumeric files"). To cater for this natural nesting,
1429
+ channel names are organized into a namespace hierarchy where levels are
1430
+ separated by periods, much like the Java or Python package namespace. So
1431
+ in the instance given above, channel names might be "input" for the upper
1432
+ level, and "input.csv", "input.xls" and "input.gnu" for the sub-levels.
1433
+ There is no arbitrary limit to the depth of nesting.
1434
+ """
1435
+ def __init__(self, name, level=NOTSET):
1436
+ """
1437
+ Initialize the logger with a name and an optional level.
1438
+ """
1439
+ Filterer.__init__(self)
1440
+ self.name = name
1441
+ self.level = _checkLevel(level)
1442
+ self.parent = None
1443
+ self.propagate = True
1444
+ self.handlers = []
1445
+ self.disabled = False
1446
+ self._cache = {}
1447
+
1448
+ def setLevel(self, level):
1449
+ """
1450
+ Set the logging level of this logger. level must be an int or a str.
1451
+ """
1452
+ self.level = _checkLevel(level)
1453
+ self.manager._clear_cache()
1454
+
1455
+ def debug(self, msg, *args, **kwargs):
1456
+ """
1457
+ Log 'msg % args' with severity 'DEBUG'.
1458
+
1459
+ To pass exception information, use the keyword argument exc_info with
1460
+ a true value, e.g.
1461
+
1462
+ logger.debug("Houston, we have a %s", "thorny problem", exc_info=1)
1463
+ """
1464
+ if self.isEnabledFor(DEBUG):
1465
+ self._log(DEBUG, msg, args, **kwargs)
1466
+
1467
+ def info(self, msg, *args, **kwargs):
1468
+ """
1469
+ Log 'msg % args' with severity 'INFO'.
1470
+
1471
+ To pass exception information, use the keyword argument exc_info with
1472
+ a true value, e.g.
1473
+
1474
+ logger.info("Houston, we have a %s", "interesting problem", exc_info=1)
1475
+ """
1476
+ if self.isEnabledFor(INFO):
1477
+ self._log(INFO, msg, args, **kwargs)
1478
+
1479
+ def warning(self, msg, *args, **kwargs):
1480
+ """
1481
+ Log 'msg % args' with severity 'WARNING'.
1482
+
1483
+ To pass exception information, use the keyword argument exc_info with
1484
+ a true value, e.g.
1485
+
1486
+ logger.warning("Houston, we have a %s", "bit of a problem", exc_info=1)
1487
+ """
1488
+ if self.isEnabledFor(WARNING):
1489
+ self._log(WARNING, msg, args, **kwargs)
1490
+
1491
+ def warn(self, msg, *args, **kwargs):
1492
+ warnings.warn("The 'warn' method is deprecated, "
1493
+ "use 'warning' instead", DeprecationWarning, 2)
1494
+ self.warning(msg, *args, **kwargs)
1495
+
1496
+ def error(self, msg, *args, **kwargs):
1497
+ """
1498
+ Log 'msg % args' with severity 'ERROR'.
1499
+
1500
+ To pass exception information, use the keyword argument exc_info with
1501
+ a true value, e.g.
1502
+
1503
+ logger.error("Houston, we have a %s", "major problem", exc_info=1)
1504
+ """
1505
+ if self.isEnabledFor(ERROR):
1506
+ self._log(ERROR, msg, args, **kwargs)
1507
+
1508
+ def exception(self, msg, *args, exc_info=True, **kwargs):
1509
+ """
1510
+ Convenience method for logging an ERROR with exception information.
1511
+ """
1512
+ self.error(msg, *args, exc_info=exc_info, **kwargs)
1513
+
1514
+ def critical(self, msg, *args, **kwargs):
1515
+ """
1516
+ Log 'msg % args' with severity 'CRITICAL'.
1517
+
1518
+ To pass exception information, use the keyword argument exc_info with
1519
+ a true value, e.g.
1520
+
1521
+ logger.critical("Houston, we have a %s", "major disaster", exc_info=1)
1522
+ """
1523
+ if self.isEnabledFor(CRITICAL):
1524
+ self._log(CRITICAL, msg, args, **kwargs)
1525
+
1526
+ def fatal(self, msg, *args, **kwargs):
1527
+ """
1528
+ Don't use this method, use critical() instead.
1529
+ """
1530
+ self.critical(msg, *args, **kwargs)
1531
+
1532
+ def log(self, level, msg, *args, **kwargs):
1533
+ """
1534
+ Log 'msg % args' with the integer severity 'level'.
1535
+
1536
+ To pass exception information, use the keyword argument exc_info with
1537
+ a true value, e.g.
1538
+
1539
+ logger.log(level, "We have a %s", "mysterious problem", exc_info=1)
1540
+ """
1541
+ if not isinstance(level, int):
1542
+ if raiseExceptions:
1543
+ raise TypeError("level must be an integer")
1544
+ else:
1545
+ return
1546
+ if self.isEnabledFor(level):
1547
+ self._log(level, msg, args, **kwargs)
1548
+
1549
+ def findCaller(self, stack_info=False, stacklevel=1):
1550
+ """
1551
+ Find the stack frame of the caller so that we can note the source
1552
+ file name, line number and function name.
1553
+ """
1554
+ f = currentframe()
1555
+ #On some versions of IronPython, currentframe() returns None if
1556
+ #IronPython isn't run with -X:Frames.
1557
+ if f is not None:
1558
+ f = f.f_back
1559
+ orig_f = f
1560
+ while f and stacklevel > 1:
1561
+ f = f.f_back
1562
+ stacklevel -= 1
1563
+ if not f:
1564
+ f = orig_f
1565
+ rv = "(unknown file)", 0, "(unknown function)", None
1566
+ while hasattr(f, "f_code"):
1567
+ co = f.f_code
1568
+ filename = os.path.normcase(co.co_filename)
1569
+ if filename == _srcfile:
1570
+ f = f.f_back
1571
+ continue
1572
+ sinfo = None
1573
+ if stack_info:
1574
+ sio = io.StringIO()
1575
+ sio.write('Stack (most recent call last):\n')
1576
+ traceback.print_stack(f, file=sio)
1577
+ sinfo = sio.getvalue()
1578
+ if sinfo[-1] == '\n':
1579
+ sinfo = sinfo[:-1]
1580
+ sio.close()
1581
+ rv = (co.co_filename, f.f_lineno, co.co_name, sinfo)
1582
+ break
1583
+ return rv
1584
+
1585
+ def makeRecord(self, name, level, fn, lno, msg, args, exc_info,
1586
+ func=None, extra=None, sinfo=None):
1587
+ """
1588
+ A factory method which can be overridden in subclasses to create
1589
+ specialized LogRecords.
1590
+ """
1591
+ rv = _logRecordFactory(name, level, fn, lno, msg, args, exc_info, func,
1592
+ sinfo)
1593
+ if extra is not None:
1594
+ for key in extra:
1595
+ if (key in ["message", "asctime"]) or (key in rv.__dict__):
1596
+ raise KeyError("Attempt to overwrite %r in LogRecord" % key)
1597
+ rv.__dict__[key] = extra[key]
1598
+ return rv
1599
+
1600
+ def _log(self, level, msg, args, exc_info=None, extra=None, stack_info=False,
1601
+ stacklevel=1):
1602
+ """
1603
+ Low-level logging routine which creates a LogRecord and then calls
1604
+ all the handlers of this logger to handle the record.
1605
+ """
1606
+ sinfo = None
1607
+ if _srcfile:
1608
+ #IronPython doesn't track Python frames, so findCaller raises an
1609
+ #exception on some versions of IronPython. We trap it here so that
1610
+ #IronPython can use logging.
1611
+ try:
1612
+ fn, lno, func, sinfo = self.findCaller(stack_info, stacklevel)
1613
+ except ValueError: # pragma: no cover
1614
+ fn, lno, func = "(unknown file)", 0, "(unknown function)"
1615
+ else: # pragma: no cover
1616
+ fn, lno, func = "(unknown file)", 0, "(unknown function)"
1617
+ if exc_info:
1618
+ if isinstance(exc_info, BaseException):
1619
+ exc_info = (type(exc_info), exc_info, exc_info.__traceback__)
1620
+ elif not isinstance(exc_info, tuple):
1621
+ exc_info = sys.exc_info()
1622
+ record = self.makeRecord(self.name, level, fn, lno, msg, args,
1623
+ exc_info, func, extra, sinfo)
1624
+ self.handle(record)
1625
+
1626
+ def handle(self, record):
1627
+ """
1628
+ Call the handlers for the specified record.
1629
+
1630
+ This method is used for unpickled records received from a socket, as
1631
+ well as those created locally. Logger-level filtering is applied.
1632
+ """
1633
+ if (not self.disabled) and self.filter(record):
1634
+ self.callHandlers(record)
1635
+
1636
+ def addHandler(self, hdlr):
1637
+ """
1638
+ Add the specified handler to this logger.
1639
+ """
1640
+ _acquireLock()
1641
+ try:
1642
+ if not (hdlr in self.handlers):
1643
+ self.handlers.append(hdlr)
1644
+ finally:
1645
+ _releaseLock()
1646
+
1647
+ def removeHandler(self, hdlr):
1648
+ """
1649
+ Remove the specified handler from this logger.
1650
+ """
1651
+ _acquireLock()
1652
+ try:
1653
+ if hdlr in self.handlers:
1654
+ self.handlers.remove(hdlr)
1655
+ finally:
1656
+ _releaseLock()
1657
+
1658
+ def hasHandlers(self):
1659
+ """
1660
+ See if this logger has any handlers configured.
1661
+
1662
+ Loop through all handlers for this logger and its parents in the
1663
+ logger hierarchy. Return True if a handler was found, else False.
1664
+ Stop searching up the hierarchy whenever a logger with the "propagate"
1665
+ attribute set to zero is found - that will be the last logger which
1666
+ is checked for the existence of handlers.
1667
+ """
1668
+ c = self
1669
+ rv = False
1670
+ while c:
1671
+ if c.handlers:
1672
+ rv = True
1673
+ break
1674
+ if not c.propagate:
1675
+ break
1676
+ else:
1677
+ c = c.parent
1678
+ return rv
1679
+
1680
+ def callHandlers(self, record):
1681
+ """
1682
+ Pass a record to all relevant handlers.
1683
+
1684
+ Loop through all handlers for this logger and its parents in the
1685
+ logger hierarchy. If no handler was found, output a one-off error
1686
+ message to sys.stderr. Stop searching up the hierarchy whenever a
1687
+ logger with the "propagate" attribute set to zero is found - that
1688
+ will be the last logger whose handlers are called.
1689
+ """
1690
+ c = self
1691
+ found = 0
1692
+ while c:
1693
+ for hdlr in c.handlers:
1694
+ found = found + 1
1695
+ if record.levelno >= hdlr.level:
1696
+ hdlr.handle(record)
1697
+ if not c.propagate:
1698
+ c = None #break out
1699
+ else:
1700
+ c = c.parent
1701
+ if (found == 0):
1702
+ if lastResort:
1703
+ if record.levelno >= lastResort.level:
1704
+ lastResort.handle(record)
1705
+ elif raiseExceptions and not self.manager.emittedNoHandlerWarning:
1706
+ sys.stderr.write("No handlers could be found for logger"
1707
+ " \"%s\"\n" % self.name)
1708
+ self.manager.emittedNoHandlerWarning = True
1709
+
1710
+ def getEffectiveLevel(self):
1711
+ """
1712
+ Get the effective level for this logger.
1713
+
1714
+ Loop through this logger and its parents in the logger hierarchy,
1715
+ looking for a non-zero logging level. Return the first one found.
1716
+ """
1717
+ logger = self
1718
+ while logger:
1719
+ if logger.level:
1720
+ return logger.level
1721
+ logger = logger.parent
1722
+ return NOTSET
1723
+
1724
+ def isEnabledFor(self, level):
1725
+ """
1726
+ Is this logger enabled for level 'level'?
1727
+ """
1728
+ if self.disabled:
1729
+ return False
1730
+
1731
+ try:
1732
+ return self._cache[level]
1733
+ except KeyError:
1734
+ _acquireLock()
1735
+ try:
1736
+ if self.manager.disable >= level:
1737
+ is_enabled = self._cache[level] = False
1738
+ else:
1739
+ is_enabled = self._cache[level] = (
1740
+ level >= self.getEffectiveLevel()
1741
+ )
1742
+ finally:
1743
+ _releaseLock()
1744
+ return is_enabled
1745
+
1746
+ def getChild(self, suffix):
1747
+ """
1748
+ Get a logger which is a descendant to this one.
1749
+
1750
+ This is a convenience method, such that
1751
+
1752
+ logging.getLogger('abc').getChild('def.ghi')
1753
+
1754
+ is the same as
1755
+
1756
+ logging.getLogger('abc.def.ghi')
1757
+
1758
+ It's useful, for example, when the parent logger is named using
1759
+ __name__ rather than a literal string.
1760
+ """
1761
+ if self.root is not self:
1762
+ suffix = '.'.join((self.name, suffix))
1763
+ return self.manager.getLogger(suffix)
1764
+
1765
+ def __repr__(self):
1766
+ level = getLevelName(self.getEffectiveLevel())
1767
+ return '<%s %s (%s)>' % (self.__class__.__name__, self.name, level)
1768
+
1769
+ def __reduce__(self):
1770
+ # In general, only the root logger will not be accessible via its name.
1771
+ # However, the root logger's class has its own __reduce__ method.
1772
+ if getLogger(self.name) is not self:
1773
+ import pickle
1774
+ raise pickle.PicklingError('logger cannot be pickled')
1775
+ return getLogger, (self.name,)
1776
+
1777
+
1778
+ class RootLogger(Logger):
1779
+ """
1780
+ A root logger is not that different to any other logger, except that
1781
+ it must have a logging level and there is only one instance of it in
1782
+ the hierarchy.
1783
+ """
1784
+ def __init__(self, level):
1785
+ """
1786
+ Initialize the logger with the name "root".
1787
+ """
1788
+ Logger.__init__(self, "root", level)
1789
+
1790
+ def __reduce__(self):
1791
+ return getLogger, ()
1792
+
1793
+ _loggerClass = Logger
1794
+
1795
+ class LoggerAdapter(object):
1796
+ """
1797
+ An adapter for loggers which makes it easier to specify contextual
1798
+ information in logging output.
1799
+ """
1800
+
1801
+ def __init__(self, logger, extra=None):
1802
+ """
1803
+ Initialize the adapter with a logger and a dict-like object which
1804
+ provides contextual information. This constructor signature allows
1805
+ easy stacking of LoggerAdapters, if so desired.
1806
+
1807
+ You can effectively pass keyword arguments as shown in the
1808
+ following example:
1809
+
1810
+ adapter = LoggerAdapter(someLogger, dict(p1=v1, p2="v2"))
1811
+ """
1812
+ self.logger = logger
1813
+ self.extra = extra
1814
+
1815
+ def process(self, msg, kwargs):
1816
+ """
1817
+ Process the logging message and keyword arguments passed in to
1818
+ a logging call to insert contextual information. You can either
1819
+ manipulate the message itself, the keyword args or both. Return
1820
+ the message and kwargs modified (or not) to suit your needs.
1821
+
1822
+ Normally, you'll only need to override this one method in a
1823
+ LoggerAdapter subclass for your specific needs.
1824
+ """
1825
+ kwargs["extra"] = self.extra
1826
+ return msg, kwargs
1827
+
1828
+ #
1829
+ # Boilerplate convenience methods
1830
+ #
1831
+ def debug(self, msg, *args, **kwargs):
1832
+ """
1833
+ Delegate a debug call to the underlying logger.
1834
+ """
1835
+ self.log(DEBUG, msg, *args, **kwargs)
1836
+
1837
+ def info(self, msg, *args, **kwargs):
1838
+ """
1839
+ Delegate an info call to the underlying logger.
1840
+ """
1841
+ self.log(INFO, msg, *args, **kwargs)
1842
+
1843
+ def warning(self, msg, *args, **kwargs):
1844
+ """
1845
+ Delegate a warning call to the underlying logger.
1846
+ """
1847
+ self.log(WARNING, msg, *args, **kwargs)
1848
+
1849
+ def warn(self, msg, *args, **kwargs):
1850
+ warnings.warn("The 'warn' method is deprecated, "
1851
+ "use 'warning' instead", DeprecationWarning, 2)
1852
+ self.warning(msg, *args, **kwargs)
1853
+
1854
+ def error(self, msg, *args, **kwargs):
1855
+ """
1856
+ Delegate an error call to the underlying logger.
1857
+ """
1858
+ self.log(ERROR, msg, *args, **kwargs)
1859
+
1860
+ def exception(self, msg, *args, exc_info=True, **kwargs):
1861
+ """
1862
+ Delegate an exception call to the underlying logger.
1863
+ """
1864
+ self.log(ERROR, msg, *args, exc_info=exc_info, **kwargs)
1865
+
1866
+ def critical(self, msg, *args, **kwargs):
1867
+ """
1868
+ Delegate a critical call to the underlying logger.
1869
+ """
1870
+ self.log(CRITICAL, msg, *args, **kwargs)
1871
+
1872
+ def log(self, level, msg, *args, **kwargs):
1873
+ """
1874
+ Delegate a log call to the underlying logger, after adding
1875
+ contextual information from this adapter instance.
1876
+ """
1877
+ if self.isEnabledFor(level):
1878
+ msg, kwargs = self.process(msg, kwargs)
1879
+ self.logger.log(level, msg, *args, **kwargs)
1880
+
1881
+ def isEnabledFor(self, level):
1882
+ """
1883
+ Is this logger enabled for level 'level'?
1884
+ """
1885
+ return self.logger.isEnabledFor(level)
1886
+
1887
+ def setLevel(self, level):
1888
+ """
1889
+ Set the specified level on the underlying logger.
1890
+ """
1891
+ self.logger.setLevel(level)
1892
+
1893
+ def getEffectiveLevel(self):
1894
+ """
1895
+ Get the effective level for the underlying logger.
1896
+ """
1897
+ return self.logger.getEffectiveLevel()
1898
+
1899
+ def hasHandlers(self):
1900
+ """
1901
+ See if the underlying logger has any handlers.
1902
+ """
1903
+ return self.logger.hasHandlers()
1904
+
1905
+ def _log(self, level, msg, args, exc_info=None, extra=None, stack_info=False):
1906
+ """
1907
+ Low-level log implementation, proxied to allow nested logger adapters.
1908
+ """
1909
+ return self.logger._log(
1910
+ level,
1911
+ msg,
1912
+ args,
1913
+ exc_info=exc_info,
1914
+ extra=extra,
1915
+ stack_info=stack_info,
1916
+ )
1917
+
1918
+ @property
1919
+ def manager(self):
1920
+ return self.logger.manager
1921
+
1922
+ @manager.setter
1923
+ def manager(self, value):
1924
+ self.logger.manager = value
1925
+
1926
+ @property
1927
+ def name(self):
1928
+ return self.logger.name
1929
+
1930
+ def __repr__(self):
1931
+ logger = self.logger
1932
+ level = getLevelName(logger.getEffectiveLevel())
1933
+ return '<%s %s (%s)>' % (self.__class__.__name__, logger.name, level)
1934
+
1935
+ root = RootLogger(WARNING)
1936
+ Logger.root = root
1937
+ Logger.manager = Manager(Logger.root)
1938
+
1939
+ #---------------------------------------------------------------------------
1940
+ # Configuration classes and functions
1941
+ #---------------------------------------------------------------------------
1942
+
1943
+ def basicConfig(**kwargs):
1944
+ """
1945
+ Do basic configuration for the logging system.
1946
+
1947
+ This function does nothing if the root logger already has handlers
1948
+ configured, unless the keyword argument *force* is set to ``True``.
1949
+ It is a convenience method intended for use by simple scripts
1950
+ to do one-shot configuration of the logging package.
1951
+
1952
+ The default behaviour is to create a StreamHandler which writes to
1953
+ sys.stderr, set a formatter using the BASIC_FORMAT format string, and
1954
+ add the handler to the root logger.
1955
+
1956
+ A number of optional keyword arguments may be specified, which can alter
1957
+ the default behaviour.
1958
+
1959
+ filename Specifies that a FileHandler be created, using the specified
1960
+ filename, rather than a StreamHandler.
1961
+ filemode Specifies the mode to open the file, if filename is specified
1962
+ (if filemode is unspecified, it defaults to 'a').
1963
+ format Use the specified format string for the handler.
1964
+ datefmt Use the specified date/time format.
1965
+ style If a format string is specified, use this to specify the
1966
+ type of format string (possible values '%', '{', '$', for
1967
+ %-formatting, :meth:`str.format` and :class:`string.Template`
1968
+ - defaults to '%').
1969
+ level Set the root logger level to the specified level.
1970
+ stream Use the specified stream to initialize the StreamHandler. Note
1971
+ that this argument is incompatible with 'filename' - if both
1972
+ are present, 'stream' is ignored.
1973
+ handlers If specified, this should be an iterable of already created
1974
+ handlers, which will be added to the root handler. Any handler
1975
+ in the list which does not have a formatter assigned will be
1976
+ assigned the formatter created in this function.
1977
+ force If this keyword is specified as true, any existing handlers
1978
+ attached to the root logger are removed and closed, before
1979
+ carrying out the configuration as specified by the other
1980
+ arguments.
1981
+ encoding If specified together with a filename, this encoding is passed to
1982
+ the created FileHandler, causing it to be used when the file is
1983
+ opened.
1984
+ errors If specified together with a filename, this value is passed to the
1985
+ created FileHandler, causing it to be used when the file is
1986
+ opened in text mode. If not specified, the default value is
1987
+ `backslashreplace`.
1988
+
1989
+ Note that you could specify a stream created using open(filename, mode)
1990
+ rather than passing the filename and mode in. However, it should be
1991
+ remembered that StreamHandler does not close its stream (since it may be
1992
+ using sys.stdout or sys.stderr), whereas FileHandler closes its stream
1993
+ when the handler is closed.
1994
+
1995
+ .. versionchanged:: 3.2
1996
+ Added the ``style`` parameter.
1997
+
1998
+ .. versionchanged:: 3.3
1999
+ Added the ``handlers`` parameter. A ``ValueError`` is now thrown for
2000
+ incompatible arguments (e.g. ``handlers`` specified together with
2001
+ ``filename``/``filemode``, or ``filename``/``filemode`` specified
2002
+ together with ``stream``, or ``handlers`` specified together with
2003
+ ``stream``.
2004
+
2005
+ .. versionchanged:: 3.8
2006
+ Added the ``force`` parameter.
2007
+
2008
+ .. versionchanged:: 3.9
2009
+ Added the ``encoding`` and ``errors`` parameters.
2010
+ """
2011
+ # Add thread safety in case someone mistakenly calls
2012
+ # basicConfig() from multiple threads
2013
+ _acquireLock()
2014
+ try:
2015
+ force = kwargs.pop('force', False)
2016
+ encoding = kwargs.pop('encoding', None)
2017
+ errors = kwargs.pop('errors', 'backslashreplace')
2018
+ if force:
2019
+ for h in root.handlers[:]:
2020
+ root.removeHandler(h)
2021
+ h.close()
2022
+ if len(root.handlers) == 0:
2023
+ handlers = kwargs.pop("handlers", None)
2024
+ if handlers is None:
2025
+ if "stream" in kwargs and "filename" in kwargs:
2026
+ raise ValueError("'stream' and 'filename' should not be "
2027
+ "specified together")
2028
+ else:
2029
+ if "stream" in kwargs or "filename" in kwargs:
2030
+ raise ValueError("'stream' or 'filename' should not be "
2031
+ "specified together with 'handlers'")
2032
+ if handlers is None:
2033
+ filename = kwargs.pop("filename", None)
2034
+ mode = kwargs.pop("filemode", 'a')
2035
+ if filename:
2036
+ if 'b' in mode:
2037
+ errors = None
2038
+ else:
2039
+ encoding = io.text_encoding(encoding)
2040
+ h = FileHandler(filename, mode,
2041
+ encoding=encoding, errors=errors)
2042
+ else:
2043
+ stream = kwargs.pop("stream", None)
2044
+ h = StreamHandler(stream)
2045
+ handlers = [h]
2046
+ dfs = kwargs.pop("datefmt", None)
2047
+ style = kwargs.pop("style", '%')
2048
+ if style not in _STYLES:
2049
+ raise ValueError('Style must be one of: %s' % ','.join(
2050
+ _STYLES.keys()))
2051
+ fs = kwargs.pop("format", _STYLES[style][1])
2052
+ fmt = Formatter(fs, dfs, style)
2053
+ for h in handlers:
2054
+ if h.formatter is None:
2055
+ h.setFormatter(fmt)
2056
+ root.addHandler(h)
2057
+ level = kwargs.pop("level", None)
2058
+ if level is not None:
2059
+ root.setLevel(level)
2060
+ if kwargs:
2061
+ keys = ', '.join(kwargs.keys())
2062
+ raise ValueError('Unrecognised argument(s): %s' % keys)
2063
+ finally:
2064
+ _releaseLock()
2065
+
2066
+ #---------------------------------------------------------------------------
2067
+ # Utility functions at module level.
2068
+ # Basically delegate everything to the root logger.
2069
+ #---------------------------------------------------------------------------
2070
+
2071
+ def getLogger(name=None):
2072
+ """
2073
+ Return a logger with the specified name, creating it if necessary.
2074
+
2075
+ If no name is specified, return the root logger.
2076
+ """
2077
+ if not name or isinstance(name, str) and name == root.name:
2078
+ return root
2079
+ return Logger.manager.getLogger(name)
2080
+
2081
+ def critical(msg, *args, **kwargs):
2082
+ """
2083
+ Log a message with severity 'CRITICAL' on the root logger. If the logger
2084
+ has no handlers, call basicConfig() to add a console handler with a
2085
+ pre-defined format.
2086
+ """
2087
+ if len(root.handlers) == 0:
2088
+ basicConfig()
2089
+ root.critical(msg, *args, **kwargs)
2090
+
2091
+ def fatal(msg, *args, **kwargs):
2092
+ """
2093
+ Don't use this function, use critical() instead.
2094
+ """
2095
+ critical(msg, *args, **kwargs)
2096
+
2097
+ def error(msg, *args, **kwargs):
2098
+ """
2099
+ Log a message with severity 'ERROR' on the root logger. If the logger has
2100
+ no handlers, call basicConfig() to add a console handler with a pre-defined
2101
+ format.
2102
+ """
2103
+ if len(root.handlers) == 0:
2104
+ basicConfig()
2105
+ root.error(msg, *args, **kwargs)
2106
+
2107
+ def exception(msg, *args, exc_info=True, **kwargs):
2108
+ """
2109
+ Log a message with severity 'ERROR' on the root logger, with exception
2110
+ information. If the logger has no handlers, basicConfig() is called to add
2111
+ a console handler with a pre-defined format.
2112
+ """
2113
+ error(msg, *args, exc_info=exc_info, **kwargs)
2114
+
2115
+ def warning(msg, *args, **kwargs):
2116
+ """
2117
+ Log a message with severity 'WARNING' on the root logger. If the logger has
2118
+ no handlers, call basicConfig() to add a console handler with a pre-defined
2119
+ format.
2120
+ """
2121
+ if len(root.handlers) == 0:
2122
+ basicConfig()
2123
+ root.warning(msg, *args, **kwargs)
2124
+
2125
+ def warn(msg, *args, **kwargs):
2126
+ warnings.warn("The 'warn' function is deprecated, "
2127
+ "use 'warning' instead", DeprecationWarning, 2)
2128
+ warning(msg, *args, **kwargs)
2129
+
2130
+ def info(msg, *args, **kwargs):
2131
+ """
2132
+ Log a message with severity 'INFO' on the root logger. If the logger has
2133
+ no handlers, call basicConfig() to add a console handler with a pre-defined
2134
+ format.
2135
+ """
2136
+ if len(root.handlers) == 0:
2137
+ basicConfig()
2138
+ root.info(msg, *args, **kwargs)
2139
+
2140
+ def debug(msg, *args, **kwargs):
2141
+ """
2142
+ Log a message with severity 'DEBUG' on the root logger. If the logger has
2143
+ no handlers, call basicConfig() to add a console handler with a pre-defined
2144
+ format.
2145
+ """
2146
+ if len(root.handlers) == 0:
2147
+ basicConfig()
2148
+ root.debug(msg, *args, **kwargs)
2149
+
2150
+ def log(level, msg, *args, **kwargs):
2151
+ """
2152
+ Log 'msg % args' with the integer severity 'level' on the root logger. If
2153
+ the logger has no handlers, call basicConfig() to add a console handler
2154
+ with a pre-defined format.
2155
+ """
2156
+ if len(root.handlers) == 0:
2157
+ basicConfig()
2158
+ root.log(level, msg, *args, **kwargs)
2159
+
2160
+ def disable(level=CRITICAL):
2161
+ """
2162
+ Disable all logging calls of severity 'level' and below.
2163
+ """
2164
+ root.manager.disable = level
2165
+ root.manager._clear_cache()
2166
+
2167
+ def shutdown(handlerList=_handlerList):
2168
+ """
2169
+ Perform any cleanup actions in the logging system (e.g. flushing
2170
+ buffers).
2171
+
2172
+ Should be called at application exit.
2173
+ """
2174
+ for wr in reversed(handlerList[:]):
2175
+ #errors might occur, for example, if files are locked
2176
+ #we just ignore them if raiseExceptions is not set
2177
+ try:
2178
+ h = wr()
2179
+ if h:
2180
+ try:
2181
+ h.acquire()
2182
+ h.flush()
2183
+ h.close()
2184
+ except (OSError, ValueError):
2185
+ # Ignore errors which might be caused
2186
+ # because handlers have been closed but
2187
+ # references to them are still around at
2188
+ # application exit.
2189
+ pass
2190
+ finally:
2191
+ h.release()
2192
+ except: # ignore everything, as we're shutting down
2193
+ if raiseExceptions:
2194
+ raise
2195
+ #else, swallow
2196
+
2197
+ #Let's try and shutdown automatically on application exit...
2198
+ import atexit
2199
+ atexit.register(shutdown)
2200
+
2201
+ # Null handler
2202
+
2203
+ class NullHandler(Handler):
2204
+ """
2205
+ This handler does nothing. It's intended to be used to avoid the
2206
+ "No handlers could be found for logger XXX" one-off warning. This is
2207
+ important for library code, which may contain code to log events. If a user
2208
+ of the library does not configure logging, the one-off warning might be
2209
+ produced; to avoid this, the library developer simply needs to instantiate
2210
+ a NullHandler and add it to the top-level logger of the library module or
2211
+ package.
2212
+ """
2213
+ def handle(self, record):
2214
+ """Stub."""
2215
+
2216
+ def emit(self, record):
2217
+ """Stub."""
2218
+
2219
+ def createLock(self):
2220
+ self.lock = None
2221
+
2222
+ def _at_fork_reinit(self):
2223
+ pass
2224
+
2225
+ # Warnings integration
2226
+
2227
+ _warnings_showwarning = None
2228
+
2229
+ def _showwarning(message, category, filename, lineno, file=None, line=None):
2230
+ """
2231
+ Implementation of showwarnings which redirects to logging, which will first
2232
+ check to see if the file parameter is None. If a file is specified, it will
2233
+ delegate to the original warnings implementation of showwarning. Otherwise,
2234
+ it will call warnings.formatwarning and will log the resulting string to a
2235
+ warnings logger named "py.warnings" with level logging.WARNING.
2236
+ """
2237
+ if file is not None:
2238
+ if _warnings_showwarning is not None:
2239
+ _warnings_showwarning(message, category, filename, lineno, file, line)
2240
+ else:
2241
+ s = warnings.formatwarning(message, category, filename, lineno, line)
2242
+ logger = getLogger("py.warnings")
2243
+ if not logger.handlers:
2244
+ logger.addHandler(NullHandler())
2245
+ logger.warning("%s", s)
2246
+
2247
+ def captureWarnings(capture):
2248
+ """
2249
+ If capture is true, redirect all warnings to the logging package.
2250
+ If capture is False, ensure that warnings are not redirected to logging
2251
+ but to their original destinations.
2252
+ """
2253
+ global _warnings_showwarning
2254
+ if capture:
2255
+ if _warnings_showwarning is None:
2256
+ _warnings_showwarning = warnings.showwarning
2257
+ warnings.showwarning = _showwarning
2258
+ else:
2259
+ if _warnings_showwarning is not None:
2260
+ warnings.showwarning = _warnings_showwarning
2261
+ _warnings_showwarning = None
valley/lib/python3.10/logging/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (66.9 kB). View file
 
valley/lib/python3.10/logging/__pycache__/config.cpython-310.pyc ADDED
Binary file (23.4 kB). View file
 
valley/lib/python3.10/logging/__pycache__/handlers.cpython-310.pyc ADDED
Binary file (44.9 kB). View file
 
valley/lib/python3.10/logging/config.py ADDED
@@ -0,0 +1,947 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2001-2019 by Vinay Sajip. All Rights Reserved.
2
+ #
3
+ # Permission to use, copy, modify, and distribute this software and its
4
+ # documentation for any purpose and without fee is hereby granted,
5
+ # provided that the above copyright notice appear in all copies and that
6
+ # both that copyright notice and this permission notice appear in
7
+ # supporting documentation, and that the name of Vinay Sajip
8
+ # not be used in advertising or publicity pertaining to distribution
9
+ # of the software without specific, written prior permission.
10
+ # VINAY SAJIP DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
11
+ # ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
12
+ # VINAY SAJIP BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
13
+ # ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
14
+ # IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
15
+ # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16
+
17
+ """
18
+ Configuration functions for the logging package for Python. The core package
19
+ is based on PEP 282 and comments thereto in comp.lang.python, and influenced
20
+ by Apache's log4j system.
21
+
22
+ Copyright (C) 2001-2019 Vinay Sajip. All Rights Reserved.
23
+
24
+ To use, simply 'import logging' and log away!
25
+ """
26
+
27
+ import errno
28
+ import io
29
+ import logging
30
+ import logging.handlers
31
+ import re
32
+ import struct
33
+ import sys
34
+ import threading
35
+ import traceback
36
+
37
+ from socketserver import ThreadingTCPServer, StreamRequestHandler
38
+
39
+
40
+ DEFAULT_LOGGING_CONFIG_PORT = 9030
41
+
42
+ RESET_ERROR = errno.ECONNRESET
43
+
44
+ #
45
+ # The following code implements a socket listener for on-the-fly
46
+ # reconfiguration of logging.
47
+ #
48
+ # _listener holds the server object doing the listening
49
+ _listener = None
50
+
51
+ def fileConfig(fname, defaults=None, disable_existing_loggers=True, encoding=None):
52
+ """
53
+ Read the logging configuration from a ConfigParser-format file.
54
+
55
+ This can be called several times from an application, allowing an end user
56
+ the ability to select from various pre-canned configurations (if the
57
+ developer provides a mechanism to present the choices and load the chosen
58
+ configuration).
59
+ """
60
+ import configparser
61
+
62
+ if isinstance(fname, configparser.RawConfigParser):
63
+ cp = fname
64
+ else:
65
+ cp = configparser.ConfigParser(defaults)
66
+ if hasattr(fname, 'readline'):
67
+ cp.read_file(fname)
68
+ else:
69
+ encoding = io.text_encoding(encoding)
70
+ cp.read(fname, encoding=encoding)
71
+
72
+ formatters = _create_formatters(cp)
73
+
74
+ # critical section
75
+ logging._acquireLock()
76
+ try:
77
+ _clearExistingHandlers()
78
+
79
+ # Handlers add themselves to logging._handlers
80
+ handlers = _install_handlers(cp, formatters)
81
+ _install_loggers(cp, handlers, disable_existing_loggers)
82
+ finally:
83
+ logging._releaseLock()
84
+
85
+
86
+ def _resolve(name):
87
+ """Resolve a dotted name to a global object."""
88
+ name = name.split('.')
89
+ used = name.pop(0)
90
+ found = __import__(used)
91
+ for n in name:
92
+ used = used + '.' + n
93
+ try:
94
+ found = getattr(found, n)
95
+ except AttributeError:
96
+ __import__(used)
97
+ found = getattr(found, n)
98
+ return found
99
+
100
+ def _strip_spaces(alist):
101
+ return map(str.strip, alist)
102
+
103
+ def _create_formatters(cp):
104
+ """Create and return formatters"""
105
+ flist = cp["formatters"]["keys"]
106
+ if not len(flist):
107
+ return {}
108
+ flist = flist.split(",")
109
+ flist = _strip_spaces(flist)
110
+ formatters = {}
111
+ for form in flist:
112
+ sectname = "formatter_%s" % form
113
+ fs = cp.get(sectname, "format", raw=True, fallback=None)
114
+ dfs = cp.get(sectname, "datefmt", raw=True, fallback=None)
115
+ stl = cp.get(sectname, "style", raw=True, fallback='%')
116
+ c = logging.Formatter
117
+ class_name = cp[sectname].get("class")
118
+ if class_name:
119
+ c = _resolve(class_name)
120
+ f = c(fs, dfs, stl)
121
+ formatters[form] = f
122
+ return formatters
123
+
124
+
125
+ def _install_handlers(cp, formatters):
126
+ """Install and return handlers"""
127
+ hlist = cp["handlers"]["keys"]
128
+ if not len(hlist):
129
+ return {}
130
+ hlist = hlist.split(",")
131
+ hlist = _strip_spaces(hlist)
132
+ handlers = {}
133
+ fixups = [] #for inter-handler references
134
+ for hand in hlist:
135
+ section = cp["handler_%s" % hand]
136
+ klass = section["class"]
137
+ fmt = section.get("formatter", "")
138
+ try:
139
+ klass = eval(klass, vars(logging))
140
+ except (AttributeError, NameError):
141
+ klass = _resolve(klass)
142
+ args = section.get("args", '()')
143
+ args = eval(args, vars(logging))
144
+ kwargs = section.get("kwargs", '{}')
145
+ kwargs = eval(kwargs, vars(logging))
146
+ h = klass(*args, **kwargs)
147
+ h.name = hand
148
+ if "level" in section:
149
+ level = section["level"]
150
+ h.setLevel(level)
151
+ if len(fmt):
152
+ h.setFormatter(formatters[fmt])
153
+ if issubclass(klass, logging.handlers.MemoryHandler):
154
+ target = section.get("target", "")
155
+ if len(target): #the target handler may not be loaded yet, so keep for later...
156
+ fixups.append((h, target))
157
+ handlers[hand] = h
158
+ #now all handlers are loaded, fixup inter-handler references...
159
+ for h, t in fixups:
160
+ h.setTarget(handlers[t])
161
+ return handlers
162
+
163
+ def _handle_existing_loggers(existing, child_loggers, disable_existing):
164
+ """
165
+ When (re)configuring logging, handle loggers which were in the previous
166
+ configuration but are not in the new configuration. There's no point
167
+ deleting them as other threads may continue to hold references to them;
168
+ and by disabling them, you stop them doing any logging.
169
+
170
+ However, don't disable children of named loggers, as that's probably not
171
+ what was intended by the user. Also, allow existing loggers to NOT be
172
+ disabled if disable_existing is false.
173
+ """
174
+ root = logging.root
175
+ for log in existing:
176
+ logger = root.manager.loggerDict[log]
177
+ if log in child_loggers:
178
+ if not isinstance(logger, logging.PlaceHolder):
179
+ logger.setLevel(logging.NOTSET)
180
+ logger.handlers = []
181
+ logger.propagate = True
182
+ else:
183
+ logger.disabled = disable_existing
184
+
185
+ def _install_loggers(cp, handlers, disable_existing):
186
+ """Create and install loggers"""
187
+
188
+ # configure the root first
189
+ llist = cp["loggers"]["keys"]
190
+ llist = llist.split(",")
191
+ llist = list(_strip_spaces(llist))
192
+ llist.remove("root")
193
+ section = cp["logger_root"]
194
+ root = logging.root
195
+ log = root
196
+ if "level" in section:
197
+ level = section["level"]
198
+ log.setLevel(level)
199
+ for h in root.handlers[:]:
200
+ root.removeHandler(h)
201
+ hlist = section["handlers"]
202
+ if len(hlist):
203
+ hlist = hlist.split(",")
204
+ hlist = _strip_spaces(hlist)
205
+ for hand in hlist:
206
+ log.addHandler(handlers[hand])
207
+
208
+ #and now the others...
209
+ #we don't want to lose the existing loggers,
210
+ #since other threads may have pointers to them.
211
+ #existing is set to contain all existing loggers,
212
+ #and as we go through the new configuration we
213
+ #remove any which are configured. At the end,
214
+ #what's left in existing is the set of loggers
215
+ #which were in the previous configuration but
216
+ #which are not in the new configuration.
217
+ existing = list(root.manager.loggerDict.keys())
218
+ #The list needs to be sorted so that we can
219
+ #avoid disabling child loggers of explicitly
220
+ #named loggers. With a sorted list it is easier
221
+ #to find the child loggers.
222
+ existing.sort()
223
+ #We'll keep the list of existing loggers
224
+ #which are children of named loggers here...
225
+ child_loggers = []
226
+ #now set up the new ones...
227
+ for log in llist:
228
+ section = cp["logger_%s" % log]
229
+ qn = section["qualname"]
230
+ propagate = section.getint("propagate", fallback=1)
231
+ logger = logging.getLogger(qn)
232
+ if qn in existing:
233
+ i = existing.index(qn) + 1 # start with the entry after qn
234
+ prefixed = qn + "."
235
+ pflen = len(prefixed)
236
+ num_existing = len(existing)
237
+ while i < num_existing:
238
+ if existing[i][:pflen] == prefixed:
239
+ child_loggers.append(existing[i])
240
+ i += 1
241
+ existing.remove(qn)
242
+ if "level" in section:
243
+ level = section["level"]
244
+ logger.setLevel(level)
245
+ for h in logger.handlers[:]:
246
+ logger.removeHandler(h)
247
+ logger.propagate = propagate
248
+ logger.disabled = 0
249
+ hlist = section["handlers"]
250
+ if len(hlist):
251
+ hlist = hlist.split(",")
252
+ hlist = _strip_spaces(hlist)
253
+ for hand in hlist:
254
+ logger.addHandler(handlers[hand])
255
+
256
+ #Disable any old loggers. There's no point deleting
257
+ #them as other threads may continue to hold references
258
+ #and by disabling them, you stop them doing any logging.
259
+ #However, don't disable children of named loggers, as that's
260
+ #probably not what was intended by the user.
261
+ #for log in existing:
262
+ # logger = root.manager.loggerDict[log]
263
+ # if log in child_loggers:
264
+ # logger.level = logging.NOTSET
265
+ # logger.handlers = []
266
+ # logger.propagate = 1
267
+ # elif disable_existing_loggers:
268
+ # logger.disabled = 1
269
+ _handle_existing_loggers(existing, child_loggers, disable_existing)
270
+
271
+
272
+ def _clearExistingHandlers():
273
+ """Clear and close existing handlers"""
274
+ logging._handlers.clear()
275
+ logging.shutdown(logging._handlerList[:])
276
+ del logging._handlerList[:]
277
+
278
+
279
+ IDENTIFIER = re.compile('^[a-z_][a-z0-9_]*$', re.I)
280
+
281
+
282
+ def valid_ident(s):
283
+ m = IDENTIFIER.match(s)
284
+ if not m:
285
+ raise ValueError('Not a valid Python identifier: %r' % s)
286
+ return True
287
+
288
+
289
+ class ConvertingMixin(object):
290
+ """For ConvertingXXX's, this mixin class provides common functions"""
291
+
292
+ def convert_with_key(self, key, value, replace=True):
293
+ result = self.configurator.convert(value)
294
+ #If the converted value is different, save for next time
295
+ if value is not result:
296
+ if replace:
297
+ self[key] = result
298
+ if type(result) in (ConvertingDict, ConvertingList,
299
+ ConvertingTuple):
300
+ result.parent = self
301
+ result.key = key
302
+ return result
303
+
304
+ def convert(self, value):
305
+ result = self.configurator.convert(value)
306
+ if value is not result:
307
+ if type(result) in (ConvertingDict, ConvertingList,
308
+ ConvertingTuple):
309
+ result.parent = self
310
+ return result
311
+
312
+
313
+ # The ConvertingXXX classes are wrappers around standard Python containers,
314
+ # and they serve to convert any suitable values in the container. The
315
+ # conversion converts base dicts, lists and tuples to their wrapped
316
+ # equivalents, whereas strings which match a conversion format are converted
317
+ # appropriately.
318
+ #
319
+ # Each wrapper should have a configurator attribute holding the actual
320
+ # configurator to use for conversion.
321
+
322
+ class ConvertingDict(dict, ConvertingMixin):
323
+ """A converting dictionary wrapper."""
324
+
325
+ def __getitem__(self, key):
326
+ value = dict.__getitem__(self, key)
327
+ return self.convert_with_key(key, value)
328
+
329
+ def get(self, key, default=None):
330
+ value = dict.get(self, key, default)
331
+ return self.convert_with_key(key, value)
332
+
333
+ def pop(self, key, default=None):
334
+ value = dict.pop(self, key, default)
335
+ return self.convert_with_key(key, value, replace=False)
336
+
337
+ class ConvertingList(list, ConvertingMixin):
338
+ """A converting list wrapper."""
339
+ def __getitem__(self, key):
340
+ value = list.__getitem__(self, key)
341
+ return self.convert_with_key(key, value)
342
+
343
+ def pop(self, idx=-1):
344
+ value = list.pop(self, idx)
345
+ return self.convert(value)
346
+
347
+ class ConvertingTuple(tuple, ConvertingMixin):
348
+ """A converting tuple wrapper."""
349
+ def __getitem__(self, key):
350
+ value = tuple.__getitem__(self, key)
351
+ # Can't replace a tuple entry.
352
+ return self.convert_with_key(key, value, replace=False)
353
+
354
+ class BaseConfigurator(object):
355
+ """
356
+ The configurator base class which defines some useful defaults.
357
+ """
358
+
359
+ CONVERT_PATTERN = re.compile(r'^(?P<prefix>[a-z]+)://(?P<suffix>.*)$')
360
+
361
+ WORD_PATTERN = re.compile(r'^\s*(\w+)\s*')
362
+ DOT_PATTERN = re.compile(r'^\.\s*(\w+)\s*')
363
+ INDEX_PATTERN = re.compile(r'^\[\s*(\w+)\s*\]\s*')
364
+ DIGIT_PATTERN = re.compile(r'^\d+$')
365
+
366
+ value_converters = {
367
+ 'ext' : 'ext_convert',
368
+ 'cfg' : 'cfg_convert',
369
+ }
370
+
371
+ # We might want to use a different one, e.g. importlib
372
+ importer = staticmethod(__import__)
373
+
374
+ def __init__(self, config):
375
+ self.config = ConvertingDict(config)
376
+ self.config.configurator = self
377
+
378
+ def resolve(self, s):
379
+ """
380
+ Resolve strings to objects using standard import and attribute
381
+ syntax.
382
+ """
383
+ name = s.split('.')
384
+ used = name.pop(0)
385
+ try:
386
+ found = self.importer(used)
387
+ for frag in name:
388
+ used += '.' + frag
389
+ try:
390
+ found = getattr(found, frag)
391
+ except AttributeError:
392
+ self.importer(used)
393
+ found = getattr(found, frag)
394
+ return found
395
+ except ImportError:
396
+ e, tb = sys.exc_info()[1:]
397
+ v = ValueError('Cannot resolve %r: %s' % (s, e))
398
+ v.__cause__, v.__traceback__ = e, tb
399
+ raise v
400
+
401
+ def ext_convert(self, value):
402
+ """Default converter for the ext:// protocol."""
403
+ return self.resolve(value)
404
+
405
+ def cfg_convert(self, value):
406
+ """Default converter for the cfg:// protocol."""
407
+ rest = value
408
+ m = self.WORD_PATTERN.match(rest)
409
+ if m is None:
410
+ raise ValueError("Unable to convert %r" % value)
411
+ else:
412
+ rest = rest[m.end():]
413
+ d = self.config[m.groups()[0]]
414
+ #print d, rest
415
+ while rest:
416
+ m = self.DOT_PATTERN.match(rest)
417
+ if m:
418
+ d = d[m.groups()[0]]
419
+ else:
420
+ m = self.INDEX_PATTERN.match(rest)
421
+ if m:
422
+ idx = m.groups()[0]
423
+ if not self.DIGIT_PATTERN.match(idx):
424
+ d = d[idx]
425
+ else:
426
+ try:
427
+ n = int(idx) # try as number first (most likely)
428
+ d = d[n]
429
+ except TypeError:
430
+ d = d[idx]
431
+ if m:
432
+ rest = rest[m.end():]
433
+ else:
434
+ raise ValueError('Unable to convert '
435
+ '%r at %r' % (value, rest))
436
+ #rest should be empty
437
+ return d
438
+
439
+ def convert(self, value):
440
+ """
441
+ Convert values to an appropriate type. dicts, lists and tuples are
442
+ replaced by their converting alternatives. Strings are checked to
443
+ see if they have a conversion format and are converted if they do.
444
+ """
445
+ if not isinstance(value, ConvertingDict) and isinstance(value, dict):
446
+ value = ConvertingDict(value)
447
+ value.configurator = self
448
+ elif not isinstance(value, ConvertingList) and isinstance(value, list):
449
+ value = ConvertingList(value)
450
+ value.configurator = self
451
+ elif not isinstance(value, ConvertingTuple) and\
452
+ isinstance(value, tuple) and not hasattr(value, '_fields'):
453
+ value = ConvertingTuple(value)
454
+ value.configurator = self
455
+ elif isinstance(value, str): # str for py3k
456
+ m = self.CONVERT_PATTERN.match(value)
457
+ if m:
458
+ d = m.groupdict()
459
+ prefix = d['prefix']
460
+ converter = self.value_converters.get(prefix, None)
461
+ if converter:
462
+ suffix = d['suffix']
463
+ converter = getattr(self, converter)
464
+ value = converter(suffix)
465
+ return value
466
+
467
+ def configure_custom(self, config):
468
+ """Configure an object with a user-supplied factory."""
469
+ c = config.pop('()')
470
+ if not callable(c):
471
+ c = self.resolve(c)
472
+ props = config.pop('.', None)
473
+ # Check for valid identifiers
474
+ kwargs = {k: config[k] for k in config if valid_ident(k)}
475
+ result = c(**kwargs)
476
+ if props:
477
+ for name, value in props.items():
478
+ setattr(result, name, value)
479
+ return result
480
+
481
+ def as_tuple(self, value):
482
+ """Utility function which converts lists to tuples."""
483
+ if isinstance(value, list):
484
+ value = tuple(value)
485
+ return value
486
+
487
+ class DictConfigurator(BaseConfigurator):
488
+ """
489
+ Configure logging using a dictionary-like object to describe the
490
+ configuration.
491
+ """
492
+
493
+ def configure(self):
494
+ """Do the configuration."""
495
+
496
+ config = self.config
497
+ if 'version' not in config:
498
+ raise ValueError("dictionary doesn't specify a version")
499
+ if config['version'] != 1:
500
+ raise ValueError("Unsupported version: %s" % config['version'])
501
+ incremental = config.pop('incremental', False)
502
+ EMPTY_DICT = {}
503
+ logging._acquireLock()
504
+ try:
505
+ if incremental:
506
+ handlers = config.get('handlers', EMPTY_DICT)
507
+ for name in handlers:
508
+ if name not in logging._handlers:
509
+ raise ValueError('No handler found with '
510
+ 'name %r' % name)
511
+ else:
512
+ try:
513
+ handler = logging._handlers[name]
514
+ handler_config = handlers[name]
515
+ level = handler_config.get('level', None)
516
+ if level:
517
+ handler.setLevel(logging._checkLevel(level))
518
+ except Exception as e:
519
+ raise ValueError('Unable to configure handler '
520
+ '%r' % name) from e
521
+ loggers = config.get('loggers', EMPTY_DICT)
522
+ for name in loggers:
523
+ try:
524
+ self.configure_logger(name, loggers[name], True)
525
+ except Exception as e:
526
+ raise ValueError('Unable to configure logger '
527
+ '%r' % name) from e
528
+ root = config.get('root', None)
529
+ if root:
530
+ try:
531
+ self.configure_root(root, True)
532
+ except Exception as e:
533
+ raise ValueError('Unable to configure root '
534
+ 'logger') from e
535
+ else:
536
+ disable_existing = config.pop('disable_existing_loggers', True)
537
+
538
+ _clearExistingHandlers()
539
+
540
+ # Do formatters first - they don't refer to anything else
541
+ formatters = config.get('formatters', EMPTY_DICT)
542
+ for name in formatters:
543
+ try:
544
+ formatters[name] = self.configure_formatter(
545
+ formatters[name])
546
+ except Exception as e:
547
+ raise ValueError('Unable to configure '
548
+ 'formatter %r' % name) from e
549
+ # Next, do filters - they don't refer to anything else, either
550
+ filters = config.get('filters', EMPTY_DICT)
551
+ for name in filters:
552
+ try:
553
+ filters[name] = self.configure_filter(filters[name])
554
+ except Exception as e:
555
+ raise ValueError('Unable to configure '
556
+ 'filter %r' % name) from e
557
+
558
+ # Next, do handlers - they refer to formatters and filters
559
+ # As handlers can refer to other handlers, sort the keys
560
+ # to allow a deterministic order of configuration
561
+ handlers = config.get('handlers', EMPTY_DICT)
562
+ deferred = []
563
+ for name in sorted(handlers):
564
+ try:
565
+ handler = self.configure_handler(handlers[name])
566
+ handler.name = name
567
+ handlers[name] = handler
568
+ except Exception as e:
569
+ if 'target not configured yet' in str(e.__cause__):
570
+ deferred.append(name)
571
+ else:
572
+ raise ValueError('Unable to configure handler '
573
+ '%r' % name) from e
574
+
575
+ # Now do any that were deferred
576
+ for name in deferred:
577
+ try:
578
+ handler = self.configure_handler(handlers[name])
579
+ handler.name = name
580
+ handlers[name] = handler
581
+ except Exception as e:
582
+ raise ValueError('Unable to configure handler '
583
+ '%r' % name) from e
584
+
585
+ # Next, do loggers - they refer to handlers and filters
586
+
587
+ #we don't want to lose the existing loggers,
588
+ #since other threads may have pointers to them.
589
+ #existing is set to contain all existing loggers,
590
+ #and as we go through the new configuration we
591
+ #remove any which are configured. At the end,
592
+ #what's left in existing is the set of loggers
593
+ #which were in the previous configuration but
594
+ #which are not in the new configuration.
595
+ root = logging.root
596
+ existing = list(root.manager.loggerDict.keys())
597
+ #The list needs to be sorted so that we can
598
+ #avoid disabling child loggers of explicitly
599
+ #named loggers. With a sorted list it is easier
600
+ #to find the child loggers.
601
+ existing.sort()
602
+ #We'll keep the list of existing loggers
603
+ #which are children of named loggers here...
604
+ child_loggers = []
605
+ #now set up the new ones...
606
+ loggers = config.get('loggers', EMPTY_DICT)
607
+ for name in loggers:
608
+ if name in existing:
609
+ i = existing.index(name) + 1 # look after name
610
+ prefixed = name + "."
611
+ pflen = len(prefixed)
612
+ num_existing = len(existing)
613
+ while i < num_existing:
614
+ if existing[i][:pflen] == prefixed:
615
+ child_loggers.append(existing[i])
616
+ i += 1
617
+ existing.remove(name)
618
+ try:
619
+ self.configure_logger(name, loggers[name])
620
+ except Exception as e:
621
+ raise ValueError('Unable to configure logger '
622
+ '%r' % name) from e
623
+
624
+ #Disable any old loggers. There's no point deleting
625
+ #them as other threads may continue to hold references
626
+ #and by disabling them, you stop them doing any logging.
627
+ #However, don't disable children of named loggers, as that's
628
+ #probably not what was intended by the user.
629
+ #for log in existing:
630
+ # logger = root.manager.loggerDict[log]
631
+ # if log in child_loggers:
632
+ # logger.level = logging.NOTSET
633
+ # logger.handlers = []
634
+ # logger.propagate = True
635
+ # elif disable_existing:
636
+ # logger.disabled = True
637
+ _handle_existing_loggers(existing, child_loggers,
638
+ disable_existing)
639
+
640
+ # And finally, do the root logger
641
+ root = config.get('root', None)
642
+ if root:
643
+ try:
644
+ self.configure_root(root)
645
+ except Exception as e:
646
+ raise ValueError('Unable to configure root '
647
+ 'logger') from e
648
+ finally:
649
+ logging._releaseLock()
650
+
651
+ def configure_formatter(self, config):
652
+ """Configure a formatter from a dictionary."""
653
+ if '()' in config:
654
+ factory = config['()'] # for use in exception handler
655
+ try:
656
+ result = self.configure_custom(config)
657
+ except TypeError as te:
658
+ if "'format'" not in str(te):
659
+ raise
660
+ #Name of parameter changed from fmt to format.
661
+ #Retry with old name.
662
+ #This is so that code can be used with older Python versions
663
+ #(e.g. by Django)
664
+ config['fmt'] = config.pop('format')
665
+ config['()'] = factory
666
+ result = self.configure_custom(config)
667
+ else:
668
+ fmt = config.get('format', None)
669
+ dfmt = config.get('datefmt', None)
670
+ style = config.get('style', '%')
671
+ cname = config.get('class', None)
672
+
673
+ if not cname:
674
+ c = logging.Formatter
675
+ else:
676
+ c = _resolve(cname)
677
+
678
+ # A TypeError would be raised if "validate" key is passed in with a formatter callable
679
+ # that does not accept "validate" as a parameter
680
+ if 'validate' in config: # if user hasn't mentioned it, the default will be fine
681
+ result = c(fmt, dfmt, style, config['validate'])
682
+ else:
683
+ result = c(fmt, dfmt, style)
684
+
685
+ return result
686
+
687
+ def configure_filter(self, config):
688
+ """Configure a filter from a dictionary."""
689
+ if '()' in config:
690
+ result = self.configure_custom(config)
691
+ else:
692
+ name = config.get('name', '')
693
+ result = logging.Filter(name)
694
+ return result
695
+
696
+ def add_filters(self, filterer, filters):
697
+ """Add filters to a filterer from a list of names."""
698
+ for f in filters:
699
+ try:
700
+ filterer.addFilter(self.config['filters'][f])
701
+ except Exception as e:
702
+ raise ValueError('Unable to add filter %r' % f) from e
703
+
704
+ def configure_handler(self, config):
705
+ """Configure a handler from a dictionary."""
706
+ config_copy = dict(config) # for restoring in case of error
707
+ formatter = config.pop('formatter', None)
708
+ if formatter:
709
+ try:
710
+ formatter = self.config['formatters'][formatter]
711
+ except Exception as e:
712
+ raise ValueError('Unable to set formatter '
713
+ '%r' % formatter) from e
714
+ level = config.pop('level', None)
715
+ filters = config.pop('filters', None)
716
+ if '()' in config:
717
+ c = config.pop('()')
718
+ if not callable(c):
719
+ c = self.resolve(c)
720
+ factory = c
721
+ else:
722
+ cname = config.pop('class')
723
+ klass = self.resolve(cname)
724
+ #Special case for handler which refers to another handler
725
+ if issubclass(klass, logging.handlers.MemoryHandler) and\
726
+ 'target' in config:
727
+ try:
728
+ th = self.config['handlers'][config['target']]
729
+ if not isinstance(th, logging.Handler):
730
+ config.update(config_copy) # restore for deferred cfg
731
+ raise TypeError('target not configured yet')
732
+ config['target'] = th
733
+ except Exception as e:
734
+ raise ValueError('Unable to set target handler '
735
+ '%r' % config['target']) from e
736
+ elif issubclass(klass, logging.handlers.SMTPHandler) and\
737
+ 'mailhost' in config:
738
+ config['mailhost'] = self.as_tuple(config['mailhost'])
739
+ elif issubclass(klass, logging.handlers.SysLogHandler) and\
740
+ 'address' in config:
741
+ config['address'] = self.as_tuple(config['address'])
742
+ factory = klass
743
+ props = config.pop('.', None)
744
+ kwargs = {k: config[k] for k in config if valid_ident(k)}
745
+ try:
746
+ result = factory(**kwargs)
747
+ except TypeError as te:
748
+ if "'stream'" not in str(te):
749
+ raise
750
+ #The argument name changed from strm to stream
751
+ #Retry with old name.
752
+ #This is so that code can be used with older Python versions
753
+ #(e.g. by Django)
754
+ kwargs['strm'] = kwargs.pop('stream')
755
+ result = factory(**kwargs)
756
+ if formatter:
757
+ result.setFormatter(formatter)
758
+ if level is not None:
759
+ result.setLevel(logging._checkLevel(level))
760
+ if filters:
761
+ self.add_filters(result, filters)
762
+ if props:
763
+ for name, value in props.items():
764
+ setattr(result, name, value)
765
+ return result
766
+
767
+ def add_handlers(self, logger, handlers):
768
+ """Add handlers to a logger from a list of names."""
769
+ for h in handlers:
770
+ try:
771
+ logger.addHandler(self.config['handlers'][h])
772
+ except Exception as e:
773
+ raise ValueError('Unable to add handler %r' % h) from e
774
+
775
+ def common_logger_config(self, logger, config, incremental=False):
776
+ """
777
+ Perform configuration which is common to root and non-root loggers.
778
+ """
779
+ level = config.get('level', None)
780
+ if level is not None:
781
+ logger.setLevel(logging._checkLevel(level))
782
+ if not incremental:
783
+ #Remove any existing handlers
784
+ for h in logger.handlers[:]:
785
+ logger.removeHandler(h)
786
+ handlers = config.get('handlers', None)
787
+ if handlers:
788
+ self.add_handlers(logger, handlers)
789
+ filters = config.get('filters', None)
790
+ if filters:
791
+ self.add_filters(logger, filters)
792
+
793
+ def configure_logger(self, name, config, incremental=False):
794
+ """Configure a non-root logger from a dictionary."""
795
+ logger = logging.getLogger(name)
796
+ self.common_logger_config(logger, config, incremental)
797
+ logger.disabled = False
798
+ propagate = config.get('propagate', None)
799
+ if propagate is not None:
800
+ logger.propagate = propagate
801
+
802
+ def configure_root(self, config, incremental=False):
803
+ """Configure a root logger from a dictionary."""
804
+ root = logging.getLogger()
805
+ self.common_logger_config(root, config, incremental)
806
+
807
+ dictConfigClass = DictConfigurator
808
+
809
+ def dictConfig(config):
810
+ """Configure logging using a dictionary."""
811
+ dictConfigClass(config).configure()
812
+
813
+
814
+ def listen(port=DEFAULT_LOGGING_CONFIG_PORT, verify=None):
815
+ """
816
+ Start up a socket server on the specified port, and listen for new
817
+ configurations.
818
+
819
+ These will be sent as a file suitable for processing by fileConfig().
820
+ Returns a Thread object on which you can call start() to start the server,
821
+ and which you can join() when appropriate. To stop the server, call
822
+ stopListening().
823
+
824
+ Use the ``verify`` argument to verify any bytes received across the wire
825
+ from a client. If specified, it should be a callable which receives a
826
+ single argument - the bytes of configuration data received across the
827
+ network - and it should return either ``None``, to indicate that the
828
+ passed in bytes could not be verified and should be discarded, or a
829
+ byte string which is then passed to the configuration machinery as
830
+ normal. Note that you can return transformed bytes, e.g. by decrypting
831
+ the bytes passed in.
832
+ """
833
+
834
+ class ConfigStreamHandler(StreamRequestHandler):
835
+ """
836
+ Handler for a logging configuration request.
837
+
838
+ It expects a completely new logging configuration and uses fileConfig
839
+ to install it.
840
+ """
841
+ def handle(self):
842
+ """
843
+ Handle a request.
844
+
845
+ Each request is expected to be a 4-byte length, packed using
846
+ struct.pack(">L", n), followed by the config file.
847
+ Uses fileConfig() to do the grunt work.
848
+ """
849
+ try:
850
+ conn = self.connection
851
+ chunk = conn.recv(4)
852
+ if len(chunk) == 4:
853
+ slen = struct.unpack(">L", chunk)[0]
854
+ chunk = self.connection.recv(slen)
855
+ while len(chunk) < slen:
856
+ chunk = chunk + conn.recv(slen - len(chunk))
857
+ if self.server.verify is not None:
858
+ chunk = self.server.verify(chunk)
859
+ if chunk is not None: # verified, can process
860
+ chunk = chunk.decode("utf-8")
861
+ try:
862
+ import json
863
+ d =json.loads(chunk)
864
+ assert isinstance(d, dict)
865
+ dictConfig(d)
866
+ except Exception:
867
+ #Apply new configuration.
868
+
869
+ file = io.StringIO(chunk)
870
+ try:
871
+ fileConfig(file)
872
+ except Exception:
873
+ traceback.print_exc()
874
+ if self.server.ready:
875
+ self.server.ready.set()
876
+ except OSError as e:
877
+ if e.errno != RESET_ERROR:
878
+ raise
879
+
880
+ class ConfigSocketReceiver(ThreadingTCPServer):
881
+ """
882
+ A simple TCP socket-based logging config receiver.
883
+ """
884
+
885
+ allow_reuse_address = 1
886
+
887
+ def __init__(self, host='localhost', port=DEFAULT_LOGGING_CONFIG_PORT,
888
+ handler=None, ready=None, verify=None):
889
+ ThreadingTCPServer.__init__(self, (host, port), handler)
890
+ logging._acquireLock()
891
+ self.abort = 0
892
+ logging._releaseLock()
893
+ self.timeout = 1
894
+ self.ready = ready
895
+ self.verify = verify
896
+
897
+ def serve_until_stopped(self):
898
+ import select
899
+ abort = 0
900
+ while not abort:
901
+ rd, wr, ex = select.select([self.socket.fileno()],
902
+ [], [],
903
+ self.timeout)
904
+ if rd:
905
+ self.handle_request()
906
+ logging._acquireLock()
907
+ abort = self.abort
908
+ logging._releaseLock()
909
+ self.server_close()
910
+
911
+ class Server(threading.Thread):
912
+
913
+ def __init__(self, rcvr, hdlr, port, verify):
914
+ super(Server, self).__init__()
915
+ self.rcvr = rcvr
916
+ self.hdlr = hdlr
917
+ self.port = port
918
+ self.verify = verify
919
+ self.ready = threading.Event()
920
+
921
+ def run(self):
922
+ server = self.rcvr(port=self.port, handler=self.hdlr,
923
+ ready=self.ready,
924
+ verify=self.verify)
925
+ if self.port == 0:
926
+ self.port = server.server_address[1]
927
+ self.ready.set()
928
+ global _listener
929
+ logging._acquireLock()
930
+ _listener = server
931
+ logging._releaseLock()
932
+ server.serve_until_stopped()
933
+
934
+ return Server(ConfigSocketReceiver, ConfigStreamHandler, port, verify)
935
+
936
+ def stopListening():
937
+ """
938
+ Stop the listening server which was created with a call to listen().
939
+ """
940
+ global _listener
941
+ logging._acquireLock()
942
+ try:
943
+ if _listener:
944
+ _listener.abort = 1
945
+ _listener = None
946
+ finally:
947
+ logging._releaseLock()
valley/lib/python3.10/logging/handlers.py ADDED
@@ -0,0 +1,1587 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2001-2021 by Vinay Sajip. All Rights Reserved.
2
+ #
3
+ # Permission to use, copy, modify, and distribute this software and its
4
+ # documentation for any purpose and without fee is hereby granted,
5
+ # provided that the above copyright notice appear in all copies and that
6
+ # both that copyright notice and this permission notice appear in
7
+ # supporting documentation, and that the name of Vinay Sajip
8
+ # not be used in advertising or publicity pertaining to distribution
9
+ # of the software without specific, written prior permission.
10
+ # VINAY SAJIP DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
11
+ # ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
12
+ # VINAY SAJIP BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
13
+ # ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
14
+ # IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
15
+ # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16
+
17
+ """
18
+ Additional handlers for the logging package for Python. The core package is
19
+ based on PEP 282 and comments thereto in comp.lang.python.
20
+
21
+ Copyright (C) 2001-2021 Vinay Sajip. All Rights Reserved.
22
+
23
+ To use, simply 'import logging.handlers' and log away!
24
+ """
25
+
26
+ import io, logging, socket, os, pickle, struct, time, re
27
+ from stat import ST_DEV, ST_INO, ST_MTIME
28
+ import queue
29
+ import threading
30
+ import copy
31
+
32
+ #
33
+ # Some constants...
34
+ #
35
+
36
+ DEFAULT_TCP_LOGGING_PORT = 9020
37
+ DEFAULT_UDP_LOGGING_PORT = 9021
38
+ DEFAULT_HTTP_LOGGING_PORT = 9022
39
+ DEFAULT_SOAP_LOGGING_PORT = 9023
40
+ SYSLOG_UDP_PORT = 514
41
+ SYSLOG_TCP_PORT = 514
42
+
43
+ _MIDNIGHT = 24 * 60 * 60 # number of seconds in a day
44
+
45
+ class BaseRotatingHandler(logging.FileHandler):
46
+ """
47
+ Base class for handlers that rotate log files at a certain point.
48
+ Not meant to be instantiated directly. Instead, use RotatingFileHandler
49
+ or TimedRotatingFileHandler.
50
+ """
51
+ namer = None
52
+ rotator = None
53
+
54
+ def __init__(self, filename, mode, encoding=None, delay=False, errors=None):
55
+ """
56
+ Use the specified filename for streamed logging
57
+ """
58
+ logging.FileHandler.__init__(self, filename, mode=mode,
59
+ encoding=encoding, delay=delay,
60
+ errors=errors)
61
+ self.mode = mode
62
+ self.encoding = encoding
63
+ self.errors = errors
64
+
65
+ def emit(self, record):
66
+ """
67
+ Emit a record.
68
+
69
+ Output the record to the file, catering for rollover as described
70
+ in doRollover().
71
+ """
72
+ try:
73
+ if self.shouldRollover(record):
74
+ self.doRollover()
75
+ logging.FileHandler.emit(self, record)
76
+ except Exception:
77
+ self.handleError(record)
78
+
79
+ def rotation_filename(self, default_name):
80
+ """
81
+ Modify the filename of a log file when rotating.
82
+
83
+ This is provided so that a custom filename can be provided.
84
+
85
+ The default implementation calls the 'namer' attribute of the
86
+ handler, if it's callable, passing the default name to
87
+ it. If the attribute isn't callable (the default is None), the name
88
+ is returned unchanged.
89
+
90
+ :param default_name: The default name for the log file.
91
+ """
92
+ if not callable(self.namer):
93
+ result = default_name
94
+ else:
95
+ result = self.namer(default_name)
96
+ return result
97
+
98
+ def rotate(self, source, dest):
99
+ """
100
+ When rotating, rotate the current log.
101
+
102
+ The default implementation calls the 'rotator' attribute of the
103
+ handler, if it's callable, passing the source and dest arguments to
104
+ it. If the attribute isn't callable (the default is None), the source
105
+ is simply renamed to the destination.
106
+
107
+ :param source: The source filename. This is normally the base
108
+ filename, e.g. 'test.log'
109
+ :param dest: The destination filename. This is normally
110
+ what the source is rotated to, e.g. 'test.log.1'.
111
+ """
112
+ if not callable(self.rotator):
113
+ # Issue 18940: A file may not have been created if delay is True.
114
+ if os.path.exists(source):
115
+ os.rename(source, dest)
116
+ else:
117
+ self.rotator(source, dest)
118
+
119
+ class RotatingFileHandler(BaseRotatingHandler):
120
+ """
121
+ Handler for logging to a set of files, which switches from one file
122
+ to the next when the current file reaches a certain size.
123
+ """
124
+ def __init__(self, filename, mode='a', maxBytes=0, backupCount=0,
125
+ encoding=None, delay=False, errors=None):
126
+ """
127
+ Open the specified file and use it as the stream for logging.
128
+
129
+ By default, the file grows indefinitely. You can specify particular
130
+ values of maxBytes and backupCount to allow the file to rollover at
131
+ a predetermined size.
132
+
133
+ Rollover occurs whenever the current log file is nearly maxBytes in
134
+ length. If backupCount is >= 1, the system will successively create
135
+ new files with the same pathname as the base file, but with extensions
136
+ ".1", ".2" etc. appended to it. For example, with a backupCount of 5
137
+ and a base file name of "app.log", you would get "app.log",
138
+ "app.log.1", "app.log.2", ... through to "app.log.5". The file being
139
+ written to is always "app.log" - when it gets filled up, it is closed
140
+ and renamed to "app.log.1", and if files "app.log.1", "app.log.2" etc.
141
+ exist, then they are renamed to "app.log.2", "app.log.3" etc.
142
+ respectively.
143
+
144
+ If maxBytes is zero, rollover never occurs.
145
+ """
146
+ # If rotation/rollover is wanted, it doesn't make sense to use another
147
+ # mode. If for example 'w' were specified, then if there were multiple
148
+ # runs of the calling application, the logs from previous runs would be
149
+ # lost if the 'w' is respected, because the log file would be truncated
150
+ # on each run.
151
+ if maxBytes > 0:
152
+ mode = 'a'
153
+ if "b" not in mode:
154
+ encoding = io.text_encoding(encoding)
155
+ BaseRotatingHandler.__init__(self, filename, mode, encoding=encoding,
156
+ delay=delay, errors=errors)
157
+ self.maxBytes = maxBytes
158
+ self.backupCount = backupCount
159
+
160
+ def doRollover(self):
161
+ """
162
+ Do a rollover, as described in __init__().
163
+ """
164
+ if self.stream:
165
+ self.stream.close()
166
+ self.stream = None
167
+ if self.backupCount > 0:
168
+ for i in range(self.backupCount - 1, 0, -1):
169
+ sfn = self.rotation_filename("%s.%d" % (self.baseFilename, i))
170
+ dfn = self.rotation_filename("%s.%d" % (self.baseFilename,
171
+ i + 1))
172
+ if os.path.exists(sfn):
173
+ if os.path.exists(dfn):
174
+ os.remove(dfn)
175
+ os.rename(sfn, dfn)
176
+ dfn = self.rotation_filename(self.baseFilename + ".1")
177
+ if os.path.exists(dfn):
178
+ os.remove(dfn)
179
+ self.rotate(self.baseFilename, dfn)
180
+ if not self.delay:
181
+ self.stream = self._open()
182
+
183
+ def shouldRollover(self, record):
184
+ """
185
+ Determine if rollover should occur.
186
+
187
+ Basically, see if the supplied record would cause the file to exceed
188
+ the size limit we have.
189
+ """
190
+ # See bpo-45401: Never rollover anything other than regular files
191
+ if os.path.exists(self.baseFilename) and not os.path.isfile(self.baseFilename):
192
+ return False
193
+ if self.stream is None: # delay was set...
194
+ self.stream = self._open()
195
+ if self.maxBytes > 0: # are we rolling over?
196
+ msg = "%s\n" % self.format(record)
197
+ self.stream.seek(0, 2) #due to non-posix-compliant Windows feature
198
+ if self.stream.tell() + len(msg) >= self.maxBytes:
199
+ return True
200
+ return False
201
+
202
+ class TimedRotatingFileHandler(BaseRotatingHandler):
203
+ """
204
+ Handler for logging to a file, rotating the log file at certain timed
205
+ intervals.
206
+
207
+ If backupCount is > 0, when rollover is done, no more than backupCount
208
+ files are kept - the oldest ones are deleted.
209
+ """
210
+ def __init__(self, filename, when='h', interval=1, backupCount=0,
211
+ encoding=None, delay=False, utc=False, atTime=None,
212
+ errors=None):
213
+ encoding = io.text_encoding(encoding)
214
+ BaseRotatingHandler.__init__(self, filename, 'a', encoding=encoding,
215
+ delay=delay, errors=errors)
216
+ self.when = when.upper()
217
+ self.backupCount = backupCount
218
+ self.utc = utc
219
+ self.atTime = atTime
220
+ # Calculate the real rollover interval, which is just the number of
221
+ # seconds between rollovers. Also set the filename suffix used when
222
+ # a rollover occurs. Current 'when' events supported:
223
+ # S - Seconds
224
+ # M - Minutes
225
+ # H - Hours
226
+ # D - Days
227
+ # midnight - roll over at midnight
228
+ # W{0-6} - roll over on a certain day; 0 - Monday
229
+ #
230
+ # Case of the 'when' specifier is not important; lower or upper case
231
+ # will work.
232
+ if self.when == 'S':
233
+ self.interval = 1 # one second
234
+ self.suffix = "%Y-%m-%d_%H-%M-%S"
235
+ self.extMatch = r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}(\.\w+)?$"
236
+ elif self.when == 'M':
237
+ self.interval = 60 # one minute
238
+ self.suffix = "%Y-%m-%d_%H-%M"
239
+ self.extMatch = r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}(\.\w+)?$"
240
+ elif self.when == 'H':
241
+ self.interval = 60 * 60 # one hour
242
+ self.suffix = "%Y-%m-%d_%H"
243
+ self.extMatch = r"^\d{4}-\d{2}-\d{2}_\d{2}(\.\w+)?$"
244
+ elif self.when == 'D' or self.when == 'MIDNIGHT':
245
+ self.interval = 60 * 60 * 24 # one day
246
+ self.suffix = "%Y-%m-%d"
247
+ self.extMatch = r"^\d{4}-\d{2}-\d{2}(\.\w+)?$"
248
+ elif self.when.startswith('W'):
249
+ self.interval = 60 * 60 * 24 * 7 # one week
250
+ if len(self.when) != 2:
251
+ raise ValueError("You must specify a day for weekly rollover from 0 to 6 (0 is Monday): %s" % self.when)
252
+ if self.when[1] < '0' or self.when[1] > '6':
253
+ raise ValueError("Invalid day specified for weekly rollover: %s" % self.when)
254
+ self.dayOfWeek = int(self.when[1])
255
+ self.suffix = "%Y-%m-%d"
256
+ self.extMatch = r"^\d{4}-\d{2}-\d{2}(\.\w+)?$"
257
+ else:
258
+ raise ValueError("Invalid rollover interval specified: %s" % self.when)
259
+
260
+ self.extMatch = re.compile(self.extMatch, re.ASCII)
261
+ self.interval = self.interval * interval # multiply by units requested
262
+ # The following line added because the filename passed in could be a
263
+ # path object (see Issue #27493), but self.baseFilename will be a string
264
+ filename = self.baseFilename
265
+ if os.path.exists(filename):
266
+ t = os.stat(filename)[ST_MTIME]
267
+ else:
268
+ t = int(time.time())
269
+ self.rolloverAt = self.computeRollover(t)
270
+
271
+ def computeRollover(self, currentTime):
272
+ """
273
+ Work out the rollover time based on the specified time.
274
+ """
275
+ result = currentTime + self.interval
276
+ # If we are rolling over at midnight or weekly, then the interval is already known.
277
+ # What we need to figure out is WHEN the next interval is. In other words,
278
+ # if you are rolling over at midnight, then your base interval is 1 day,
279
+ # but you want to start that one day clock at midnight, not now. So, we
280
+ # have to fudge the rolloverAt value in order to trigger the first rollover
281
+ # at the right time. After that, the regular interval will take care of
282
+ # the rest. Note that this code doesn't care about leap seconds. :)
283
+ if self.when == 'MIDNIGHT' or self.when.startswith('W'):
284
+ # This could be done with less code, but I wanted it to be clear
285
+ if self.utc:
286
+ t = time.gmtime(currentTime)
287
+ else:
288
+ t = time.localtime(currentTime)
289
+ currentHour = t[3]
290
+ currentMinute = t[4]
291
+ currentSecond = t[5]
292
+ currentDay = t[6]
293
+ # r is the number of seconds left between now and the next rotation
294
+ if self.atTime is None:
295
+ rotate_ts = _MIDNIGHT
296
+ else:
297
+ rotate_ts = ((self.atTime.hour * 60 + self.atTime.minute)*60 +
298
+ self.atTime.second)
299
+
300
+ r = rotate_ts - ((currentHour * 60 + currentMinute) * 60 +
301
+ currentSecond)
302
+ if r < 0:
303
+ # Rotate time is before the current time (for example when
304
+ # self.rotateAt is 13:45 and it now 14:15), rotation is
305
+ # tomorrow.
306
+ r += _MIDNIGHT
307
+ currentDay = (currentDay + 1) % 7
308
+ result = currentTime + r
309
+ # If we are rolling over on a certain day, add in the number of days until
310
+ # the next rollover, but offset by 1 since we just calculated the time
311
+ # until the next day starts. There are three cases:
312
+ # Case 1) The day to rollover is today; in this case, do nothing
313
+ # Case 2) The day to rollover is further in the interval (i.e., today is
314
+ # day 2 (Wednesday) and rollover is on day 6 (Sunday). Days to
315
+ # next rollover is simply 6 - 2 - 1, or 3.
316
+ # Case 3) The day to rollover is behind us in the interval (i.e., today
317
+ # is day 5 (Saturday) and rollover is on day 3 (Thursday).
318
+ # Days to rollover is 6 - 5 + 3, or 4. In this case, it's the
319
+ # number of days left in the current week (1) plus the number
320
+ # of days in the next week until the rollover day (3).
321
+ # The calculations described in 2) and 3) above need to have a day added.
322
+ # This is because the above time calculation takes us to midnight on this
323
+ # day, i.e. the start of the next day.
324
+ if self.when.startswith('W'):
325
+ day = currentDay # 0 is Monday
326
+ if day != self.dayOfWeek:
327
+ if day < self.dayOfWeek:
328
+ daysToWait = self.dayOfWeek - day
329
+ else:
330
+ daysToWait = 6 - day + self.dayOfWeek + 1
331
+ newRolloverAt = result + (daysToWait * (60 * 60 * 24))
332
+ if not self.utc:
333
+ dstNow = t[-1]
334
+ dstAtRollover = time.localtime(newRolloverAt)[-1]
335
+ if dstNow != dstAtRollover:
336
+ if not dstNow: # DST kicks in before next rollover, so we need to deduct an hour
337
+ addend = -3600
338
+ else: # DST bows out before next rollover, so we need to add an hour
339
+ addend = 3600
340
+ newRolloverAt += addend
341
+ result = newRolloverAt
342
+ return result
343
+
344
+ def shouldRollover(self, record):
345
+ """
346
+ Determine if rollover should occur.
347
+
348
+ record is not used, as we are just comparing times, but it is needed so
349
+ the method signatures are the same
350
+ """
351
+ t = int(time.time())
352
+ if t >= self.rolloverAt:
353
+ # See #89564: Never rollover anything other than regular files
354
+ if os.path.exists(self.baseFilename) and not os.path.isfile(self.baseFilename):
355
+ # The file is not a regular file, so do not rollover, but do
356
+ # set the next rollover time to avoid repeated checks.
357
+ self.rolloverAt = self.computeRollover(t)
358
+ return False
359
+
360
+ return True
361
+ return False
362
+
363
+ def getFilesToDelete(self):
364
+ """
365
+ Determine the files to delete when rolling over.
366
+
367
+ More specific than the earlier method, which just used glob.glob().
368
+ """
369
+ dirName, baseName = os.path.split(self.baseFilename)
370
+ fileNames = os.listdir(dirName)
371
+ result = []
372
+ # See bpo-44753: Don't use the extension when computing the prefix.
373
+ n, e = os.path.splitext(baseName)
374
+ prefix = n + '.'
375
+ plen = len(prefix)
376
+ for fileName in fileNames:
377
+ if self.namer is None:
378
+ # Our files will always start with baseName
379
+ if not fileName.startswith(baseName):
380
+ continue
381
+ else:
382
+ # Our files could be just about anything after custom naming, but
383
+ # likely candidates are of the form
384
+ # foo.log.DATETIME_SUFFIX or foo.DATETIME_SUFFIX.log
385
+ if (not fileName.startswith(baseName) and fileName.endswith(e) and
386
+ len(fileName) > (plen + 1) and not fileName[plen+1].isdigit()):
387
+ continue
388
+
389
+ if fileName[:plen] == prefix:
390
+ suffix = fileName[plen:]
391
+ # See bpo-45628: The date/time suffix could be anywhere in the
392
+ # filename
393
+ parts = suffix.split('.')
394
+ for part in parts:
395
+ if self.extMatch.match(part):
396
+ result.append(os.path.join(dirName, fileName))
397
+ break
398
+ if len(result) < self.backupCount:
399
+ result = []
400
+ else:
401
+ result.sort()
402
+ result = result[:len(result) - self.backupCount]
403
+ return result
404
+
405
+ def doRollover(self):
406
+ """
407
+ do a rollover; in this case, a date/time stamp is appended to the filename
408
+ when the rollover happens. However, you want the file to be named for the
409
+ start of the interval, not the current time. If there is a backup count,
410
+ then we have to get a list of matching filenames, sort them and remove
411
+ the one with the oldest suffix.
412
+ """
413
+ if self.stream:
414
+ self.stream.close()
415
+ self.stream = None
416
+ # get the time that this sequence started at and make it a TimeTuple
417
+ currentTime = int(time.time())
418
+ dstNow = time.localtime(currentTime)[-1]
419
+ t = self.rolloverAt - self.interval
420
+ if self.utc:
421
+ timeTuple = time.gmtime(t)
422
+ else:
423
+ timeTuple = time.localtime(t)
424
+ dstThen = timeTuple[-1]
425
+ if dstNow != dstThen:
426
+ if dstNow:
427
+ addend = 3600
428
+ else:
429
+ addend = -3600
430
+ timeTuple = time.localtime(t + addend)
431
+ dfn = self.rotation_filename(self.baseFilename + "." +
432
+ time.strftime(self.suffix, timeTuple))
433
+ if os.path.exists(dfn):
434
+ os.remove(dfn)
435
+ self.rotate(self.baseFilename, dfn)
436
+ if self.backupCount > 0:
437
+ for s in self.getFilesToDelete():
438
+ os.remove(s)
439
+ if not self.delay:
440
+ self.stream = self._open()
441
+ newRolloverAt = self.computeRollover(currentTime)
442
+ while newRolloverAt <= currentTime:
443
+ newRolloverAt = newRolloverAt + self.interval
444
+ #If DST changes and midnight or weekly rollover, adjust for this.
445
+ if (self.when == 'MIDNIGHT' or self.when.startswith('W')) and not self.utc:
446
+ dstAtRollover = time.localtime(newRolloverAt)[-1]
447
+ if dstNow != dstAtRollover:
448
+ if not dstNow: # DST kicks in before next rollover, so we need to deduct an hour
449
+ addend = -3600
450
+ else: # DST bows out before next rollover, so we need to add an hour
451
+ addend = 3600
452
+ newRolloverAt += addend
453
+ self.rolloverAt = newRolloverAt
454
+
455
+ class WatchedFileHandler(logging.FileHandler):
456
+ """
457
+ A handler for logging to a file, which watches the file
458
+ to see if it has changed while in use. This can happen because of
459
+ usage of programs such as newsyslog and logrotate which perform
460
+ log file rotation. This handler, intended for use under Unix,
461
+ watches the file to see if it has changed since the last emit.
462
+ (A file has changed if its device or inode have changed.)
463
+ If it has changed, the old file stream is closed, and the file
464
+ opened to get a new stream.
465
+
466
+ This handler is not appropriate for use under Windows, because
467
+ under Windows open files cannot be moved or renamed - logging
468
+ opens the files with exclusive locks - and so there is no need
469
+ for such a handler. Furthermore, ST_INO is not supported under
470
+ Windows; stat always returns zero for this value.
471
+
472
+ This handler is based on a suggestion and patch by Chad J.
473
+ Schroeder.
474
+ """
475
+ def __init__(self, filename, mode='a', encoding=None, delay=False,
476
+ errors=None):
477
+ if "b" not in mode:
478
+ encoding = io.text_encoding(encoding)
479
+ logging.FileHandler.__init__(self, filename, mode=mode,
480
+ encoding=encoding, delay=delay,
481
+ errors=errors)
482
+ self.dev, self.ino = -1, -1
483
+ self._statstream()
484
+
485
+ def _statstream(self):
486
+ if self.stream:
487
+ sres = os.fstat(self.stream.fileno())
488
+ self.dev, self.ino = sres[ST_DEV], sres[ST_INO]
489
+
490
+ def reopenIfNeeded(self):
491
+ """
492
+ Reopen log file if needed.
493
+
494
+ Checks if the underlying file has changed, and if it
495
+ has, close the old stream and reopen the file to get the
496
+ current stream.
497
+ """
498
+ # Reduce the chance of race conditions by stat'ing by path only
499
+ # once and then fstat'ing our new fd if we opened a new log stream.
500
+ # See issue #14632: Thanks to John Mulligan for the problem report
501
+ # and patch.
502
+ try:
503
+ # stat the file by path, checking for existence
504
+ sres = os.stat(self.baseFilename)
505
+ except FileNotFoundError:
506
+ sres = None
507
+ # compare file system stat with that of our stream file handle
508
+ if not sres or sres[ST_DEV] != self.dev or sres[ST_INO] != self.ino:
509
+ if self.stream is not None:
510
+ # we have an open file handle, clean it up
511
+ self.stream.flush()
512
+ self.stream.close()
513
+ self.stream = None # See Issue #21742: _open () might fail.
514
+ # open a new file handle and get new stat info from that fd
515
+ self.stream = self._open()
516
+ self._statstream()
517
+
518
+ def emit(self, record):
519
+ """
520
+ Emit a record.
521
+
522
+ If underlying file has changed, reopen the file before emitting the
523
+ record to it.
524
+ """
525
+ self.reopenIfNeeded()
526
+ logging.FileHandler.emit(self, record)
527
+
528
+
529
+ class SocketHandler(logging.Handler):
530
+ """
531
+ A handler class which writes logging records, in pickle format, to
532
+ a streaming socket. The socket is kept open across logging calls.
533
+ If the peer resets it, an attempt is made to reconnect on the next call.
534
+ The pickle which is sent is that of the LogRecord's attribute dictionary
535
+ (__dict__), so that the receiver does not need to have the logging module
536
+ installed in order to process the logging event.
537
+
538
+ To unpickle the record at the receiving end into a LogRecord, use the
539
+ makeLogRecord function.
540
+ """
541
+
542
+ def __init__(self, host, port):
543
+ """
544
+ Initializes the handler with a specific host address and port.
545
+
546
+ When the attribute *closeOnError* is set to True - if a socket error
547
+ occurs, the socket is silently closed and then reopened on the next
548
+ logging call.
549
+ """
550
+ logging.Handler.__init__(self)
551
+ self.host = host
552
+ self.port = port
553
+ if port is None:
554
+ self.address = host
555
+ else:
556
+ self.address = (host, port)
557
+ self.sock = None
558
+ self.closeOnError = False
559
+ self.retryTime = None
560
+ #
561
+ # Exponential backoff parameters.
562
+ #
563
+ self.retryStart = 1.0
564
+ self.retryMax = 30.0
565
+ self.retryFactor = 2.0
566
+
567
+ def makeSocket(self, timeout=1):
568
+ """
569
+ A factory method which allows subclasses to define the precise
570
+ type of socket they want.
571
+ """
572
+ if self.port is not None:
573
+ result = socket.create_connection(self.address, timeout=timeout)
574
+ else:
575
+ result = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
576
+ result.settimeout(timeout)
577
+ try:
578
+ result.connect(self.address)
579
+ except OSError:
580
+ result.close() # Issue 19182
581
+ raise
582
+ return result
583
+
584
+ def createSocket(self):
585
+ """
586
+ Try to create a socket, using an exponential backoff with
587
+ a max retry time. Thanks to Robert Olson for the original patch
588
+ (SF #815911) which has been slightly refactored.
589
+ """
590
+ now = time.time()
591
+ # Either retryTime is None, in which case this
592
+ # is the first time back after a disconnect, or
593
+ # we've waited long enough.
594
+ if self.retryTime is None:
595
+ attempt = True
596
+ else:
597
+ attempt = (now >= self.retryTime)
598
+ if attempt:
599
+ try:
600
+ self.sock = self.makeSocket()
601
+ self.retryTime = None # next time, no delay before trying
602
+ except OSError:
603
+ #Creation failed, so set the retry time and return.
604
+ if self.retryTime is None:
605
+ self.retryPeriod = self.retryStart
606
+ else:
607
+ self.retryPeriod = self.retryPeriod * self.retryFactor
608
+ if self.retryPeriod > self.retryMax:
609
+ self.retryPeriod = self.retryMax
610
+ self.retryTime = now + self.retryPeriod
611
+
612
+ def send(self, s):
613
+ """
614
+ Send a pickled string to the socket.
615
+
616
+ This function allows for partial sends which can happen when the
617
+ network is busy.
618
+ """
619
+ if self.sock is None:
620
+ self.createSocket()
621
+ #self.sock can be None either because we haven't reached the retry
622
+ #time yet, or because we have reached the retry time and retried,
623
+ #but are still unable to connect.
624
+ if self.sock:
625
+ try:
626
+ self.sock.sendall(s)
627
+ except OSError: #pragma: no cover
628
+ self.sock.close()
629
+ self.sock = None # so we can call createSocket next time
630
+
631
+ def makePickle(self, record):
632
+ """
633
+ Pickles the record in binary format with a length prefix, and
634
+ returns it ready for transmission across the socket.
635
+ """
636
+ ei = record.exc_info
637
+ if ei:
638
+ # just to get traceback text into record.exc_text ...
639
+ dummy = self.format(record)
640
+ # See issue #14436: If msg or args are objects, they may not be
641
+ # available on the receiving end. So we convert the msg % args
642
+ # to a string, save it as msg and zap the args.
643
+ d = dict(record.__dict__)
644
+ d['msg'] = record.getMessage()
645
+ d['args'] = None
646
+ d['exc_info'] = None
647
+ # Issue #25685: delete 'message' if present: redundant with 'msg'
648
+ d.pop('message', None)
649
+ s = pickle.dumps(d, 1)
650
+ slen = struct.pack(">L", len(s))
651
+ return slen + s
652
+
653
+ def handleError(self, record):
654
+ """
655
+ Handle an error during logging.
656
+
657
+ An error has occurred during logging. Most likely cause -
658
+ connection lost. Close the socket so that we can retry on the
659
+ next event.
660
+ """
661
+ if self.closeOnError and self.sock:
662
+ self.sock.close()
663
+ self.sock = None #try to reconnect next time
664
+ else:
665
+ logging.Handler.handleError(self, record)
666
+
667
+ def emit(self, record):
668
+ """
669
+ Emit a record.
670
+
671
+ Pickles the record and writes it to the socket in binary format.
672
+ If there is an error with the socket, silently drop the packet.
673
+ If there was a problem with the socket, re-establishes the
674
+ socket.
675
+ """
676
+ try:
677
+ s = self.makePickle(record)
678
+ self.send(s)
679
+ except Exception:
680
+ self.handleError(record)
681
+
682
+ def close(self):
683
+ """
684
+ Closes the socket.
685
+ """
686
+ self.acquire()
687
+ try:
688
+ sock = self.sock
689
+ if sock:
690
+ self.sock = None
691
+ sock.close()
692
+ logging.Handler.close(self)
693
+ finally:
694
+ self.release()
695
+
696
+ class DatagramHandler(SocketHandler):
697
+ """
698
+ A handler class which writes logging records, in pickle format, to
699
+ a datagram socket. The pickle which is sent is that of the LogRecord's
700
+ attribute dictionary (__dict__), so that the receiver does not need to
701
+ have the logging module installed in order to process the logging event.
702
+
703
+ To unpickle the record at the receiving end into a LogRecord, use the
704
+ makeLogRecord function.
705
+
706
+ """
707
+ def __init__(self, host, port):
708
+ """
709
+ Initializes the handler with a specific host address and port.
710
+ """
711
+ SocketHandler.__init__(self, host, port)
712
+ self.closeOnError = False
713
+
714
+ def makeSocket(self):
715
+ """
716
+ The factory method of SocketHandler is here overridden to create
717
+ a UDP socket (SOCK_DGRAM).
718
+ """
719
+ if self.port is None:
720
+ family = socket.AF_UNIX
721
+ else:
722
+ family = socket.AF_INET
723
+ s = socket.socket(family, socket.SOCK_DGRAM)
724
+ return s
725
+
726
+ def send(self, s):
727
+ """
728
+ Send a pickled string to a socket.
729
+
730
+ This function no longer allows for partial sends which can happen
731
+ when the network is busy - UDP does not guarantee delivery and
732
+ can deliver packets out of sequence.
733
+ """
734
+ if self.sock is None:
735
+ self.createSocket()
736
+ self.sock.sendto(s, self.address)
737
+
738
+ class SysLogHandler(logging.Handler):
739
+ """
740
+ A handler class which sends formatted logging records to a syslog
741
+ server. Based on Sam Rushing's syslog module:
742
+ http://www.nightmare.com/squirl/python-ext/misc/syslog.py
743
+ Contributed by Nicolas Untz (after which minor refactoring changes
744
+ have been made).
745
+ """
746
+
747
+ # from <linux/sys/syslog.h>:
748
+ # ======================================================================
749
+ # priorities/facilities are encoded into a single 32-bit quantity, where
750
+ # the bottom 3 bits are the priority (0-7) and the top 28 bits are the
751
+ # facility (0-big number). Both the priorities and the facilities map
752
+ # roughly one-to-one to strings in the syslogd(8) source code. This
753
+ # mapping is included in this file.
754
+ #
755
+ # priorities (these are ordered)
756
+
757
+ LOG_EMERG = 0 # system is unusable
758
+ LOG_ALERT = 1 # action must be taken immediately
759
+ LOG_CRIT = 2 # critical conditions
760
+ LOG_ERR = 3 # error conditions
761
+ LOG_WARNING = 4 # warning conditions
762
+ LOG_NOTICE = 5 # normal but significant condition
763
+ LOG_INFO = 6 # informational
764
+ LOG_DEBUG = 7 # debug-level messages
765
+
766
+ # facility codes
767
+ LOG_KERN = 0 # kernel messages
768
+ LOG_USER = 1 # random user-level messages
769
+ LOG_MAIL = 2 # mail system
770
+ LOG_DAEMON = 3 # system daemons
771
+ LOG_AUTH = 4 # security/authorization messages
772
+ LOG_SYSLOG = 5 # messages generated internally by syslogd
773
+ LOG_LPR = 6 # line printer subsystem
774
+ LOG_NEWS = 7 # network news subsystem
775
+ LOG_UUCP = 8 # UUCP subsystem
776
+ LOG_CRON = 9 # clock daemon
777
+ LOG_AUTHPRIV = 10 # security/authorization messages (private)
778
+ LOG_FTP = 11 # FTP daemon
779
+ LOG_NTP = 12 # NTP subsystem
780
+ LOG_SECURITY = 13 # Log audit
781
+ LOG_CONSOLE = 14 # Log alert
782
+ LOG_SOLCRON = 15 # Scheduling daemon (Solaris)
783
+
784
+ # other codes through 15 reserved for system use
785
+ LOG_LOCAL0 = 16 # reserved for local use
786
+ LOG_LOCAL1 = 17 # reserved for local use
787
+ LOG_LOCAL2 = 18 # reserved for local use
788
+ LOG_LOCAL3 = 19 # reserved for local use
789
+ LOG_LOCAL4 = 20 # reserved for local use
790
+ LOG_LOCAL5 = 21 # reserved for local use
791
+ LOG_LOCAL6 = 22 # reserved for local use
792
+ LOG_LOCAL7 = 23 # reserved for local use
793
+
794
+ priority_names = {
795
+ "alert": LOG_ALERT,
796
+ "crit": LOG_CRIT,
797
+ "critical": LOG_CRIT,
798
+ "debug": LOG_DEBUG,
799
+ "emerg": LOG_EMERG,
800
+ "err": LOG_ERR,
801
+ "error": LOG_ERR, # DEPRECATED
802
+ "info": LOG_INFO,
803
+ "notice": LOG_NOTICE,
804
+ "panic": LOG_EMERG, # DEPRECATED
805
+ "warn": LOG_WARNING, # DEPRECATED
806
+ "warning": LOG_WARNING,
807
+ }
808
+
809
+ facility_names = {
810
+ "auth": LOG_AUTH,
811
+ "authpriv": LOG_AUTHPRIV,
812
+ "console": LOG_CONSOLE,
813
+ "cron": LOG_CRON,
814
+ "daemon": LOG_DAEMON,
815
+ "ftp": LOG_FTP,
816
+ "kern": LOG_KERN,
817
+ "lpr": LOG_LPR,
818
+ "mail": LOG_MAIL,
819
+ "news": LOG_NEWS,
820
+ "ntp": LOG_NTP,
821
+ "security": LOG_SECURITY,
822
+ "solaris-cron": LOG_SOLCRON,
823
+ "syslog": LOG_SYSLOG,
824
+ "user": LOG_USER,
825
+ "uucp": LOG_UUCP,
826
+ "local0": LOG_LOCAL0,
827
+ "local1": LOG_LOCAL1,
828
+ "local2": LOG_LOCAL2,
829
+ "local3": LOG_LOCAL3,
830
+ "local4": LOG_LOCAL4,
831
+ "local5": LOG_LOCAL5,
832
+ "local6": LOG_LOCAL6,
833
+ "local7": LOG_LOCAL7,
834
+ }
835
+
836
+ #The map below appears to be trivially lowercasing the key. However,
837
+ #there's more to it than meets the eye - in some locales, lowercasing
838
+ #gives unexpected results. See SF #1524081: in the Turkish locale,
839
+ #"INFO".lower() != "info"
840
+ priority_map = {
841
+ "DEBUG" : "debug",
842
+ "INFO" : "info",
843
+ "WARNING" : "warning",
844
+ "ERROR" : "error",
845
+ "CRITICAL" : "critical"
846
+ }
847
+
848
+ def __init__(self, address=('localhost', SYSLOG_UDP_PORT),
849
+ facility=LOG_USER, socktype=None):
850
+ """
851
+ Initialize a handler.
852
+
853
+ If address is specified as a string, a UNIX socket is used. To log to a
854
+ local syslogd, "SysLogHandler(address="/dev/log")" can be used.
855
+ If facility is not specified, LOG_USER is used. If socktype is
856
+ specified as socket.SOCK_DGRAM or socket.SOCK_STREAM, that specific
857
+ socket type will be used. For Unix sockets, you can also specify a
858
+ socktype of None, in which case socket.SOCK_DGRAM will be used, falling
859
+ back to socket.SOCK_STREAM.
860
+ """
861
+ logging.Handler.__init__(self)
862
+
863
+ self.address = address
864
+ self.facility = facility
865
+ self.socktype = socktype
866
+
867
+ if isinstance(address, str):
868
+ self.unixsocket = True
869
+ # Syslog server may be unavailable during handler initialisation.
870
+ # C's openlog() function also ignores connection errors.
871
+ # Moreover, we ignore these errors while logging, so it not worse
872
+ # to ignore it also here.
873
+ try:
874
+ self._connect_unixsocket(address)
875
+ except OSError:
876
+ pass
877
+ else:
878
+ self.unixsocket = False
879
+ if socktype is None:
880
+ socktype = socket.SOCK_DGRAM
881
+ host, port = address
882
+ ress = socket.getaddrinfo(host, port, 0, socktype)
883
+ if not ress:
884
+ raise OSError("getaddrinfo returns an empty list")
885
+ for res in ress:
886
+ af, socktype, proto, _, sa = res
887
+ err = sock = None
888
+ try:
889
+ sock = socket.socket(af, socktype, proto)
890
+ if socktype == socket.SOCK_STREAM:
891
+ sock.connect(sa)
892
+ break
893
+ except OSError as exc:
894
+ err = exc
895
+ if sock is not None:
896
+ sock.close()
897
+ if err is not None:
898
+ raise err
899
+ self.socket = sock
900
+ self.socktype = socktype
901
+
902
+ def _connect_unixsocket(self, address):
903
+ use_socktype = self.socktype
904
+ if use_socktype is None:
905
+ use_socktype = socket.SOCK_DGRAM
906
+ self.socket = socket.socket(socket.AF_UNIX, use_socktype)
907
+ try:
908
+ self.socket.connect(address)
909
+ # it worked, so set self.socktype to the used type
910
+ self.socktype = use_socktype
911
+ except OSError:
912
+ self.socket.close()
913
+ if self.socktype is not None:
914
+ # user didn't specify falling back, so fail
915
+ raise
916
+ use_socktype = socket.SOCK_STREAM
917
+ self.socket = socket.socket(socket.AF_UNIX, use_socktype)
918
+ try:
919
+ self.socket.connect(address)
920
+ # it worked, so set self.socktype to the used type
921
+ self.socktype = use_socktype
922
+ except OSError:
923
+ self.socket.close()
924
+ raise
925
+
926
+ def encodePriority(self, facility, priority):
927
+ """
928
+ Encode the facility and priority. You can pass in strings or
929
+ integers - if strings are passed, the facility_names and
930
+ priority_names mapping dictionaries are used to convert them to
931
+ integers.
932
+ """
933
+ if isinstance(facility, str):
934
+ facility = self.facility_names[facility]
935
+ if isinstance(priority, str):
936
+ priority = self.priority_names[priority]
937
+ return (facility << 3) | priority
938
+
939
+ def close(self):
940
+ """
941
+ Closes the socket.
942
+ """
943
+ self.acquire()
944
+ try:
945
+ self.socket.close()
946
+ logging.Handler.close(self)
947
+ finally:
948
+ self.release()
949
+
950
+ def mapPriority(self, levelName):
951
+ """
952
+ Map a logging level name to a key in the priority_names map.
953
+ This is useful in two scenarios: when custom levels are being
954
+ used, and in the case where you can't do a straightforward
955
+ mapping by lowercasing the logging level name because of locale-
956
+ specific issues (see SF #1524081).
957
+ """
958
+ return self.priority_map.get(levelName, "warning")
959
+
960
+ ident = '' # prepended to all messages
961
+ append_nul = True # some old syslog daemons expect a NUL terminator
962
+
963
+ def emit(self, record):
964
+ """
965
+ Emit a record.
966
+
967
+ The record is formatted, and then sent to the syslog server. If
968
+ exception information is present, it is NOT sent to the server.
969
+ """
970
+ try:
971
+ msg = self.format(record)
972
+ if self.ident:
973
+ msg = self.ident + msg
974
+ if self.append_nul:
975
+ msg += '\000'
976
+
977
+ # We need to convert record level to lowercase, maybe this will
978
+ # change in the future.
979
+ prio = '<%d>' % self.encodePriority(self.facility,
980
+ self.mapPriority(record.levelname))
981
+ prio = prio.encode('utf-8')
982
+ # Message is a string. Convert to bytes as required by RFC 5424
983
+ msg = msg.encode('utf-8')
984
+ msg = prio + msg
985
+ if self.unixsocket:
986
+ try:
987
+ self.socket.send(msg)
988
+ except OSError:
989
+ self.socket.close()
990
+ self._connect_unixsocket(self.address)
991
+ self.socket.send(msg)
992
+ elif self.socktype == socket.SOCK_DGRAM:
993
+ self.socket.sendto(msg, self.address)
994
+ else:
995
+ self.socket.sendall(msg)
996
+ except Exception:
997
+ self.handleError(record)
998
+
999
+ class SMTPHandler(logging.Handler):
1000
+ """
1001
+ A handler class which sends an SMTP email for each logging event.
1002
+ """
1003
+ def __init__(self, mailhost, fromaddr, toaddrs, subject,
1004
+ credentials=None, secure=None, timeout=5.0):
1005
+ """
1006
+ Initialize the handler.
1007
+
1008
+ Initialize the instance with the from and to addresses and subject
1009
+ line of the email. To specify a non-standard SMTP port, use the
1010
+ (host, port) tuple format for the mailhost argument. To specify
1011
+ authentication credentials, supply a (username, password) tuple
1012
+ for the credentials argument. To specify the use of a secure
1013
+ protocol (TLS), pass in a tuple for the secure argument. This will
1014
+ only be used when authentication credentials are supplied. The tuple
1015
+ will be either an empty tuple, or a single-value tuple with the name
1016
+ of a keyfile, or a 2-value tuple with the names of the keyfile and
1017
+ certificate file. (This tuple is passed to the `starttls` method).
1018
+ A timeout in seconds can be specified for the SMTP connection (the
1019
+ default is one second).
1020
+ """
1021
+ logging.Handler.__init__(self)
1022
+ if isinstance(mailhost, (list, tuple)):
1023
+ self.mailhost, self.mailport = mailhost
1024
+ else:
1025
+ self.mailhost, self.mailport = mailhost, None
1026
+ if isinstance(credentials, (list, tuple)):
1027
+ self.username, self.password = credentials
1028
+ else:
1029
+ self.username = None
1030
+ self.fromaddr = fromaddr
1031
+ if isinstance(toaddrs, str):
1032
+ toaddrs = [toaddrs]
1033
+ self.toaddrs = toaddrs
1034
+ self.subject = subject
1035
+ self.secure = secure
1036
+ self.timeout = timeout
1037
+
1038
+ def getSubject(self, record):
1039
+ """
1040
+ Determine the subject for the email.
1041
+
1042
+ If you want to specify a subject line which is record-dependent,
1043
+ override this method.
1044
+ """
1045
+ return self.subject
1046
+
1047
+ def emit(self, record):
1048
+ """
1049
+ Emit a record.
1050
+
1051
+ Format the record and send it to the specified addressees.
1052
+ """
1053
+ try:
1054
+ import smtplib
1055
+ from email.message import EmailMessage
1056
+ import email.utils
1057
+
1058
+ port = self.mailport
1059
+ if not port:
1060
+ port = smtplib.SMTP_PORT
1061
+ smtp = smtplib.SMTP(self.mailhost, port, timeout=self.timeout)
1062
+ msg = EmailMessage()
1063
+ msg['From'] = self.fromaddr
1064
+ msg['To'] = ','.join(self.toaddrs)
1065
+ msg['Subject'] = self.getSubject(record)
1066
+ msg['Date'] = email.utils.localtime()
1067
+ msg.set_content(self.format(record))
1068
+ if self.username:
1069
+ if self.secure is not None:
1070
+ smtp.ehlo()
1071
+ smtp.starttls(*self.secure)
1072
+ smtp.ehlo()
1073
+ smtp.login(self.username, self.password)
1074
+ smtp.send_message(msg)
1075
+ smtp.quit()
1076
+ except Exception:
1077
+ self.handleError(record)
1078
+
1079
+ class NTEventLogHandler(logging.Handler):
1080
+ """
1081
+ A handler class which sends events to the NT Event Log. Adds a
1082
+ registry entry for the specified application name. If no dllname is
1083
+ provided, win32service.pyd (which contains some basic message
1084
+ placeholders) is used. Note that use of these placeholders will make
1085
+ your event logs big, as the entire message source is held in the log.
1086
+ If you want slimmer logs, you have to pass in the name of your own DLL
1087
+ which contains the message definitions you want to use in the event log.
1088
+ """
1089
+ def __init__(self, appname, dllname=None, logtype="Application"):
1090
+ logging.Handler.__init__(self)
1091
+ try:
1092
+ import win32evtlogutil, win32evtlog
1093
+ self.appname = appname
1094
+ self._welu = win32evtlogutil
1095
+ if not dllname:
1096
+ dllname = os.path.split(self._welu.__file__)
1097
+ dllname = os.path.split(dllname[0])
1098
+ dllname = os.path.join(dllname[0], r'win32service.pyd')
1099
+ self.dllname = dllname
1100
+ self.logtype = logtype
1101
+ # Administrative privileges are required to add a source to the registry.
1102
+ # This may not be available for a user that just wants to add to an
1103
+ # existing source - handle this specific case.
1104
+ try:
1105
+ self._welu.AddSourceToRegistry(appname, dllname, logtype)
1106
+ except Exception as e:
1107
+ # This will probably be a pywintypes.error. Only raise if it's not
1108
+ # an "access denied" error, else let it pass
1109
+ if getattr(e, 'winerror', None) != 5: # not access denied
1110
+ raise
1111
+ self.deftype = win32evtlog.EVENTLOG_ERROR_TYPE
1112
+ self.typemap = {
1113
+ logging.DEBUG : win32evtlog.EVENTLOG_INFORMATION_TYPE,
1114
+ logging.INFO : win32evtlog.EVENTLOG_INFORMATION_TYPE,
1115
+ logging.WARNING : win32evtlog.EVENTLOG_WARNING_TYPE,
1116
+ logging.ERROR : win32evtlog.EVENTLOG_ERROR_TYPE,
1117
+ logging.CRITICAL: win32evtlog.EVENTLOG_ERROR_TYPE,
1118
+ }
1119
+ except ImportError:
1120
+ print("The Python Win32 extensions for NT (service, event "\
1121
+ "logging) appear not to be available.")
1122
+ self._welu = None
1123
+
1124
+ def getMessageID(self, record):
1125
+ """
1126
+ Return the message ID for the event record. If you are using your
1127
+ own messages, you could do this by having the msg passed to the
1128
+ logger being an ID rather than a formatting string. Then, in here,
1129
+ you could use a dictionary lookup to get the message ID. This
1130
+ version returns 1, which is the base message ID in win32service.pyd.
1131
+ """
1132
+ return 1
1133
+
1134
+ def getEventCategory(self, record):
1135
+ """
1136
+ Return the event category for the record.
1137
+
1138
+ Override this if you want to specify your own categories. This version
1139
+ returns 0.
1140
+ """
1141
+ return 0
1142
+
1143
+ def getEventType(self, record):
1144
+ """
1145
+ Return the event type for the record.
1146
+
1147
+ Override this if you want to specify your own types. This version does
1148
+ a mapping using the handler's typemap attribute, which is set up in
1149
+ __init__() to a dictionary which contains mappings for DEBUG, INFO,
1150
+ WARNING, ERROR and CRITICAL. If you are using your own levels you will
1151
+ either need to override this method or place a suitable dictionary in
1152
+ the handler's typemap attribute.
1153
+ """
1154
+ return self.typemap.get(record.levelno, self.deftype)
1155
+
1156
+ def emit(self, record):
1157
+ """
1158
+ Emit a record.
1159
+
1160
+ Determine the message ID, event category and event type. Then
1161
+ log the message in the NT event log.
1162
+ """
1163
+ if self._welu:
1164
+ try:
1165
+ id = self.getMessageID(record)
1166
+ cat = self.getEventCategory(record)
1167
+ type = self.getEventType(record)
1168
+ msg = self.format(record)
1169
+ self._welu.ReportEvent(self.appname, id, cat, type, [msg])
1170
+ except Exception:
1171
+ self.handleError(record)
1172
+
1173
+ def close(self):
1174
+ """
1175
+ Clean up this handler.
1176
+
1177
+ You can remove the application name from the registry as a
1178
+ source of event log entries. However, if you do this, you will
1179
+ not be able to see the events as you intended in the Event Log
1180
+ Viewer - it needs to be able to access the registry to get the
1181
+ DLL name.
1182
+ """
1183
+ #self._welu.RemoveSourceFromRegistry(self.appname, self.logtype)
1184
+ logging.Handler.close(self)
1185
+
1186
+ class HTTPHandler(logging.Handler):
1187
+ """
1188
+ A class which sends records to a web server, using either GET or
1189
+ POST semantics.
1190
+ """
1191
+ def __init__(self, host, url, method="GET", secure=False, credentials=None,
1192
+ context=None):
1193
+ """
1194
+ Initialize the instance with the host, the request URL, and the method
1195
+ ("GET" or "POST")
1196
+ """
1197
+ logging.Handler.__init__(self)
1198
+ method = method.upper()
1199
+ if method not in ["GET", "POST"]:
1200
+ raise ValueError("method must be GET or POST")
1201
+ if not secure and context is not None:
1202
+ raise ValueError("context parameter only makes sense "
1203
+ "with secure=True")
1204
+ self.host = host
1205
+ self.url = url
1206
+ self.method = method
1207
+ self.secure = secure
1208
+ self.credentials = credentials
1209
+ self.context = context
1210
+
1211
+ def mapLogRecord(self, record):
1212
+ """
1213
+ Default implementation of mapping the log record into a dict
1214
+ that is sent as the CGI data. Overwrite in your class.
1215
+ Contributed by Franz Glasner.
1216
+ """
1217
+ return record.__dict__
1218
+
1219
+ def getConnection(self, host, secure):
1220
+ """
1221
+ get a HTTP[S]Connection.
1222
+
1223
+ Override when a custom connection is required, for example if
1224
+ there is a proxy.
1225
+ """
1226
+ import http.client
1227
+ if secure:
1228
+ connection = http.client.HTTPSConnection(host, context=self.context)
1229
+ else:
1230
+ connection = http.client.HTTPConnection(host)
1231
+ return connection
1232
+
1233
+ def emit(self, record):
1234
+ """
1235
+ Emit a record.
1236
+
1237
+ Send the record to the web server as a percent-encoded dictionary
1238
+ """
1239
+ try:
1240
+ import urllib.parse
1241
+ host = self.host
1242
+ h = self.getConnection(host, self.secure)
1243
+ url = self.url
1244
+ data = urllib.parse.urlencode(self.mapLogRecord(record))
1245
+ if self.method == "GET":
1246
+ if (url.find('?') >= 0):
1247
+ sep = '&'
1248
+ else:
1249
+ sep = '?'
1250
+ url = url + "%c%s" % (sep, data)
1251
+ h.putrequest(self.method, url)
1252
+ # support multiple hosts on one IP address...
1253
+ # need to strip optional :port from host, if present
1254
+ i = host.find(":")
1255
+ if i >= 0:
1256
+ host = host[:i]
1257
+ # See issue #30904: putrequest call above already adds this header
1258
+ # on Python 3.x.
1259
+ # h.putheader("Host", host)
1260
+ if self.method == "POST":
1261
+ h.putheader("Content-type",
1262
+ "application/x-www-form-urlencoded")
1263
+ h.putheader("Content-length", str(len(data)))
1264
+ if self.credentials:
1265
+ import base64
1266
+ s = ('%s:%s' % self.credentials).encode('utf-8')
1267
+ s = 'Basic ' + base64.b64encode(s).strip().decode('ascii')
1268
+ h.putheader('Authorization', s)
1269
+ h.endheaders()
1270
+ if self.method == "POST":
1271
+ h.send(data.encode('utf-8'))
1272
+ h.getresponse() #can't do anything with the result
1273
+ except Exception:
1274
+ self.handleError(record)
1275
+
1276
+ class BufferingHandler(logging.Handler):
1277
+ """
1278
+ A handler class which buffers logging records in memory. Whenever each
1279
+ record is added to the buffer, a check is made to see if the buffer should
1280
+ be flushed. If it should, then flush() is expected to do what's needed.
1281
+ """
1282
+ def __init__(self, capacity):
1283
+ """
1284
+ Initialize the handler with the buffer size.
1285
+ """
1286
+ logging.Handler.__init__(self)
1287
+ self.capacity = capacity
1288
+ self.buffer = []
1289
+
1290
+ def shouldFlush(self, record):
1291
+ """
1292
+ Should the handler flush its buffer?
1293
+
1294
+ Returns true if the buffer is up to capacity. This method can be
1295
+ overridden to implement custom flushing strategies.
1296
+ """
1297
+ return (len(self.buffer) >= self.capacity)
1298
+
1299
+ def emit(self, record):
1300
+ """
1301
+ Emit a record.
1302
+
1303
+ Append the record. If shouldFlush() tells us to, call flush() to process
1304
+ the buffer.
1305
+ """
1306
+ self.buffer.append(record)
1307
+ if self.shouldFlush(record):
1308
+ self.flush()
1309
+
1310
+ def flush(self):
1311
+ """
1312
+ Override to implement custom flushing behaviour.
1313
+
1314
+ This version just zaps the buffer to empty.
1315
+ """
1316
+ self.acquire()
1317
+ try:
1318
+ self.buffer.clear()
1319
+ finally:
1320
+ self.release()
1321
+
1322
+ def close(self):
1323
+ """
1324
+ Close the handler.
1325
+
1326
+ This version just flushes and chains to the parent class' close().
1327
+ """
1328
+ try:
1329
+ self.flush()
1330
+ finally:
1331
+ logging.Handler.close(self)
1332
+
1333
+ class MemoryHandler(BufferingHandler):
1334
+ """
1335
+ A handler class which buffers logging records in memory, periodically
1336
+ flushing them to a target handler. Flushing occurs whenever the buffer
1337
+ is full, or when an event of a certain severity or greater is seen.
1338
+ """
1339
+ def __init__(self, capacity, flushLevel=logging.ERROR, target=None,
1340
+ flushOnClose=True):
1341
+ """
1342
+ Initialize the handler with the buffer size, the level at which
1343
+ flushing should occur and an optional target.
1344
+
1345
+ Note that without a target being set either here or via setTarget(),
1346
+ a MemoryHandler is no use to anyone!
1347
+
1348
+ The ``flushOnClose`` argument is ``True`` for backward compatibility
1349
+ reasons - the old behaviour is that when the handler is closed, the
1350
+ buffer is flushed, even if the flush level hasn't been exceeded nor the
1351
+ capacity exceeded. To prevent this, set ``flushOnClose`` to ``False``.
1352
+ """
1353
+ BufferingHandler.__init__(self, capacity)
1354
+ self.flushLevel = flushLevel
1355
+ self.target = target
1356
+ # See Issue #26559 for why this has been added
1357
+ self.flushOnClose = flushOnClose
1358
+
1359
+ def shouldFlush(self, record):
1360
+ """
1361
+ Check for buffer full or a record at the flushLevel or higher.
1362
+ """
1363
+ return (len(self.buffer) >= self.capacity) or \
1364
+ (record.levelno >= self.flushLevel)
1365
+
1366
+ def setTarget(self, target):
1367
+ """
1368
+ Set the target handler for this handler.
1369
+ """
1370
+ self.acquire()
1371
+ try:
1372
+ self.target = target
1373
+ finally:
1374
+ self.release()
1375
+
1376
+ def flush(self):
1377
+ """
1378
+ For a MemoryHandler, flushing means just sending the buffered
1379
+ records to the target, if there is one. Override if you want
1380
+ different behaviour.
1381
+
1382
+ The record buffer is also cleared by this operation.
1383
+ """
1384
+ self.acquire()
1385
+ try:
1386
+ if self.target:
1387
+ for record in self.buffer:
1388
+ self.target.handle(record)
1389
+ self.buffer.clear()
1390
+ finally:
1391
+ self.release()
1392
+
1393
+ def close(self):
1394
+ """
1395
+ Flush, if appropriately configured, set the target to None and lose the
1396
+ buffer.
1397
+ """
1398
+ try:
1399
+ if self.flushOnClose:
1400
+ self.flush()
1401
+ finally:
1402
+ self.acquire()
1403
+ try:
1404
+ self.target = None
1405
+ BufferingHandler.close(self)
1406
+ finally:
1407
+ self.release()
1408
+
1409
+
1410
+ class QueueHandler(logging.Handler):
1411
+ """
1412
+ This handler sends events to a queue. Typically, it would be used together
1413
+ with a multiprocessing Queue to centralise logging to file in one process
1414
+ (in a multi-process application), so as to avoid file write contention
1415
+ between processes.
1416
+
1417
+ This code is new in Python 3.2, but this class can be copy pasted into
1418
+ user code for use with earlier Python versions.
1419
+ """
1420
+
1421
+ def __init__(self, queue):
1422
+ """
1423
+ Initialise an instance, using the passed queue.
1424
+ """
1425
+ logging.Handler.__init__(self)
1426
+ self.queue = queue
1427
+
1428
+ def enqueue(self, record):
1429
+ """
1430
+ Enqueue a record.
1431
+
1432
+ The base implementation uses put_nowait. You may want to override
1433
+ this method if you want to use blocking, timeouts or custom queue
1434
+ implementations.
1435
+ """
1436
+ self.queue.put_nowait(record)
1437
+
1438
+ def prepare(self, record):
1439
+ """
1440
+ Prepares a record for queuing. The object returned by this method is
1441
+ enqueued.
1442
+
1443
+ The base implementation formats the record to merge the message
1444
+ and arguments, and removes unpickleable items from the record
1445
+ in-place.
1446
+
1447
+ You might want to override this method if you want to convert
1448
+ the record to a dict or JSON string, or send a modified copy
1449
+ of the record while leaving the original intact.
1450
+ """
1451
+ # The format operation gets traceback text into record.exc_text
1452
+ # (if there's exception data), and also returns the formatted
1453
+ # message. We can then use this to replace the original
1454
+ # msg + args, as these might be unpickleable. We also zap the
1455
+ # exc_info, exc_text and stack_info attributes, as they are no longer
1456
+ # needed and, if not None, will typically not be pickleable.
1457
+ msg = self.format(record)
1458
+ # bpo-35726: make copy of record to avoid affecting other handlers in the chain.
1459
+ record = copy.copy(record)
1460
+ record.message = msg
1461
+ record.msg = msg
1462
+ record.args = None
1463
+ record.exc_info = None
1464
+ record.exc_text = None
1465
+ record.stack_info = None
1466
+ return record
1467
+
1468
+ def emit(self, record):
1469
+ """
1470
+ Emit a record.
1471
+
1472
+ Writes the LogRecord to the queue, preparing it for pickling first.
1473
+ """
1474
+ try:
1475
+ self.enqueue(self.prepare(record))
1476
+ except Exception:
1477
+ self.handleError(record)
1478
+
1479
+
1480
+ class QueueListener(object):
1481
+ """
1482
+ This class implements an internal threaded listener which watches for
1483
+ LogRecords being added to a queue, removes them and passes them to a
1484
+ list of handlers for processing.
1485
+ """
1486
+ _sentinel = None
1487
+
1488
+ def __init__(self, queue, *handlers, respect_handler_level=False):
1489
+ """
1490
+ Initialise an instance with the specified queue and
1491
+ handlers.
1492
+ """
1493
+ self.queue = queue
1494
+ self.handlers = handlers
1495
+ self._thread = None
1496
+ self.respect_handler_level = respect_handler_level
1497
+
1498
+ def dequeue(self, block):
1499
+ """
1500
+ Dequeue a record and return it, optionally blocking.
1501
+
1502
+ The base implementation uses get. You may want to override this method
1503
+ if you want to use timeouts or work with custom queue implementations.
1504
+ """
1505
+ return self.queue.get(block)
1506
+
1507
+ def start(self):
1508
+ """
1509
+ Start the listener.
1510
+
1511
+ This starts up a background thread to monitor the queue for
1512
+ LogRecords to process.
1513
+ """
1514
+ self._thread = t = threading.Thread(target=self._monitor)
1515
+ t.daemon = True
1516
+ t.start()
1517
+
1518
+ def prepare(self, record):
1519
+ """
1520
+ Prepare a record for handling.
1521
+
1522
+ This method just returns the passed-in record. You may want to
1523
+ override this method if you need to do any custom marshalling or
1524
+ manipulation of the record before passing it to the handlers.
1525
+ """
1526
+ return record
1527
+
1528
+ def handle(self, record):
1529
+ """
1530
+ Handle a record.
1531
+
1532
+ This just loops through the handlers offering them the record
1533
+ to handle.
1534
+ """
1535
+ record = self.prepare(record)
1536
+ for handler in self.handlers:
1537
+ if not self.respect_handler_level:
1538
+ process = True
1539
+ else:
1540
+ process = record.levelno >= handler.level
1541
+ if process:
1542
+ handler.handle(record)
1543
+
1544
+ def _monitor(self):
1545
+ """
1546
+ Monitor the queue for records, and ask the handler
1547
+ to deal with them.
1548
+
1549
+ This method runs on a separate, internal thread.
1550
+ The thread will terminate if it sees a sentinel object in the queue.
1551
+ """
1552
+ q = self.queue
1553
+ has_task_done = hasattr(q, 'task_done')
1554
+ while True:
1555
+ try:
1556
+ record = self.dequeue(True)
1557
+ if record is self._sentinel:
1558
+ if has_task_done:
1559
+ q.task_done()
1560
+ break
1561
+ self.handle(record)
1562
+ if has_task_done:
1563
+ q.task_done()
1564
+ except queue.Empty:
1565
+ break
1566
+
1567
+ def enqueue_sentinel(self):
1568
+ """
1569
+ This is used to enqueue the sentinel record.
1570
+
1571
+ The base implementation uses put_nowait. You may want to override this
1572
+ method if you want to use timeouts or work with custom queue
1573
+ implementations.
1574
+ """
1575
+ self.queue.put_nowait(self._sentinel)
1576
+
1577
+ def stop(self):
1578
+ """
1579
+ Stop the listener.
1580
+
1581
+ This asks the thread to terminate, and then waits for it to do so.
1582
+ Note that if you don't call this before your application exits, there
1583
+ may be some records still left on the queue, which won't be processed.
1584
+ """
1585
+ self.enqueue_sentinel()
1586
+ self._thread.join()
1587
+ self._thread = None
valley/lib/python3.10/turtledemo/__init__.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ --------------------------------------
3
+ About this viewer
4
+ --------------------------------------
5
+
6
+ Tiny demo viewer to view turtle graphics example scripts.
7
+
8
+ Quickly and dirtyly assembled by Gregor Lingl.
9
+ June, 2006
10
+
11
+ For more information see: turtledemo - Help
12
+
13
+ Have fun!
14
+ """
valley/lib/python3.10/turtledemo/__main__.py ADDED
@@ -0,0 +1,398 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+
3
+ """
4
+ ----------------------------------------------
5
+ turtleDemo - Help
6
+ ----------------------------------------------
7
+
8
+ This document has two sections:
9
+
10
+ (1) How to use the demo viewer
11
+ (2) How to add your own demos to the demo repository
12
+
13
+
14
+ (1) How to use the demo viewer.
15
+
16
+ Select a demoscript from the example menu.
17
+ The (syntax colored) source code appears in the left
18
+ source code window. IT CANNOT BE EDITED, but ONLY VIEWED!
19
+
20
+ The demo viewer windows can be resized. The divider between text
21
+ and canvas can be moved by grabbing it with the mouse. The text font
22
+ size can be changed from the menu and with Control/Command '-'/'+'.
23
+ It can also be changed on most systems with Control-mousewheel
24
+ when the mouse is over the text.
25
+
26
+ Press START button to start the demo.
27
+ Stop execution by pressing the STOP button.
28
+ Clear screen by pressing the CLEAR button.
29
+ Restart by pressing the START button again.
30
+
31
+ SPECIAL demos, such as clock.py are those which run EVENTDRIVEN.
32
+
33
+ Press START button to start the demo.
34
+
35
+ - Until the EVENTLOOP is entered everything works
36
+ as in an ordinary demo script.
37
+
38
+ - When the EVENTLOOP is entered, you control the
39
+ application by using the mouse and/or keys (or it's
40
+ controlled by some timer events)
41
+ To stop it you can and must press the STOP button.
42
+
43
+ While the EVENTLOOP is running, the examples menu is disabled.
44
+
45
+ - Only after having pressed the STOP button, you may
46
+ restart it or choose another example script.
47
+
48
+ * * * * * * * *
49
+ In some rare situations there may occur interferences/conflicts
50
+ between events concerning the demo script and those concerning the
51
+ demo-viewer. (They run in the same process.) Strange behaviour may be
52
+ the consequence and in the worst case you must close and restart the
53
+ viewer.
54
+ * * * * * * * *
55
+
56
+
57
+ (2) How to add your own demos to the demo repository
58
+
59
+ - Place the file in the same directory as turtledemo/__main__.py
60
+ IMPORTANT! When imported, the demo should not modify the system
61
+ by calling functions in other modules, such as sys, tkinter, or
62
+ turtle. Global variables should be initialized in main().
63
+
64
+ - The code must contain a main() function which will
65
+ be executed by the viewer (see provided example scripts).
66
+ It may return a string which will be displayed in the Label below
67
+ the source code window (when execution has finished.)
68
+
69
+ - In order to run mydemo.py by itself, such as during development,
70
+ add the following at the end of the file:
71
+
72
+ if __name__ == '__main__':
73
+ main()
74
+ mainloop() # keep window open
75
+
76
+ python -m turtledemo.mydemo # will then run it
77
+
78
+ - If the demo is EVENT DRIVEN, main must return the string
79
+ "EVENTLOOP". This informs the demo viewer that the script is
80
+ still running and must be stopped by the user!
81
+
82
+ If an "EVENTLOOP" demo runs by itself, as with clock, which uses
83
+ ontimer, or minimal_hanoi, which loops by recursion, then the
84
+ code should catch the turtle.Terminator exception that will be
85
+ raised when the user presses the STOP button. (Paint is not such
86
+ a demo; it only acts in response to mouse clicks and movements.)
87
+ """
88
+ import sys
89
+ import os
90
+
91
+ from tkinter import *
92
+ from idlelib.colorizer import ColorDelegator, color_config
93
+ from idlelib.percolator import Percolator
94
+ from idlelib.textview import view_text
95
+ from turtledemo import __doc__ as about_turtledemo
96
+
97
+ import turtle
98
+
99
+ demo_dir = os.path.dirname(os.path.abspath(__file__))
100
+ darwin = sys.platform == 'darwin'
101
+
102
+ STARTUP = 1
103
+ READY = 2
104
+ RUNNING = 3
105
+ DONE = 4
106
+ EVENTDRIVEN = 5
107
+
108
+ menufont = ("Arial", 12, NORMAL)
109
+ btnfont = ("Arial", 12, 'bold')
110
+ txtfont = ['Lucida Console', 10, 'normal']
111
+
112
+ MINIMUM_FONT_SIZE = 6
113
+ MAXIMUM_FONT_SIZE = 100
114
+ font_sizes = [8, 9, 10, 11, 12, 14, 18, 20, 22, 24, 30]
115
+
116
+ def getExampleEntries():
117
+ return [entry[:-3] for entry in os.listdir(demo_dir) if
118
+ entry.endswith(".py") and entry[0] != '_']
119
+
120
+ help_entries = ( # (help_label, help_doc)
121
+ ('Turtledemo help', __doc__),
122
+ ('About turtledemo', about_turtledemo),
123
+ ('About turtle module', turtle.__doc__),
124
+ )
125
+
126
+
127
+ class DemoWindow(object):
128
+
129
+ def __init__(self, filename=None):
130
+ self.root = root = turtle._root = Tk()
131
+ root.title('Python turtle-graphics examples')
132
+ root.wm_protocol("WM_DELETE_WINDOW", self._destroy)
133
+
134
+ if darwin:
135
+ import subprocess
136
+ # Make sure we are the currently activated OS X application
137
+ # so that our menu bar appears.
138
+ subprocess.run(
139
+ [
140
+ 'osascript',
141
+ '-e', 'tell application "System Events"',
142
+ '-e', 'set frontmost of the first process whose '
143
+ 'unix id is {} to true'.format(os.getpid()),
144
+ '-e', 'end tell',
145
+ ],
146
+ stderr=subprocess.DEVNULL,
147
+ stdout=subprocess.DEVNULL,)
148
+
149
+ root.grid_rowconfigure(0, weight=1)
150
+ root.grid_columnconfigure(0, weight=1)
151
+ root.grid_columnconfigure(1, minsize=90, weight=1)
152
+ root.grid_columnconfigure(2, minsize=90, weight=1)
153
+ root.grid_columnconfigure(3, minsize=90, weight=1)
154
+
155
+ self.mBar = Menu(root, relief=RAISED, borderwidth=2)
156
+ self.mBar.add_cascade(menu=self.makeLoadDemoMenu(self.mBar),
157
+ label='Examples', underline=0)
158
+ self.mBar.add_cascade(menu=self.makeFontMenu(self.mBar),
159
+ label='Fontsize', underline=0)
160
+ self.mBar.add_cascade(menu=self.makeHelpMenu(self.mBar),
161
+ label='Help', underline=0)
162
+ root['menu'] = self.mBar
163
+
164
+ pane = PanedWindow(orient=HORIZONTAL, sashwidth=5,
165
+ sashrelief=SOLID, bg='#ddd')
166
+ pane.add(self.makeTextFrame(pane))
167
+ pane.add(self.makeGraphFrame(pane))
168
+ pane.grid(row=0, columnspan=4, sticky='news')
169
+
170
+ self.output_lbl = Label(root, height= 1, text=" --- ", bg="#ddf",
171
+ font=("Arial", 16, 'normal'), borderwidth=2,
172
+ relief=RIDGE)
173
+ if darwin: # Leave Mac button colors alone - #44254.
174
+ self.start_btn = Button(root, text=" START ", font=btnfont,
175
+ fg='#00cc22', command=self.startDemo)
176
+ self.stop_btn = Button(root, text=" STOP ", font=btnfont,
177
+ fg='#00cc22', command=self.stopIt)
178
+ self.clear_btn = Button(root, text=" CLEAR ", font=btnfont,
179
+ fg='#00cc22', command = self.clearCanvas)
180
+ else:
181
+ self.start_btn = Button(root, text=" START ", font=btnfont,
182
+ fg="white", disabledforeground = "#fed",
183
+ command=self.startDemo)
184
+ self.stop_btn = Button(root, text=" STOP ", font=btnfont,
185
+ fg="white", disabledforeground = "#fed",
186
+ command=self.stopIt)
187
+ self.clear_btn = Button(root, text=" CLEAR ", font=btnfont,
188
+ fg="white", disabledforeground="#fed",
189
+ command = self.clearCanvas)
190
+ self.output_lbl.grid(row=1, column=0, sticky='news', padx=(0,5))
191
+ self.start_btn.grid(row=1, column=1, sticky='ew')
192
+ self.stop_btn.grid(row=1, column=2, sticky='ew')
193
+ self.clear_btn.grid(row=1, column=3, sticky='ew')
194
+
195
+ Percolator(self.text).insertfilter(ColorDelegator())
196
+ self.dirty = False
197
+ self.exitflag = False
198
+ if filename:
199
+ self.loadfile(filename)
200
+ self.configGUI(DISABLED, DISABLED, DISABLED,
201
+ "Choose example from menu", "black")
202
+ self.state = STARTUP
203
+
204
+
205
+ def onResize(self, event):
206
+ cwidth = self._canvas.winfo_width()
207
+ cheight = self._canvas.winfo_height()
208
+ self._canvas.xview_moveto(0.5*(self.canvwidth-cwidth)/self.canvwidth)
209
+ self._canvas.yview_moveto(0.5*(self.canvheight-cheight)/self.canvheight)
210
+
211
+ def makeTextFrame(self, root):
212
+ self.text_frame = text_frame = Frame(root)
213
+ self.text = text = Text(text_frame, name='text', padx=5,
214
+ wrap='none', width=45)
215
+ color_config(text)
216
+
217
+ self.vbar = vbar = Scrollbar(text_frame, name='vbar')
218
+ vbar['command'] = text.yview
219
+ vbar.pack(side=LEFT, fill=Y)
220
+ self.hbar = hbar = Scrollbar(text_frame, name='hbar', orient=HORIZONTAL)
221
+ hbar['command'] = text.xview
222
+ hbar.pack(side=BOTTOM, fill=X)
223
+ text['yscrollcommand'] = vbar.set
224
+ text['xscrollcommand'] = hbar.set
225
+
226
+ text['font'] = tuple(txtfont)
227
+ shortcut = 'Command' if darwin else 'Control'
228
+ text.bind_all('<%s-minus>' % shortcut, self.decrease_size)
229
+ text.bind_all('<%s-underscore>' % shortcut, self.decrease_size)
230
+ text.bind_all('<%s-equal>' % shortcut, self.increase_size)
231
+ text.bind_all('<%s-plus>' % shortcut, self.increase_size)
232
+ text.bind('<Control-MouseWheel>', self.update_mousewheel)
233
+ text.bind('<Control-Button-4>', self.increase_size)
234
+ text.bind('<Control-Button-5>', self.decrease_size)
235
+
236
+ text.pack(side=LEFT, fill=BOTH, expand=1)
237
+ return text_frame
238
+
239
+ def makeGraphFrame(self, root):
240
+ turtle._Screen._root = root
241
+ self.canvwidth = 1000
242
+ self.canvheight = 800
243
+ turtle._Screen._canvas = self._canvas = canvas = turtle.ScrolledCanvas(
244
+ root, 800, 600, self.canvwidth, self.canvheight)
245
+ canvas.adjustScrolls()
246
+ canvas._rootwindow.bind('<Configure>', self.onResize)
247
+ canvas._canvas['borderwidth'] = 0
248
+
249
+ self.screen = _s_ = turtle.Screen()
250
+ turtle.TurtleScreen.__init__(_s_, _s_._canvas)
251
+ self.scanvas = _s_._canvas
252
+ turtle.RawTurtle.screens = [_s_]
253
+ return canvas
254
+
255
+ def set_txtsize(self, size):
256
+ txtfont[1] = size
257
+ self.text['font'] = tuple(txtfont)
258
+ self.output_lbl['text'] = 'Font size %d' % size
259
+
260
+ def decrease_size(self, dummy=None):
261
+ self.set_txtsize(max(txtfont[1] - 1, MINIMUM_FONT_SIZE))
262
+ return 'break'
263
+
264
+ def increase_size(self, dummy=None):
265
+ self.set_txtsize(min(txtfont[1] + 1, MAXIMUM_FONT_SIZE))
266
+ return 'break'
267
+
268
+ def update_mousewheel(self, event):
269
+ # For wheel up, event.delta = 120 on Windows, -1 on darwin.
270
+ # X-11 sends Control-Button-4 event instead.
271
+ if (event.delta < 0) == (not darwin):
272
+ return self.decrease_size()
273
+ else:
274
+ return self.increase_size()
275
+
276
+ def configGUI(self, start, stop, clear, txt="", color="blue"):
277
+ if darwin: # Leave Mac button colors alone - #44254.
278
+ self.start_btn.config(state=start)
279
+ self.stop_btn.config(state=stop)
280
+ self.clear_btn.config(state=clear)
281
+ else:
282
+ self.start_btn.config(state=start,
283
+ bg="#d00" if start == NORMAL else "#fca")
284
+ self.stop_btn.config(state=stop,
285
+ bg="#d00" if stop == NORMAL else "#fca")
286
+ self.clear_btn.config(state=clear,
287
+ bg="#d00" if clear == NORMAL else "#fca")
288
+ self.output_lbl.config(text=txt, fg=color)
289
+
290
+ def makeLoadDemoMenu(self, master):
291
+ menu = Menu(master)
292
+
293
+ for entry in getExampleEntries():
294
+ def load(entry=entry):
295
+ self.loadfile(entry)
296
+ menu.add_command(label=entry, underline=0,
297
+ font=menufont, command=load)
298
+ return menu
299
+
300
+ def makeFontMenu(self, master):
301
+ menu = Menu(master)
302
+ menu.add_command(label="Decrease (C-'-')", command=self.decrease_size,
303
+ font=menufont)
304
+ menu.add_command(label="Increase (C-'+')", command=self.increase_size,
305
+ font=menufont)
306
+ menu.add_separator()
307
+
308
+ for size in font_sizes:
309
+ def resize(size=size):
310
+ self.set_txtsize(size)
311
+ menu.add_command(label=str(size), underline=0,
312
+ font=menufont, command=resize)
313
+ return menu
314
+
315
+ def makeHelpMenu(self, master):
316
+ menu = Menu(master)
317
+
318
+ for help_label, help_file in help_entries:
319
+ def show(help_label=help_label, help_file=help_file):
320
+ view_text(self.root, help_label, help_file)
321
+ menu.add_command(label=help_label, font=menufont, command=show)
322
+ return menu
323
+
324
+ def refreshCanvas(self):
325
+ if self.dirty:
326
+ self.screen.clear()
327
+ self.dirty=False
328
+
329
+ def loadfile(self, filename):
330
+ self.clearCanvas()
331
+ turtle.TurtleScreen._RUNNING = False
332
+ modname = 'turtledemo.' + filename
333
+ __import__(modname)
334
+ self.module = sys.modules[modname]
335
+ with open(self.module.__file__, 'r') as f:
336
+ chars = f.read()
337
+ self.text.delete("1.0", "end")
338
+ self.text.insert("1.0", chars)
339
+ self.root.title(filename + " - a Python turtle graphics example")
340
+ self.configGUI(NORMAL, DISABLED, DISABLED,
341
+ "Press start button", "red")
342
+ self.state = READY
343
+
344
+ def startDemo(self):
345
+ self.refreshCanvas()
346
+ self.dirty = True
347
+ turtle.TurtleScreen._RUNNING = True
348
+ self.configGUI(DISABLED, NORMAL, DISABLED,
349
+ "demo running...", "black")
350
+ self.screen.clear()
351
+ self.screen.mode("standard")
352
+ self.state = RUNNING
353
+
354
+ try:
355
+ result = self.module.main()
356
+ if result == "EVENTLOOP":
357
+ self.state = EVENTDRIVEN
358
+ else:
359
+ self.state = DONE
360
+ except turtle.Terminator:
361
+ if self.root is None:
362
+ return
363
+ self.state = DONE
364
+ result = "stopped!"
365
+ if self.state == DONE:
366
+ self.configGUI(NORMAL, DISABLED, NORMAL,
367
+ result)
368
+ elif self.state == EVENTDRIVEN:
369
+ self.exitflag = True
370
+ self.configGUI(DISABLED, NORMAL, DISABLED,
371
+ "use mouse/keys or STOP", "red")
372
+
373
+ def clearCanvas(self):
374
+ self.refreshCanvas()
375
+ self.screen._delete("all")
376
+ self.scanvas.config(cursor="")
377
+ self.configGUI(NORMAL, DISABLED, DISABLED)
378
+
379
+ def stopIt(self):
380
+ if self.exitflag:
381
+ self.clearCanvas()
382
+ self.exitflag = False
383
+ self.configGUI(NORMAL, DISABLED, DISABLED,
384
+ "STOPPED!", "red")
385
+ turtle.TurtleScreen._RUNNING = False
386
+
387
+ def _destroy(self):
388
+ turtle.TurtleScreen._RUNNING = False
389
+ self.root.destroy()
390
+ self.root = None
391
+
392
+
393
+ def main():
394
+ demo = DemoWindow()
395
+ demo.root.mainloop()
396
+
397
+ if __name__ == '__main__':
398
+ main()
valley/lib/python3.10/turtledemo/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (711 Bytes). View file
 
valley/lib/python3.10/turtledemo/__pycache__/__main__.cpython-310.pyc ADDED
Binary file (13.6 kB). View file
 
valley/lib/python3.10/turtledemo/__pycache__/bytedesign.cpython-310.pyc ADDED
Binary file (4.08 kB). View file
 
valley/lib/python3.10/turtledemo/__pycache__/chaos.cpython-310.pyc ADDED
Binary file (1.97 kB). View file
 
valley/lib/python3.10/turtledemo/__pycache__/clock.cpython-310.pyc ADDED
Binary file (3.69 kB). View file
 
valley/lib/python3.10/turtledemo/__pycache__/colormixer.cpython-310.pyc ADDED
Binary file (2.1 kB). View file
 
valley/lib/python3.10/turtledemo/__pycache__/forest.cpython-310.pyc ADDED
Binary file (3.54 kB). View file
 
valley/lib/python3.10/turtledemo/__pycache__/fractalcurves.cpython-310.pyc ADDED
Binary file (3.15 kB). View file
 
valley/lib/python3.10/turtledemo/__pycache__/lindenmayer.cpython-310.pyc ADDED
Binary file (2.79 kB). View file
 
valley/lib/python3.10/turtledemo/__pycache__/minimal_hanoi.cpython-310.pyc ADDED
Binary file (3.09 kB). View file
 
valley/lib/python3.10/turtledemo/__pycache__/nim.cpython-310.pyc ADDED
Binary file (7.66 kB). View file
 
valley/lib/python3.10/turtledemo/__pycache__/paint.cpython-310.pyc ADDED
Binary file (1.62 kB). View file
 
valley/lib/python3.10/turtledemo/__pycache__/peace.cpython-310.pyc ADDED
Binary file (1.38 kB). View file
 
valley/lib/python3.10/turtledemo/__pycache__/penrose.cpython-310.pyc ADDED
Binary file (4.87 kB). View file
 
valley/lib/python3.10/turtledemo/__pycache__/planet_and_moon.cpython-310.pyc ADDED
Binary file (3.5 kB). View file
 
valley/lib/python3.10/turtledemo/__pycache__/rosette.cpython-310.pyc ADDED
Binary file (1.73 kB). View file
 
valley/lib/python3.10/turtledemo/__pycache__/round_dance.cpython-310.pyc ADDED
Binary file (1.9 kB). View file
 
valley/lib/python3.10/turtledemo/__pycache__/sorting_animate.cpython-310.pyc ADDED
Binary file (6.33 kB). View file
 
valley/lib/python3.10/turtledemo/__pycache__/tree.cpython-310.pyc ADDED
Binary file (2 kB). View file
 
valley/lib/python3.10/turtledemo/__pycache__/two_canvases.cpython-310.pyc ADDED
Binary file (1.53 kB). View file
 
valley/lib/python3.10/turtledemo/__pycache__/yinyang.cpython-310.pyc ADDED
Binary file (1.07 kB). View file
 
valley/lib/python3.10/turtledemo/bytedesign.py ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """ turtle-example-suite:
3
+
4
+ tdemo_bytedesign.py
5
+
6
+ An example adapted from the example-suite
7
+ of PythonCard's turtle graphics.
8
+
9
+ It's based on an article in BYTE magazine
10
+ Problem Solving with Logo: Using Turtle
11
+ Graphics to Redraw a Design
12
+ November 1982, p. 118 - 134
13
+
14
+ -------------------------------------------
15
+
16
+ Due to the statement
17
+
18
+ t.delay(0)
19
+
20
+ in line 152, which sets the animation delay
21
+ to 0, this animation runs in "line per line"
22
+ mode as fast as possible.
23
+ """
24
+
25
+ from turtle import Turtle, mainloop
26
+ from time import perf_counter as clock
27
+
28
+ # wrapper for any additional drawing routines
29
+ # that need to know about each other
30
+ class Designer(Turtle):
31
+
32
+ def design(self, homePos, scale):
33
+ self.up()
34
+ for i in range(5):
35
+ self.forward(64.65 * scale)
36
+ self.down()
37
+ self.wheel(self.position(), scale)
38
+ self.up()
39
+ self.backward(64.65 * scale)
40
+ self.right(72)
41
+ self.up()
42
+ self.goto(homePos)
43
+ self.right(36)
44
+ self.forward(24.5 * scale)
45
+ self.right(198)
46
+ self.down()
47
+ self.centerpiece(46 * scale, 143.4, scale)
48
+ self.getscreen().tracer(True)
49
+
50
+ def wheel(self, initpos, scale):
51
+ self.right(54)
52
+ for i in range(4):
53
+ self.pentpiece(initpos, scale)
54
+ self.down()
55
+ self.left(36)
56
+ for i in range(5):
57
+ self.tripiece(initpos, scale)
58
+ self.left(36)
59
+ for i in range(5):
60
+ self.down()
61
+ self.right(72)
62
+ self.forward(28 * scale)
63
+ self.up()
64
+ self.backward(28 * scale)
65
+ self.left(54)
66
+ self.getscreen().update()
67
+
68
+ def tripiece(self, initpos, scale):
69
+ oldh = self.heading()
70
+ self.down()
71
+ self.backward(2.5 * scale)
72
+ self.tripolyr(31.5 * scale, scale)
73
+ self.up()
74
+ self.goto(initpos)
75
+ self.setheading(oldh)
76
+ self.down()
77
+ self.backward(2.5 * scale)
78
+ self.tripolyl(31.5 * scale, scale)
79
+ self.up()
80
+ self.goto(initpos)
81
+ self.setheading(oldh)
82
+ self.left(72)
83
+ self.getscreen().update()
84
+
85
+ def pentpiece(self, initpos, scale):
86
+ oldh = self.heading()
87
+ self.up()
88
+ self.forward(29 * scale)
89
+ self.down()
90
+ for i in range(5):
91
+ self.forward(18 * scale)
92
+ self.right(72)
93
+ self.pentr(18 * scale, 75, scale)
94
+ self.up()
95
+ self.goto(initpos)
96
+ self.setheading(oldh)
97
+ self.forward(29 * scale)
98
+ self.down()
99
+ for i in range(5):
100
+ self.forward(18 * scale)
101
+ self.right(72)
102
+ self.pentl(18 * scale, 75, scale)
103
+ self.up()
104
+ self.goto(initpos)
105
+ self.setheading(oldh)
106
+ self.left(72)
107
+ self.getscreen().update()
108
+
109
+ def pentl(self, side, ang, scale):
110
+ if side < (2 * scale): return
111
+ self.forward(side)
112
+ self.left(ang)
113
+ self.pentl(side - (.38 * scale), ang, scale)
114
+
115
+ def pentr(self, side, ang, scale):
116
+ if side < (2 * scale): return
117
+ self.forward(side)
118
+ self.right(ang)
119
+ self.pentr(side - (.38 * scale), ang, scale)
120
+
121
+ def tripolyr(self, side, scale):
122
+ if side < (4 * scale): return
123
+ self.forward(side)
124
+ self.right(111)
125
+ self.forward(side / 1.78)
126
+ self.right(111)
127
+ self.forward(side / 1.3)
128
+ self.right(146)
129
+ self.tripolyr(side * .75, scale)
130
+
131
+ def tripolyl(self, side, scale):
132
+ if side < (4 * scale): return
133
+ self.forward(side)
134
+ self.left(111)
135
+ self.forward(side / 1.78)
136
+ self.left(111)
137
+ self.forward(side / 1.3)
138
+ self.left(146)
139
+ self.tripolyl(side * .75, scale)
140
+
141
+ def centerpiece(self, s, a, scale):
142
+ self.forward(s); self.left(a)
143
+ if s < (7.5 * scale):
144
+ return
145
+ self.centerpiece(s - (1.2 * scale), a, scale)
146
+
147
+ def main():
148
+ t = Designer()
149
+ t.speed(0)
150
+ t.hideturtle()
151
+ t.getscreen().delay(0)
152
+ t.getscreen().tracer(0)
153
+ at = clock()
154
+ t.design(t.position(), 2)
155
+ et = clock()
156
+ return "runtime: %.2f sec." % (et-at)
157
+
158
+ if __name__ == '__main__':
159
+ msg = main()
160
+ print(msg)
161
+ mainloop()
valley/lib/python3.10/turtledemo/chaos.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # File: tdemo_chaos.py
2
+ # Author: Gregor Lingl
3
+ # Date: 2009-06-24
4
+
5
+ # A demonstration of chaos
6
+
7
+ from turtle import *
8
+
9
+ N = 80
10
+
11
+ def f(x):
12
+ return 3.9*x*(1-x)
13
+
14
+ def g(x):
15
+ return 3.9*(x-x**2)
16
+
17
+ def h(x):
18
+ return 3.9*x-3.9*x*x
19
+
20
+ def jumpto(x, y):
21
+ penup(); goto(x,y)
22
+
23
+ def line(x1, y1, x2, y2):
24
+ jumpto(x1, y1)
25
+ pendown()
26
+ goto(x2, y2)
27
+
28
+ def coosys():
29
+ line(-1, 0, N+1, 0)
30
+ line(0, -0.1, 0, 1.1)
31
+
32
+ def plot(fun, start, color):
33
+ pencolor(color)
34
+ x = start
35
+ jumpto(0, x)
36
+ pendown()
37
+ dot(5)
38
+ for i in range(N):
39
+ x=fun(x)
40
+ goto(i+1,x)
41
+ dot(5)
42
+
43
+ def main():
44
+ reset()
45
+ setworldcoordinates(-1.0,-0.1, N+1, 1.1)
46
+ speed(0)
47
+ hideturtle()
48
+ coosys()
49
+ plot(f, 0.35, "blue")
50
+ plot(g, 0.35, "green")
51
+ plot(h, 0.35, "red")
52
+ # Now zoom in:
53
+ for s in range(100):
54
+ setworldcoordinates(0.5*s,-0.1, N+1, 1.1)
55
+ return "Done!"
56
+
57
+ if __name__ == "__main__":
58
+ main()
59
+ mainloop()
valley/lib/python3.10/turtledemo/clock.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # -*- coding: cp1252 -*-
3
+ """ turtle-example-suite:
4
+
5
+ tdemo_clock.py
6
+
7
+ Enhanced clock-program, showing date
8
+ and time
9
+ ------------------------------------
10
+ Press STOP to exit the program!
11
+ ------------------------------------
12
+ """
13
+ from turtle import *
14
+ from datetime import datetime
15
+
16
+ def jump(distanz, winkel=0):
17
+ penup()
18
+ right(winkel)
19
+ forward(distanz)
20
+ left(winkel)
21
+ pendown()
22
+
23
+ def hand(laenge, spitze):
24
+ fd(laenge*1.15)
25
+ rt(90)
26
+ fd(spitze/2.0)
27
+ lt(120)
28
+ fd(spitze)
29
+ lt(120)
30
+ fd(spitze)
31
+ lt(120)
32
+ fd(spitze/2.0)
33
+
34
+ def make_hand_shape(name, laenge, spitze):
35
+ reset()
36
+ jump(-laenge*0.15)
37
+ begin_poly()
38
+ hand(laenge, spitze)
39
+ end_poly()
40
+ hand_form = get_poly()
41
+ register_shape(name, hand_form)
42
+
43
+ def clockface(radius):
44
+ reset()
45
+ pensize(7)
46
+ for i in range(60):
47
+ jump(radius)
48
+ if i % 5 == 0:
49
+ fd(25)
50
+ jump(-radius-25)
51
+ else:
52
+ dot(3)
53
+ jump(-radius)
54
+ rt(6)
55
+
56
+ def setup():
57
+ global second_hand, minute_hand, hour_hand, writer
58
+ mode("logo")
59
+ make_hand_shape("second_hand", 125, 25)
60
+ make_hand_shape("minute_hand", 130, 25)
61
+ make_hand_shape("hour_hand", 90, 25)
62
+ clockface(160)
63
+ second_hand = Turtle()
64
+ second_hand.shape("second_hand")
65
+ second_hand.color("gray20", "gray80")
66
+ minute_hand = Turtle()
67
+ minute_hand.shape("minute_hand")
68
+ minute_hand.color("blue1", "red1")
69
+ hour_hand = Turtle()
70
+ hour_hand.shape("hour_hand")
71
+ hour_hand.color("blue3", "red3")
72
+ for hand in second_hand, minute_hand, hour_hand:
73
+ hand.resizemode("user")
74
+ hand.shapesize(1, 1, 3)
75
+ hand.speed(0)
76
+ ht()
77
+ writer = Turtle()
78
+ #writer.mode("logo")
79
+ writer.ht()
80
+ writer.pu()
81
+ writer.bk(85)
82
+
83
+ def wochentag(t):
84
+ wochentag = ["Monday", "Tuesday", "Wednesday",
85
+ "Thursday", "Friday", "Saturday", "Sunday"]
86
+ return wochentag[t.weekday()]
87
+
88
+ def datum(z):
89
+ monat = ["Jan.", "Feb.", "Mar.", "Apr.", "May", "June",
90
+ "July", "Aug.", "Sep.", "Oct.", "Nov.", "Dec."]
91
+ j = z.year
92
+ m = monat[z.month - 1]
93
+ t = z.day
94
+ return "%s %d %d" % (m, t, j)
95
+
96
+ def tick():
97
+ t = datetime.today()
98
+ sekunde = t.second + t.microsecond*0.000001
99
+ minute = t.minute + sekunde/60.0
100
+ stunde = t.hour + minute/60.0
101
+ try:
102
+ tracer(False) # Terminator can occur here
103
+ writer.clear()
104
+ writer.home()
105
+ writer.forward(65)
106
+ writer.write(wochentag(t),
107
+ align="center", font=("Courier", 14, "bold"))
108
+ writer.back(150)
109
+ writer.write(datum(t),
110
+ align="center", font=("Courier", 14, "bold"))
111
+ writer.forward(85)
112
+ second_hand.setheading(6*sekunde) # or here
113
+ minute_hand.setheading(6*minute)
114
+ hour_hand.setheading(30*stunde)
115
+ tracer(True)
116
+ ontimer(tick, 100)
117
+ except Terminator:
118
+ pass # turtledemo user pressed STOP
119
+
120
+ def main():
121
+ tracer(False)
122
+ setup()
123
+ tracer(True)
124
+ tick()
125
+ return "EVENTLOOP"
126
+
127
+ if __name__ == "__main__":
128
+ mode("logo")
129
+ msg = main()
130
+ print(msg)
131
+ mainloop()
valley/lib/python3.10/turtledemo/colormixer.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # colormixer
2
+
3
+ from turtle import Screen, Turtle, mainloop
4
+
5
+ class ColorTurtle(Turtle):
6
+
7
+ def __init__(self, x, y):
8
+ Turtle.__init__(self)
9
+ self.shape("turtle")
10
+ self.resizemode("user")
11
+ self.shapesize(3,3,5)
12
+ self.pensize(10)
13
+ self._color = [0,0,0]
14
+ self.x = x
15
+ self._color[x] = y
16
+ self.color(self._color)
17
+ self.speed(0)
18
+ self.left(90)
19
+ self.pu()
20
+ self.goto(x,0)
21
+ self.pd()
22
+ self.sety(1)
23
+ self.pu()
24
+ self.sety(y)
25
+ self.pencolor("gray25")
26
+ self.ondrag(self.shift)
27
+
28
+ def shift(self, x, y):
29
+ self.sety(max(0,min(y,1)))
30
+ self._color[self.x] = self.ycor()
31
+ self.fillcolor(self._color)
32
+ setbgcolor()
33
+
34
+ def setbgcolor():
35
+ screen.bgcolor(red.ycor(), green.ycor(), blue.ycor())
36
+
37
+ def main():
38
+ global screen, red, green, blue
39
+ screen = Screen()
40
+ screen.delay(0)
41
+ screen.setworldcoordinates(-1, -0.3, 3, 1.3)
42
+
43
+ red = ColorTurtle(0, .5)
44
+ green = ColorTurtle(1, .5)
45
+ blue = ColorTurtle(2, .5)
46
+ setbgcolor()
47
+
48
+ writer = Turtle()
49
+ writer.ht()
50
+ writer.pu()
51
+ writer.goto(1,1.15)
52
+ writer.write("DRAG!",align="center",font=("Arial",30,("bold","italic")))
53
+ return "EVENTLOOP"
54
+
55
+ if __name__ == "__main__":
56
+ msg = main()
57
+ print(msg)
58
+ mainloop()
valley/lib/python3.10/turtledemo/forest.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """ turtlegraphics-example-suite:
3
+
4
+ tdemo_forest.py
5
+
6
+ Displays a 'forest' of 3 breadth-first-trees
7
+ similar to the one in tree.
8
+ For further remarks see tree.py
9
+
10
+ This example is a 'breadth-first'-rewrite of
11
+ a Logo program written by Erich Neuwirth. See
12
+ http://homepage.univie.ac.at/erich.neuwirth/
13
+ """
14
+ from turtle import Turtle, colormode, tracer, mainloop
15
+ from random import randrange
16
+ from time import perf_counter as clock
17
+
18
+ def symRandom(n):
19
+ return randrange(-n,n+1)
20
+
21
+ def randomize( branchlist, angledist, sizedist ):
22
+ return [ (angle+symRandom(angledist),
23
+ sizefactor*1.01**symRandom(sizedist))
24
+ for angle, sizefactor in branchlist ]
25
+
26
+ def randomfd( t, distance, parts, angledist ):
27
+ for i in range(parts):
28
+ t.left(symRandom(angledist))
29
+ t.forward( (1.0 * distance)/parts )
30
+
31
+ def tree(tlist, size, level, widthfactor, branchlists, angledist=10, sizedist=5):
32
+ # benutzt Liste von turtles und Liste von Zweiglisten,
33
+ # fuer jede turtle eine!
34
+ if level > 0:
35
+ lst = []
36
+ brs = []
37
+ for t, branchlist in list(zip(tlist,branchlists)):
38
+ t.pensize( size * widthfactor )
39
+ t.pencolor( 255 - (180 - 11 * level + symRandom(15)),
40
+ 180 - 11 * level + symRandom(15),
41
+ 0 )
42
+ t.pendown()
43
+ randomfd(t, size, level, angledist )
44
+ yield 1
45
+ for angle, sizefactor in branchlist:
46
+ t.left(angle)
47
+ lst.append(t.clone())
48
+ brs.append(randomize(branchlist, angledist, sizedist))
49
+ t.right(angle)
50
+ for x in tree(lst, size*sizefactor, level-1, widthfactor, brs,
51
+ angledist, sizedist):
52
+ yield None
53
+
54
+
55
+ def start(t,x,y):
56
+ colormode(255)
57
+ t.reset()
58
+ t.speed(0)
59
+ t.hideturtle()
60
+ t.left(90)
61
+ t.penup()
62
+ t.setpos(x,y)
63
+ t.pendown()
64
+
65
+ def doit1(level, pen):
66
+ pen.hideturtle()
67
+ start(pen, 20, -208)
68
+ t = tree( [pen], 80, level, 0.1, [[ (45,0.69), (0,0.65), (-45,0.71) ]] )
69
+ return t
70
+
71
+ def doit2(level, pen):
72
+ pen.hideturtle()
73
+ start(pen, -135, -130)
74
+ t = tree( [pen], 120, level, 0.1, [[ (45,0.69), (-45,0.71) ]] )
75
+ return t
76
+
77
+ def doit3(level, pen):
78
+ pen.hideturtle()
79
+ start(pen, 190, -90)
80
+ t = tree( [pen], 100, level, 0.1, [[ (45,0.7), (0,0.72), (-45,0.65) ]] )
81
+ return t
82
+
83
+ # Hier 3 Baumgeneratoren:
84
+ def main():
85
+ p = Turtle()
86
+ p.ht()
87
+ tracer(75,0)
88
+ u = doit1(6, Turtle(undobuffersize=1))
89
+ s = doit2(7, Turtle(undobuffersize=1))
90
+ t = doit3(5, Turtle(undobuffersize=1))
91
+ a = clock()
92
+ while True:
93
+ done = 0
94
+ for b in u,s,t:
95
+ try:
96
+ b.__next__()
97
+ except:
98
+ done += 1
99
+ if done == 3:
100
+ break
101
+
102
+ tracer(1,10)
103
+ b = clock()
104
+ return "runtime: %.2f sec." % (b-a)
105
+
106
+ if __name__ == '__main__':
107
+ main()
108
+ mainloop()
valley/lib/python3.10/turtledemo/fractalcurves.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """ turtle-example-suite:
3
+
4
+ tdemo_fractalCurves.py
5
+
6
+ This program draws two fractal-curve-designs:
7
+ (1) A hilbert curve (in a box)
8
+ (2) A combination of Koch-curves.
9
+
10
+ The CurvesTurtle class and the fractal-curve-
11
+ methods are taken from the PythonCard example
12
+ scripts for turtle-graphics.
13
+ """
14
+ from turtle import *
15
+ from time import sleep, perf_counter as clock
16
+
17
+ class CurvesTurtle(Pen):
18
+ # example derived from
19
+ # Turtle Geometry: The Computer as a Medium for Exploring Mathematics
20
+ # by Harold Abelson and Andrea diSessa
21
+ # p. 96-98
22
+ def hilbert(self, size, level, parity):
23
+ if level == 0:
24
+ return
25
+ # rotate and draw first subcurve with opposite parity to big curve
26
+ self.left(parity * 90)
27
+ self.hilbert(size, level - 1, -parity)
28
+ # interface to and draw second subcurve with same parity as big curve
29
+ self.forward(size)
30
+ self.right(parity * 90)
31
+ self.hilbert(size, level - 1, parity)
32
+ # third subcurve
33
+ self.forward(size)
34
+ self.hilbert(size, level - 1, parity)
35
+ # fourth subcurve
36
+ self.right(parity * 90)
37
+ self.forward(size)
38
+ self.hilbert(size, level - 1, -parity)
39
+ # a final turn is needed to make the turtle
40
+ # end up facing outward from the large square
41
+ self.left(parity * 90)
42
+
43
+ # Visual Modeling with Logo: A Structural Approach to Seeing
44
+ # by James Clayson
45
+ # Koch curve, after Helge von Koch who introduced this geometric figure in 1904
46
+ # p. 146
47
+ def fractalgon(self, n, rad, lev, dir):
48
+ import math
49
+
50
+ # if dir = 1 turn outward
51
+ # if dir = -1 turn inward
52
+ edge = 2 * rad * math.sin(math.pi / n)
53
+ self.pu()
54
+ self.fd(rad)
55
+ self.pd()
56
+ self.rt(180 - (90 * (n - 2) / n))
57
+ for i in range(n):
58
+ self.fractal(edge, lev, dir)
59
+ self.rt(360 / n)
60
+ self.lt(180 - (90 * (n - 2) / n))
61
+ self.pu()
62
+ self.bk(rad)
63
+ self.pd()
64
+
65
+ # p. 146
66
+ def fractal(self, dist, depth, dir):
67
+ if depth < 1:
68
+ self.fd(dist)
69
+ return
70
+ self.fractal(dist / 3, depth - 1, dir)
71
+ self.lt(60 * dir)
72
+ self.fractal(dist / 3, depth - 1, dir)
73
+ self.rt(120 * dir)
74
+ self.fractal(dist / 3, depth - 1, dir)
75
+ self.lt(60 * dir)
76
+ self.fractal(dist / 3, depth - 1, dir)
77
+
78
+ def main():
79
+ ft = CurvesTurtle()
80
+
81
+ ft.reset()
82
+ ft.speed(0)
83
+ ft.ht()
84
+ ft.getscreen().tracer(1,0)
85
+ ft.pu()
86
+
87
+ size = 6
88
+ ft.setpos(-33*size, -32*size)
89
+ ft.pd()
90
+
91
+ ta=clock()
92
+ ft.fillcolor("red")
93
+ ft.begin_fill()
94
+ ft.fd(size)
95
+
96
+ ft.hilbert(size, 6, 1)
97
+
98
+ # frame
99
+ ft.fd(size)
100
+ for i in range(3):
101
+ ft.lt(90)
102
+ ft.fd(size*(64+i%2))
103
+ ft.pu()
104
+ for i in range(2):
105
+ ft.fd(size)
106
+ ft.rt(90)
107
+ ft.pd()
108
+ for i in range(4):
109
+ ft.fd(size*(66+i%2))
110
+ ft.rt(90)
111
+ ft.end_fill()
112
+ tb=clock()
113
+ res = "Hilbert: %.2fsec. " % (tb-ta)
114
+
115
+ sleep(3)
116
+
117
+ ft.reset()
118
+ ft.speed(0)
119
+ ft.ht()
120
+ ft.getscreen().tracer(1,0)
121
+
122
+ ta=clock()
123
+ ft.color("black", "blue")
124
+ ft.begin_fill()
125
+ ft.fractalgon(3, 250, 4, 1)
126
+ ft.end_fill()
127
+ ft.begin_fill()
128
+ ft.color("red")
129
+ ft.fractalgon(3, 200, 4, -1)
130
+ ft.end_fill()
131
+ tb=clock()
132
+ res += "Koch: %.2fsec." % (tb-ta)
133
+ return res
134
+
135
+ if __name__ == '__main__':
136
+ msg = main()
137
+ print(msg)
138
+ mainloop()
valley/lib/python3.10/turtledemo/lindenmayer.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """ turtle-example-suite:
3
+
4
+ xtx_lindenmayer_indian.py
5
+
6
+ Each morning women in Tamil Nadu, in southern
7
+ India, place designs, created by using rice
8
+ flour and known as kolam on the thresholds of
9
+ their homes.
10
+
11
+ These can be described by Lindenmayer systems,
12
+ which can easily be implemented with turtle
13
+ graphics and Python.
14
+
15
+ Two examples are shown here:
16
+ (1) the snake kolam
17
+ (2) anklets of Krishna
18
+
19
+ Taken from Marcia Ascher: Mathematics
20
+ Elsewhere, An Exploration of Ideas Across
21
+ Cultures
22
+
23
+ """
24
+ ################################
25
+ # Mini Lindenmayer tool
26
+ ###############################
27
+
28
+ from turtle import *
29
+
30
+ def replace( seq, replacementRules, n ):
31
+ for i in range(n):
32
+ newseq = ""
33
+ for element in seq:
34
+ newseq = newseq + replacementRules.get(element,element)
35
+ seq = newseq
36
+ return seq
37
+
38
+ def draw( commands, rules ):
39
+ for b in commands:
40
+ try:
41
+ rules[b]()
42
+ except TypeError:
43
+ try:
44
+ draw(rules[b], rules)
45
+ except:
46
+ pass
47
+
48
+
49
+ def main():
50
+ ################################
51
+ # Example 1: Snake kolam
52
+ ################################
53
+
54
+
55
+ def r():
56
+ right(45)
57
+
58
+ def l():
59
+ left(45)
60
+
61
+ def f():
62
+ forward(7.5)
63
+
64
+ snake_rules = {"-":r, "+":l, "f":f, "b":"f+f+f--f--f+f+f"}
65
+ snake_replacementRules = {"b": "b+f+b--f--b+f+b"}
66
+ snake_start = "b--f--b--f"
67
+
68
+ drawing = replace(snake_start, snake_replacementRules, 3)
69
+
70
+ reset()
71
+ speed(3)
72
+ tracer(1,0)
73
+ ht()
74
+ up()
75
+ backward(195)
76
+ down()
77
+ draw(drawing, snake_rules)
78
+
79
+ from time import sleep
80
+ sleep(3)
81
+
82
+ ################################
83
+ # Example 2: Anklets of Krishna
84
+ ################################
85
+
86
+ def A():
87
+ color("red")
88
+ circle(10,90)
89
+
90
+ def B():
91
+ from math import sqrt
92
+ color("black")
93
+ l = 5/sqrt(2)
94
+ forward(l)
95
+ circle(l, 270)
96
+ forward(l)
97
+
98
+ def F():
99
+ color("green")
100
+ forward(10)
101
+
102
+ krishna_rules = {"a":A, "b":B, "f":F}
103
+ krishna_replacementRules = {"a" : "afbfa", "b" : "afbfbfbfa" }
104
+ krishna_start = "fbfbfbfb"
105
+
106
+ reset()
107
+ speed(0)
108
+ tracer(3,0)
109
+ ht()
110
+ left(45)
111
+ drawing = replace(krishna_start, krishna_replacementRules, 3)
112
+ draw(drawing, krishna_rules)
113
+ tracer(1)
114
+ return "Done!"
115
+
116
+ if __name__=='__main__':
117
+ msg = main()
118
+ print(msg)
119
+ mainloop()
valley/lib/python3.10/turtledemo/minimal_hanoi.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """ turtle-example-suite:
3
+
4
+ tdemo_minimal_hanoi.py
5
+
6
+ A minimal 'Towers of Hanoi' animation:
7
+ A tower of 6 discs is transferred from the
8
+ left to the right peg.
9
+
10
+ An imho quite elegant and concise
11
+ implementation using a tower class, which
12
+ is derived from the built-in type list.
13
+
14
+ Discs are turtles with shape "square", but
15
+ stretched to rectangles by shapesize()
16
+ ---------------------------------------
17
+ To exit press STOP button
18
+ ---------------------------------------
19
+ """
20
+ from turtle import *
21
+
22
+ class Disc(Turtle):
23
+ def __init__(self, n):
24
+ Turtle.__init__(self, shape="square", visible=False)
25
+ self.pu()
26
+ self.shapesize(1.5, n*1.5, 2) # square-->rectangle
27
+ self.fillcolor(n/6., 0, 1-n/6.)
28
+ self.st()
29
+
30
+ class Tower(list):
31
+ "Hanoi tower, a subclass of built-in type list"
32
+ def __init__(self, x):
33
+ "create an empty tower. x is x-position of peg"
34
+ self.x = x
35
+ def push(self, d):
36
+ d.setx(self.x)
37
+ d.sety(-150+34*len(self))
38
+ self.append(d)
39
+ def pop(self):
40
+ d = list.pop(self)
41
+ d.sety(150)
42
+ return d
43
+
44
+ def hanoi(n, from_, with_, to_):
45
+ if n > 0:
46
+ hanoi(n-1, from_, to_, with_)
47
+ to_.push(from_.pop())
48
+ hanoi(n-1, with_, from_, to_)
49
+
50
+ def play():
51
+ onkey(None,"space")
52
+ clear()
53
+ try:
54
+ hanoi(6, t1, t2, t3)
55
+ write("press STOP button to exit",
56
+ align="center", font=("Courier", 16, "bold"))
57
+ except Terminator:
58
+ pass # turtledemo user pressed STOP
59
+
60
+ def main():
61
+ global t1, t2, t3
62
+ ht(); penup(); goto(0, -225) # writer turtle
63
+ t1 = Tower(-250)
64
+ t2 = Tower(0)
65
+ t3 = Tower(250)
66
+ # make tower of 6 discs
67
+ for i in range(6,0,-1):
68
+ t1.push(Disc(i))
69
+ # prepare spartanic user interface ;-)
70
+ write("press spacebar to start game",
71
+ align="center", font=("Courier", 16, "bold"))
72
+ onkey(play, "space")
73
+ listen()
74
+ return "EVENTLOOP"
75
+
76
+ if __name__=="__main__":
77
+ msg = main()
78
+ print(msg)
79
+ mainloop()
valley/lib/python3.10/turtledemo/nim.py ADDED
@@ -0,0 +1,226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ turtle-example-suite:
2
+
3
+ tdemo_nim.py
4
+
5
+ Play nim against the computer. The player
6
+ who takes the last stick is the winner.
7
+
8
+ Implements the model-view-controller
9
+ design pattern.
10
+ """
11
+
12
+
13
+ import turtle
14
+ import random
15
+ import time
16
+
17
+ SCREENWIDTH = 640
18
+ SCREENHEIGHT = 480
19
+
20
+ MINSTICKS = 7
21
+ MAXSTICKS = 31
22
+
23
+ HUNIT = SCREENHEIGHT // 12
24
+ WUNIT = SCREENWIDTH // ((MAXSTICKS // 5) * 11 + (MAXSTICKS % 5) * 2)
25
+
26
+ SCOLOR = (63, 63, 31)
27
+ HCOLOR = (255, 204, 204)
28
+ COLOR = (204, 204, 255)
29
+
30
+ def randomrow():
31
+ return random.randint(MINSTICKS, MAXSTICKS)
32
+
33
+ def computerzug(state):
34
+ xored = state[0] ^ state[1] ^ state[2]
35
+ if xored == 0:
36
+ return randommove(state)
37
+ for z in range(3):
38
+ s = state[z] ^ xored
39
+ if s <= state[z]:
40
+ move = (z, s)
41
+ return move
42
+
43
+ def randommove(state):
44
+ m = max(state)
45
+ while True:
46
+ z = random.randint(0,2)
47
+ if state[z] > (m > 1):
48
+ break
49
+ rand = random.randint(m > 1, state[z]-1)
50
+ return z, rand
51
+
52
+
53
+ class NimModel(object):
54
+ def __init__(self, game):
55
+ self.game = game
56
+
57
+ def setup(self):
58
+ if self.game.state not in [Nim.CREATED, Nim.OVER]:
59
+ return
60
+ self.sticks = [randomrow(), randomrow(), randomrow()]
61
+ self.player = 0
62
+ self.winner = None
63
+ self.game.view.setup()
64
+ self.game.state = Nim.RUNNING
65
+
66
+ def move(self, row, col):
67
+ maxspalte = self.sticks[row]
68
+ self.sticks[row] = col
69
+ self.game.view.notify_move(row, col, maxspalte, self.player)
70
+ if self.game_over():
71
+ self.game.state = Nim.OVER
72
+ self.winner = self.player
73
+ self.game.view.notify_over()
74
+ elif self.player == 0:
75
+ self.player = 1
76
+ row, col = computerzug(self.sticks)
77
+ self.move(row, col)
78
+ self.player = 0
79
+
80
+ def game_over(self):
81
+ return self.sticks == [0, 0, 0]
82
+
83
+ def notify_move(self, row, col):
84
+ if self.sticks[row] <= col:
85
+ return
86
+ self.move(row, col)
87
+
88
+
89
+ class Stick(turtle.Turtle):
90
+ def __init__(self, row, col, game):
91
+ turtle.Turtle.__init__(self, visible=False)
92
+ self.row = row
93
+ self.col = col
94
+ self.game = game
95
+ x, y = self.coords(row, col)
96
+ self.shape("square")
97
+ self.shapesize(HUNIT/10.0, WUNIT/20.0)
98
+ self.speed(0)
99
+ self.pu()
100
+ self.goto(x,y)
101
+ self.color("white")
102
+ self.showturtle()
103
+
104
+ def coords(self, row, col):
105
+ packet, remainder = divmod(col, 5)
106
+ x = (3 + 11 * packet + 2 * remainder) * WUNIT
107
+ y = (2 + 3 * row) * HUNIT
108
+ return x - SCREENWIDTH // 2 + WUNIT // 2, SCREENHEIGHT // 2 - y - HUNIT // 2
109
+
110
+ def makemove(self, x, y):
111
+ if self.game.state != Nim.RUNNING:
112
+ return
113
+ self.game.controller.notify_move(self.row, self.col)
114
+
115
+
116
+ class NimView(object):
117
+ def __init__(self, game):
118
+ self.game = game
119
+ self.screen = game.screen
120
+ self.model = game.model
121
+ self.screen.colormode(255)
122
+ self.screen.tracer(False)
123
+ self.screen.bgcolor((240, 240, 255))
124
+ self.writer = turtle.Turtle(visible=False)
125
+ self.writer.pu()
126
+ self.writer.speed(0)
127
+ self.sticks = {}
128
+ for row in range(3):
129
+ for col in range(MAXSTICKS):
130
+ self.sticks[(row, col)] = Stick(row, col, game)
131
+ self.display("... a moment please ...")
132
+ self.screen.tracer(True)
133
+
134
+ def display(self, msg1, msg2=None):
135
+ self.screen.tracer(False)
136
+ self.writer.clear()
137
+ if msg2 is not None:
138
+ self.writer.goto(0, - SCREENHEIGHT // 2 + 48)
139
+ self.writer.pencolor("red")
140
+ self.writer.write(msg2, align="center", font=("Courier",18,"bold"))
141
+ self.writer.goto(0, - SCREENHEIGHT // 2 + 20)
142
+ self.writer.pencolor("black")
143
+ self.writer.write(msg1, align="center", font=("Courier",14,"bold"))
144
+ self.screen.tracer(True)
145
+
146
+ def setup(self):
147
+ self.screen.tracer(False)
148
+ for row in range(3):
149
+ for col in range(self.model.sticks[row]):
150
+ self.sticks[(row, col)].color(SCOLOR)
151
+ for row in range(3):
152
+ for col in range(self.model.sticks[row], MAXSTICKS):
153
+ self.sticks[(row, col)].color("white")
154
+ self.display("Your turn! Click leftmost stick to remove.")
155
+ self.screen.tracer(True)
156
+
157
+ def notify_move(self, row, col, maxspalte, player):
158
+ if player == 0:
159
+ farbe = HCOLOR
160
+ for s in range(col, maxspalte):
161
+ self.sticks[(row, s)].color(farbe)
162
+ else:
163
+ self.display(" ... thinking ... ")
164
+ time.sleep(0.5)
165
+ self.display(" ... thinking ... aaah ...")
166
+ farbe = COLOR
167
+ for s in range(maxspalte-1, col-1, -1):
168
+ time.sleep(0.2)
169
+ self.sticks[(row, s)].color(farbe)
170
+ self.display("Your turn! Click leftmost stick to remove.")
171
+
172
+ def notify_over(self):
173
+ if self.game.model.winner == 0:
174
+ msg2 = "Congrats. You're the winner!!!"
175
+ else:
176
+ msg2 = "Sorry, the computer is the winner."
177
+ self.display("To play again press space bar. To leave press ESC.", msg2)
178
+
179
+ def clear(self):
180
+ if self.game.state == Nim.OVER:
181
+ self.screen.clear()
182
+
183
+
184
+ class NimController(object):
185
+
186
+ def __init__(self, game):
187
+ self.game = game
188
+ self.sticks = game.view.sticks
189
+ self.BUSY = False
190
+ for stick in self.sticks.values():
191
+ stick.onclick(stick.makemove)
192
+ self.game.screen.onkey(self.game.model.setup, "space")
193
+ self.game.screen.onkey(self.game.view.clear, "Escape")
194
+ self.game.view.display("Press space bar to start game")
195
+ self.game.screen.listen()
196
+
197
+ def notify_move(self, row, col):
198
+ if self.BUSY:
199
+ return
200
+ self.BUSY = True
201
+ self.game.model.notify_move(row, col)
202
+ self.BUSY = False
203
+
204
+
205
+ class Nim(object):
206
+ CREATED = 0
207
+ RUNNING = 1
208
+ OVER = 2
209
+ def __init__(self, screen):
210
+ self.state = Nim.CREATED
211
+ self.screen = screen
212
+ self.model = NimModel(self)
213
+ self.view = NimView(self)
214
+ self.controller = NimController(self)
215
+
216
+
217
+ def main():
218
+ mainscreen = turtle.Screen()
219
+ mainscreen.mode("standard")
220
+ mainscreen.setup(SCREENWIDTH, SCREENHEIGHT)
221
+ nim = Nim(mainscreen)
222
+ return "EVENTLOOP"
223
+
224
+ if __name__ == "__main__":
225
+ main()
226
+ turtle.mainloop()