easy-logging-py 1.1.5__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- easy_logging_py-1.1.5/LICENSE +201 -0
- easy_logging_py-1.1.5/PKG-INFO +39 -0
- easy_logging_py-1.1.5/README.md +3 -0
- easy_logging_py-1.1.5/easy_logging_py/__init__.py +0 -0
- easy_logging_py-1.1.5/easy_logging_py/clients.py +181 -0
- easy_logging_py-1.1.5/easy_logging_py/handlers.py +215 -0
- easy_logging_py-1.1.5/easy_logging_py/transports.py +169 -0
- easy_logging_py-1.1.5/easy_logging_py.egg-info/PKG-INFO +39 -0
- easy_logging_py-1.1.5/easy_logging_py.egg-info/SOURCES.txt +14 -0
- easy_logging_py-1.1.5/easy_logging_py.egg-info/dependency_links.txt +1 -0
- easy_logging_py-1.1.5/easy_logging_py.egg-info/requires.txt +9 -0
- easy_logging_py-1.1.5/easy_logging_py.egg-info/top_level.txt +1 -0
- easy_logging_py-1.1.5/setup.cfg +4 -0
- easy_logging_py-1.1.5/setup.py +51 -0
- easy_logging_py-1.1.5/tests/test_easy_logging.py +66 -0
- easy_logging_py-1.1.5/tests/test_http_transport.py +163 -0
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: easy-logging-py
|
|
3
|
+
Version: 1.1.5
|
|
4
|
+
Summary: Python sdk for Easy Logging
|
|
5
|
+
Author: Anton Gorinenko
|
|
6
|
+
Author-email: anton.gorinenko@gmail.com
|
|
7
|
+
Keywords: python,utils,easy logging
|
|
8
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
9
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
10
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
13
|
+
Classifier: Operating System :: OS Independent
|
|
14
|
+
Requires-Python: >=3.13
|
|
15
|
+
Description-Content-Type: text/markdown
|
|
16
|
+
License-File: LICENSE
|
|
17
|
+
Requires-Dist: http-misc[aiohttp]<4.0,>=3.0
|
|
18
|
+
Provides-Extra: test
|
|
19
|
+
Requires-Dist: pytest; extra == "test"
|
|
20
|
+
Requires-Dist: python-dotenv; extra == "test"
|
|
21
|
+
Requires-Dist: envparse; extra == "test"
|
|
22
|
+
Requires-Dist: pytest-asyncio; extra == "test"
|
|
23
|
+
Requires-Dist: pytest-mock; extra == "test"
|
|
24
|
+
Requires-Dist: pytest-env; extra == "test"
|
|
25
|
+
Dynamic: author
|
|
26
|
+
Dynamic: author-email
|
|
27
|
+
Dynamic: classifier
|
|
28
|
+
Dynamic: description
|
|
29
|
+
Dynamic: description-content-type
|
|
30
|
+
Dynamic: keywords
|
|
31
|
+
Dynamic: license-file
|
|
32
|
+
Dynamic: provides-extra
|
|
33
|
+
Dynamic: requires-dist
|
|
34
|
+
Dynamic: requires-python
|
|
35
|
+
Dynamic: summary
|
|
36
|
+
|
|
37
|
+
# Клиент Easy Logging на Python.
|
|
38
|
+
|
|
39
|
+
Библиотека утилитарных модулей для работы с распределенной системой логирования Easy Logging на Python.
|
|
File without changes
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
import abc
|
|
2
|
+
import uuid
|
|
3
|
+
from collections.abc import Collection
|
|
4
|
+
|
|
5
|
+
from easy_logging_py import transports
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class BaseClient(abc.ABC):
|
|
9
|
+
"""
|
|
10
|
+
Базовый клиент
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
def __init__(self, transport: transports.AsyncBaseTransport):
|
|
14
|
+
self.transport = transport
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class NamespacedClient:
|
|
18
|
+
def __init__(self, client: BaseClient):
|
|
19
|
+
self._client = client
|
|
20
|
+
self.transport = self._client.transport
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class AsyncOrganizationsClient(NamespacedClient):
|
|
24
|
+
""" Работа с организациями """
|
|
25
|
+
list_endpoint_kwargs = {'version': 'v1', 'name': 'organizations', 'is_admin': True}
|
|
26
|
+
|
|
27
|
+
async def create(self, name: str, internal_name: str, ignore_status: int | Collection[int] = None) -> dict:
|
|
28
|
+
""" Создание организации """
|
|
29
|
+
list_endpoint = transports.Endpoint(**self.list_endpoint_kwargs)
|
|
30
|
+
return await self.transport.create(list_endpoint, name=name, internal_name=internal_name,
|
|
31
|
+
ignore_status=ignore_status)
|
|
32
|
+
|
|
33
|
+
async def delete(self, pk: int, ignore_status: int | Collection[int] = None) -> None:
|
|
34
|
+
""" Удаление организации """
|
|
35
|
+
list_endpoint = transports.Endpoint(**self.list_endpoint_kwargs)
|
|
36
|
+
return await self.transport.delete(list_endpoint, item_id=pk, ignore_status=ignore_status)
|
|
37
|
+
|
|
38
|
+
async def get(self, pk: int, ignore_status: int | Collection[int] = None) -> dict:
|
|
39
|
+
""" Получение организации """
|
|
40
|
+
list_endpoint = transports.Endpoint(**self.list_endpoint_kwargs)
|
|
41
|
+
return await self.transport.get(list_endpoint, item_id=pk, ignore_status=ignore_status)
|
|
42
|
+
|
|
43
|
+
async def create_documents(self, internal_name: str, folder_id: str, entries: list[dict],
|
|
44
|
+
defaults: dict | None = None,
|
|
45
|
+
ignore_status: int | Collection[int] = None) -> dict:
|
|
46
|
+
""" Запрос предназначен для пакетной регистрации документов """
|
|
47
|
+
endpoint = transports.Endpoint(version='v1', name=f'organizations/{internal_name}/logs')
|
|
48
|
+
return await self.transport.create(endpoint, folder_id=folder_id,
|
|
49
|
+
entries=entries, defaults=defaults, ignore_status=ignore_status)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class AsyncFoldersClient(NamespacedClient):
|
|
53
|
+
""" Работа с папками """
|
|
54
|
+
list_endpoint_kwargs = {'version': 'v1', 'name': 'folders', 'is_admin': True}
|
|
55
|
+
|
|
56
|
+
async def create(self, name: str, folder_id: str, organization_id: int, description: str | None = None,
|
|
57
|
+
ignore_status: int | Collection[int] = None) -> dict:
|
|
58
|
+
""" Создание папки """
|
|
59
|
+
list_endpoint = transports.Endpoint(**self.list_endpoint_kwargs)
|
|
60
|
+
return await self.transport.create(list_endpoint, name=name, folder_id=folder_id,
|
|
61
|
+
organization_id=organization_id, description=description,
|
|
62
|
+
ignore_status=ignore_status)
|
|
63
|
+
|
|
64
|
+
async def delete(self, pk: int, ignore_status: int | Collection[int] = None) -> None:
|
|
65
|
+
""" Удаление папки """
|
|
66
|
+
list_endpoint = transports.Endpoint(**self.list_endpoint_kwargs)
|
|
67
|
+
return await self.transport.delete(list_endpoint, item_id=pk, ignore_status=ignore_status)
|
|
68
|
+
|
|
69
|
+
async def get(self, pk: int, ignore_status: int | Collection[int] = None) -> dict:
|
|
70
|
+
""" Получение папки """
|
|
71
|
+
list_endpoint = transports.Endpoint(**self.list_endpoint_kwargs)
|
|
72
|
+
return await self.transport.get(list_endpoint, item_id=pk, ignore_status=ignore_status)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class AsyncDevicesClient(NamespacedClient):
|
|
76
|
+
""" Работа с devices """
|
|
77
|
+
list_endpoint_kwargs = {'version': 'v1', 'name': 'devices', 'is_admin': False}
|
|
78
|
+
async def get(self, resource_name: str, device_id: int, ignore_status: int | Collection[int] = None) -> dict:
|
|
79
|
+
""" Получение устройства """
|
|
80
|
+
list_endpoint = transports.Endpoint(**self.list_endpoint_kwargs, prefix=['resources', resource_name])
|
|
81
|
+
return await self.transport.get(list_endpoint, item_id=device_id, ignore_status=ignore_status)
|
|
82
|
+
|
|
83
|
+
async def create(self, resource_name: str, device_protocol_id: str,
|
|
84
|
+
extra_config: dict | None = None,
|
|
85
|
+
status: str | None = None,
|
|
86
|
+
device_id: uuid.UUID | None = None,
|
|
87
|
+
ignore_status: int | Collection[int] = None) -> dict:
|
|
88
|
+
""" Создание устройства """
|
|
89
|
+
list_endpoint = transports.Endpoint(**self.list_endpoint_kwargs, prefix=['resources', resource_name])
|
|
90
|
+
request = {
|
|
91
|
+
'deviceProtocolId': device_protocol_id,
|
|
92
|
+
'extraConfig': extra_config
|
|
93
|
+
}
|
|
94
|
+
if status:
|
|
95
|
+
request['status'] = status
|
|
96
|
+
if device_id:
|
|
97
|
+
request['deviceId'] = str(device_id)
|
|
98
|
+
|
|
99
|
+
return await self.transport.create(list_endpoint, ignore_status=ignore_status, **request)
|
|
100
|
+
|
|
101
|
+
async def update(self, resource_name: str, device_id: int,
|
|
102
|
+
extra_config: dict | None = None,
|
|
103
|
+
status: str | None = None,
|
|
104
|
+
ignore_status: int | Collection[int] = None) -> dict:
|
|
105
|
+
""" Обновление устройства """
|
|
106
|
+
list_endpoint = transports.Endpoint(**self.list_endpoint_kwargs, prefix=['resources', resource_name])
|
|
107
|
+
request = {}
|
|
108
|
+
if extra_config:
|
|
109
|
+
request['extraConfig'] = extra_config
|
|
110
|
+
if status:
|
|
111
|
+
request['status'] = status
|
|
112
|
+
if not request:
|
|
113
|
+
raise ValueError('Не указан запрос на обновление устройства.')
|
|
114
|
+
return await self.transport.update(list_endpoint, item_id=device_id, ignore_status=ignore_status, **request)
|
|
115
|
+
|
|
116
|
+
async def delete(self, resource_name: str, device_id: int, ignore_status: int | Collection[int] = None) -> None:
|
|
117
|
+
""" Удаление устройства """
|
|
118
|
+
list_endpoint = transports.Endpoint(**self.list_endpoint_kwargs, prefix=['resources', resource_name])
|
|
119
|
+
return await self.transport.delete(list_endpoint, item_id=device_id, ignore_status=ignore_status)
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
class HeartbeatClient(NamespacedClient):
|
|
123
|
+
""" Работа с heartbeat """
|
|
124
|
+
|
|
125
|
+
async def shutdown(self, resource_name: str, resource_type: str,
|
|
126
|
+
ignore_status: int | Collection[int] = None) -> dict:
|
|
127
|
+
""" Сигнал выключения агента. """
|
|
128
|
+
endpoint = transports.Endpoint(version='v1', name='shutdown')
|
|
129
|
+
request = {
|
|
130
|
+
'resourceId': resource_name,
|
|
131
|
+
'resourceType': resource_type
|
|
132
|
+
}
|
|
133
|
+
return await self.transport.update(endpoint, ignore_status=ignore_status, **request)
|
|
134
|
+
|
|
135
|
+
async def push(self, resource_name: str, resource_type: str,
|
|
136
|
+
device_types: list[dict] | None = None,
|
|
137
|
+
devices: list[dict] | None = None,
|
|
138
|
+
ignore_status: int | Collection[int] = None) -> dict:
|
|
139
|
+
""" Периодический сигнал, генерируемый агентом для индикации нормальной работы. """
|
|
140
|
+
endpoint = transports.Endpoint(version='v1', name='heartbeat')
|
|
141
|
+
request = {
|
|
142
|
+
'resourceId': resource_name,
|
|
143
|
+
'resourceType': resource_type
|
|
144
|
+
}
|
|
145
|
+
if device_types:
|
|
146
|
+
request['deviceTypes'] = device_types
|
|
147
|
+
|
|
148
|
+
if devices:
|
|
149
|
+
request['devices'] = devices
|
|
150
|
+
|
|
151
|
+
return await self.transport.update(endpoint, ignore_status=ignore_status, **request)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
class AsyncEasyLoggingClient(BaseClient):
|
|
155
|
+
"""
|
|
156
|
+
Асинхронный AsyncEasy клиент
|
|
157
|
+
"""
|
|
158
|
+
|
|
159
|
+
def __init__(self, *args, **kwargs):
|
|
160
|
+
super().__init__(*args, **kwargs)
|
|
161
|
+
self.organizations = AsyncOrganizationsClient(self)
|
|
162
|
+
self.folders = AsyncFoldersClient(self)
|
|
163
|
+
|
|
164
|
+
async def propagate_folder(self, internal_name: str, folder_id: str,
|
|
165
|
+
ignore_status: int | Collection[int] = None) -> dict:
|
|
166
|
+
""" Запрос предназначен для развертывания хранилища для папки """
|
|
167
|
+
endpoint = transports.Endpoint(version='v1',
|
|
168
|
+
name=f'admin/organizations/{internal_name}/folders/',
|
|
169
|
+
postfix=['propagate'])
|
|
170
|
+
return await self.transport.update(endpoint, item_id=folder_id, ignore_status=ignore_status)
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
class AsyncResourcesClient(BaseClient):
|
|
174
|
+
"""
|
|
175
|
+
Асинхронный Resources клиент
|
|
176
|
+
"""
|
|
177
|
+
|
|
178
|
+
def __init__(self, *args, **kwargs):
|
|
179
|
+
super().__init__(*args, **kwargs)
|
|
180
|
+
self.heartbeats = HeartbeatClient(self)
|
|
181
|
+
self.devices = AsyncDevicesClient(self)
|
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
import abc
|
|
2
|
+
import asyncio
|
|
3
|
+
import datetime
|
|
4
|
+
import json
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from easy_logging_py.clients import AsyncEasyLoggingClient
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@dataclass
|
|
12
|
+
class LogBatchConfig:
|
|
13
|
+
""" Конфигурация пакетной отправки логов """
|
|
14
|
+
# Количество обработчиков
|
|
15
|
+
num_workers: int | None = 1
|
|
16
|
+
# Размер буфера (количество записей)
|
|
17
|
+
buffer_size: int | None = 100
|
|
18
|
+
# После достижения максимального размера происходит очистка буфера без отправки логов
|
|
19
|
+
max_buffer_size: int | None = 2000
|
|
20
|
+
# Максимальное время накопления в секундах
|
|
21
|
+
flush_interval_seconds: float | None = 5.0
|
|
22
|
+
# Максимальный размер пакета в байтах
|
|
23
|
+
max_batch_bytes: int | None = 1024 * 1024 # 1MB
|
|
24
|
+
# Количество попыток при ошибке
|
|
25
|
+
max_retries: int | None = 1
|
|
26
|
+
# Задержка между попытками
|
|
27
|
+
retry_delay_seconds: float | None = 1.0
|
|
28
|
+
# Таймаут отправки
|
|
29
|
+
request_timeout: float | None = 30.0
|
|
30
|
+
# Таймаут добавления в очередь обработки логов
|
|
31
|
+
emit_timeout: float | None = 0.5
|
|
32
|
+
# Максимальное количество логов в очереди перед блокировкой
|
|
33
|
+
max_queue_size: int | None = 10000
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class BaseHandler(abc.ABC):
|
|
37
|
+
def __init__(self, organization: str,
|
|
38
|
+
folder_id: str,
|
|
39
|
+
client: AsyncEasyLoggingClient,
|
|
40
|
+
batch_config: LogBatchConfig,
|
|
41
|
+
defaults: dict | None = None):
|
|
42
|
+
self.organization = organization
|
|
43
|
+
self.folder_id = folder_id
|
|
44
|
+
self.client = client
|
|
45
|
+
self.batch_config = batch_config
|
|
46
|
+
self.defaults = defaults
|
|
47
|
+
|
|
48
|
+
@abc.abstractmethod
|
|
49
|
+
def emit(self, record: dict):
|
|
50
|
+
raise NotImplementedError('emit')
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class AsyncQueuedHandler(BaseHandler):
|
|
54
|
+
def __init__(self, *args, **kwargs):
|
|
55
|
+
super().__init__(*args, **kwargs)
|
|
56
|
+
self._queue: asyncio.Queue = asyncio.Queue(maxsize=self.batch_config.max_queue_size)
|
|
57
|
+
self._batch: list[dict] = []
|
|
58
|
+
self._current_batch_size: int = 0
|
|
59
|
+
self._last_flush = None
|
|
60
|
+
|
|
61
|
+
self._lock: asyncio.Lock = asyncio.Lock()
|
|
62
|
+
self._stop_event: asyncio.Event = asyncio.Event()
|
|
63
|
+
self._flush_tasks: list[asyncio.Task] | None = None
|
|
64
|
+
self._flush_condition: asyncio.Condition = asyncio.Condition()
|
|
65
|
+
|
|
66
|
+
# Статистика
|
|
67
|
+
self._stats = {
|
|
68
|
+
'sent_batches': 0,
|
|
69
|
+
'failed_batches': 0,
|
|
70
|
+
'dropped_logs': 0,
|
|
71
|
+
'received_logs': 0,
|
|
72
|
+
'sent_logs': 0
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
async def emit(self, record: dict):
|
|
76
|
+
""" Добавление лога в очередь с неблокирующей проверкой """
|
|
77
|
+
self._stats['received_logs'] += 1
|
|
78
|
+
retry_count = 0
|
|
79
|
+
max_retry_count = 5
|
|
80
|
+
status = False
|
|
81
|
+
while retry_count < max_retry_count:
|
|
82
|
+
try:
|
|
83
|
+
retry_count += 1
|
|
84
|
+
await asyncio.wait_for(self._queue.put(record), timeout=self.batch_config.emit_timeout)
|
|
85
|
+
status = True
|
|
86
|
+
break
|
|
87
|
+
except (asyncio.TimeoutError, asyncio.QueueFull):
|
|
88
|
+
if self._stop_event.is_set():
|
|
89
|
+
break
|
|
90
|
+
await asyncio.sleep(0.01)
|
|
91
|
+
|
|
92
|
+
if not status:
|
|
93
|
+
self._stats['dropped_logs'] += 1
|
|
94
|
+
|
|
95
|
+
async def start(self):
|
|
96
|
+
"""Запуск обработчика"""
|
|
97
|
+
self._stop_event.clear()
|
|
98
|
+
self._flush_tasks = [
|
|
99
|
+
asyncio.create_task(self._batch_processor())
|
|
100
|
+
for _ in range(self.batch_config.num_workers)
|
|
101
|
+
]
|
|
102
|
+
|
|
103
|
+
async def stop(self, timeout: float = 30.0):
|
|
104
|
+
"""Остановка обработчика"""
|
|
105
|
+
self._stop_event.set()
|
|
106
|
+
# Ждем опустошения очереди
|
|
107
|
+
try:
|
|
108
|
+
await asyncio.wait_for(self._queue.join(), timeout=timeout)
|
|
109
|
+
except asyncio.TimeoutError:
|
|
110
|
+
pass
|
|
111
|
+
|
|
112
|
+
# Останавливаем всех воркеров
|
|
113
|
+
for task in self._flush_tasks:
|
|
114
|
+
if not task.done():
|
|
115
|
+
task.cancel()
|
|
116
|
+
|
|
117
|
+
# Ждем завершения всех воркеров
|
|
118
|
+
await asyncio.gather(*self._flush_tasks, return_exceptions=True)
|
|
119
|
+
|
|
120
|
+
async def flush(self):
|
|
121
|
+
""" Принудительная отправка всех накопленных логов """
|
|
122
|
+
if self._queue.empty():
|
|
123
|
+
return
|
|
124
|
+
|
|
125
|
+
# Ждем опустошения очереди
|
|
126
|
+
await self._queue.join()
|
|
127
|
+
|
|
128
|
+
async def get_stats(self) -> dict[str, Any]:
|
|
129
|
+
""" Получение статистики """
|
|
130
|
+
async with self._lock:
|
|
131
|
+
flush_interval_seconds = datetime.datetime.now().timestamp() - self._last_flush if self._last_flush else -1
|
|
132
|
+
return {
|
|
133
|
+
**self._stats,
|
|
134
|
+
'queue_size': self._queue.qsize(),
|
|
135
|
+
'buffer_size': len(self._batch),
|
|
136
|
+
'batch_size_bytes': self._current_batch_size,
|
|
137
|
+
'flush_interval_seconds': flush_interval_seconds,
|
|
138
|
+
'is_running': not self._stop_event.is_set()
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
async def _should_flush(self) -> bool:
|
|
142
|
+
""" Проверка, нужно ли отправить текущий батч """
|
|
143
|
+
async with self._lock:
|
|
144
|
+
if not self._batch:
|
|
145
|
+
return False
|
|
146
|
+
|
|
147
|
+
# По количеству записей
|
|
148
|
+
if len(self._batch) >= self.batch_config.buffer_size:
|
|
149
|
+
return True
|
|
150
|
+
|
|
151
|
+
# По размеру в байтах
|
|
152
|
+
if self.batch_config.max_batch_bytes and self._current_batch_size >= self.batch_config.max_batch_bytes:
|
|
153
|
+
return True
|
|
154
|
+
|
|
155
|
+
# По времени
|
|
156
|
+
if self._last_flush and datetime.datetime.now().timestamp() - self._last_flush >= self.batch_config.flush_interval_seconds:
|
|
157
|
+
return True
|
|
158
|
+
|
|
159
|
+
return False
|
|
160
|
+
|
|
161
|
+
async def _batch_processor(self):
|
|
162
|
+
"""Фоновый процесс обработки батчей"""
|
|
163
|
+
|
|
164
|
+
while not self._stop_event.is_set():
|
|
165
|
+
try:
|
|
166
|
+
# Ждем появления лога с таймаутом
|
|
167
|
+
try:
|
|
168
|
+
log_item = await asyncio.wait_for(
|
|
169
|
+
self._queue.get(),
|
|
170
|
+
timeout=self.batch_config.flush_interval_seconds
|
|
171
|
+
)
|
|
172
|
+
except asyncio.TimeoutError:
|
|
173
|
+
_is_limits = await self._should_flush()
|
|
174
|
+
if _is_limits:
|
|
175
|
+
await self._flush_batch()
|
|
176
|
+
|
|
177
|
+
continue
|
|
178
|
+
try:
|
|
179
|
+
# Добавляем лог в батч
|
|
180
|
+
async with self._lock:
|
|
181
|
+
self._batch.append(log_item)
|
|
182
|
+
self._current_batch_size += len(json.dumps(log_item))
|
|
183
|
+
|
|
184
|
+
_is_limits = await self._should_flush()
|
|
185
|
+
if _is_limits:
|
|
186
|
+
await self._flush_batch()
|
|
187
|
+
finally:
|
|
188
|
+
self._queue.task_done()
|
|
189
|
+
except Exception as ex:
|
|
190
|
+
self._stats['failed_batches'] += 1
|
|
191
|
+
await asyncio.sleep(0.1)
|
|
192
|
+
|
|
193
|
+
# Финальная отправка при остановке
|
|
194
|
+
await self._flush_batch()
|
|
195
|
+
|
|
196
|
+
async def _flush_batch(self):
|
|
197
|
+
""" Отправка батча логов """
|
|
198
|
+
async with self._lock:
|
|
199
|
+
sent_logs = 0
|
|
200
|
+
if self._batch:
|
|
201
|
+
current_batch_size = len(self._batch)
|
|
202
|
+
if current_batch_size <= self.batch_config.max_buffer_size:
|
|
203
|
+
""" Отправляем только если количество документов не превышает определенного порога """
|
|
204
|
+
await self.client.organizations.create_documents(
|
|
205
|
+
self.organization, self.folder_id, entries=self._batch, defaults=self.defaults
|
|
206
|
+
)
|
|
207
|
+
sent_logs = current_batch_size
|
|
208
|
+
|
|
209
|
+
self._batch.clear()
|
|
210
|
+
self._current_batch_size = 0
|
|
211
|
+
self._last_flush = datetime.datetime.now().timestamp()
|
|
212
|
+
if sent_logs > 0:
|
|
213
|
+
self._stats['sent_batches'] += 1
|
|
214
|
+
|
|
215
|
+
self._stats['sent_logs'] += sent_logs
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
import abc
|
|
2
|
+
import dataclasses
|
|
3
|
+
from collections.abc import Collection
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
from http_misc import http_utils, retry_policy, services, transformers
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
@dataclasses.dataclass
|
|
10
|
+
class Endpoint:
|
|
11
|
+
version: str
|
|
12
|
+
name: str
|
|
13
|
+
is_admin: bool | None = False
|
|
14
|
+
item_id: Any | None = None
|
|
15
|
+
prefix: list[str] | None = None
|
|
16
|
+
postfix: list[str] | None = None
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class AsyncBaseTransport(abc.ABC):
|
|
20
|
+
"""
|
|
21
|
+
Базовая реализация доставки
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
@abc.abstractmethod
|
|
25
|
+
async def create(self, endpoint: Endpoint, ignore_status: int | Collection[int] = None, **kwargs) -> dict:
|
|
26
|
+
raise NotImplementedError('create')
|
|
27
|
+
|
|
28
|
+
@abc.abstractmethod
|
|
29
|
+
async def update(self, endpoint: Endpoint, *, item_id: Any | None = None,
|
|
30
|
+
ignore_status: int | Collection[int] = None,
|
|
31
|
+
**kwargs) -> dict:
|
|
32
|
+
raise NotImplementedError('update')
|
|
33
|
+
|
|
34
|
+
@abc.abstractmethod
|
|
35
|
+
async def delete(self, endpoint: Endpoint, *, item_id: Any | None = None,
|
|
36
|
+
ignore_status: int | Collection[int] = None) -> None:
|
|
37
|
+
raise NotImplementedError('delete')
|
|
38
|
+
|
|
39
|
+
@abc.abstractmethod
|
|
40
|
+
async def get(self, endpoint: Endpoint, *, item_id: Any | None = None,
|
|
41
|
+
ignore_status: int | Collection[int] = None, ) -> dict:
|
|
42
|
+
raise NotImplementedError('get')
|
|
43
|
+
|
|
44
|
+
@abc.abstractmethod
|
|
45
|
+
async def filter(self, endpoint: Endpoint, ignore_status: int | Collection[int] = None, **kwargs) -> dict:
|
|
46
|
+
raise NotImplementedError('filter')
|
|
47
|
+
|
|
48
|
+
@abc.abstractmethod
|
|
49
|
+
async def close(self):
|
|
50
|
+
""" Закрытие связанных с транспортом ресурсов """
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class SetStaticAuthorization(transformers.TokenTransformer):
|
|
54
|
+
""" Указывает Basic token """
|
|
55
|
+
|
|
56
|
+
async def get_token(self, *args, **kwargs):
|
|
57
|
+
return '5c03f5957ade16a501c21fc56e97b8743630f15e0fb173276c561af32eeae8c8'
|
|
58
|
+
|
|
59
|
+
@property
|
|
60
|
+
def token_name(self):
|
|
61
|
+
return 'Bearer'
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class AsyncHttpTransport(AsyncBaseTransport):
|
|
65
|
+
"""
|
|
66
|
+
Реализация доставки с использованием REST API
|
|
67
|
+
"""
|
|
68
|
+
|
|
69
|
+
async def close(self):
|
|
70
|
+
await self.service.transport.close()
|
|
71
|
+
|
|
72
|
+
def __init__(self, base_url: str, policy: retry_policy.AsyncRetryPolicy | None = None):
|
|
73
|
+
self.base_url = base_url
|
|
74
|
+
transformer = SetStaticAuthorization()
|
|
75
|
+
self.service = services.HttpService(request_preproc=[transformer])
|
|
76
|
+
self.policy = policy or retry_policy.AsyncRetryPolicy()
|
|
77
|
+
|
|
78
|
+
async def create(self, endpoint: Endpoint, extra_cfg: dict | None = None,
|
|
79
|
+
ignore_status: int | Collection[int] = None,
|
|
80
|
+
**kwargs) -> dict:
|
|
81
|
+
""" POST Запрос """
|
|
82
|
+
url = self.endpoint_to_url(endpoint)
|
|
83
|
+
cfg = {
|
|
84
|
+
'json': kwargs
|
|
85
|
+
}
|
|
86
|
+
if extra_cfg:
|
|
87
|
+
cfg.update(extra_cfg)
|
|
88
|
+
|
|
89
|
+
request = {
|
|
90
|
+
'method': 'POST',
|
|
91
|
+
'url': url,
|
|
92
|
+
'cfg': cfg
|
|
93
|
+
}
|
|
94
|
+
return await self.send_and_validate(request, expected_status=201, ignore_status=ignore_status)
|
|
95
|
+
|
|
96
|
+
async def update(self, endpoint: Endpoint, *, item_id: Any | None = None, extra_cfg: dict | None = None,
|
|
97
|
+
ignore_status: int | Collection[int] = None, **kwargs) -> dict:
|
|
98
|
+
if item_id:
|
|
99
|
+
endpoint.item_id = item_id
|
|
100
|
+
|
|
101
|
+
url = self.endpoint_to_url(endpoint)
|
|
102
|
+
cfg = {
|
|
103
|
+
'json': kwargs
|
|
104
|
+
}
|
|
105
|
+
if extra_cfg:
|
|
106
|
+
cfg.update(extra_cfg)
|
|
107
|
+
|
|
108
|
+
request = {
|
|
109
|
+
'method': 'PUT',
|
|
110
|
+
'url': url,
|
|
111
|
+
'cfg': cfg
|
|
112
|
+
}
|
|
113
|
+
return await self.send_and_validate(request, expected_status=200, ignore_status=ignore_status)
|
|
114
|
+
|
|
115
|
+
async def delete(self, endpoint: Endpoint, *, item_id: Any | None = None,
|
|
116
|
+
ignore_status: int | Collection[int] = None) -> None:
|
|
117
|
+
if item_id:
|
|
118
|
+
endpoint.item_id = item_id
|
|
119
|
+
|
|
120
|
+
url = self.endpoint_to_url(endpoint)
|
|
121
|
+
|
|
122
|
+
request = {
|
|
123
|
+
'method': 'DELETE',
|
|
124
|
+
'url': url
|
|
125
|
+
}
|
|
126
|
+
return await self.send_and_validate(request, expected_status=204, ignore_status=ignore_status)
|
|
127
|
+
|
|
128
|
+
async def get(self, endpoint: Endpoint, *, item_id: Any | None = None,
|
|
129
|
+
ignore_status: int | Collection[int] = None) -> dict:
|
|
130
|
+
if item_id:
|
|
131
|
+
endpoint.item_id = item_id
|
|
132
|
+
|
|
133
|
+
url = self.endpoint_to_url(endpoint)
|
|
134
|
+
|
|
135
|
+
request = {
|
|
136
|
+
'method': 'GET',
|
|
137
|
+
'url': url
|
|
138
|
+
}
|
|
139
|
+
return await self.send_and_validate(request, expected_status=200, ignore_status=ignore_status)
|
|
140
|
+
|
|
141
|
+
async def filter(self, endpoint: Endpoint, ignore_status: int | Collection[int] = None, **kwargs) -> dict:
|
|
142
|
+
raise NotImplementedError()
|
|
143
|
+
|
|
144
|
+
def endpoint_to_url(self, endpoint: Endpoint) -> str:
|
|
145
|
+
""" Получение url из Endpoint """
|
|
146
|
+
if endpoint.is_admin:
|
|
147
|
+
args = [self.base_url, 'api', endpoint.version, 'admin']
|
|
148
|
+
else:
|
|
149
|
+
args = [self.base_url, 'api', endpoint.version]
|
|
150
|
+
|
|
151
|
+
if endpoint.prefix:
|
|
152
|
+
args.extend(endpoint.prefix)
|
|
153
|
+
|
|
154
|
+
args.append(endpoint.name)
|
|
155
|
+
|
|
156
|
+
if endpoint.item_id:
|
|
157
|
+
args.append(str(endpoint.item_id))
|
|
158
|
+
|
|
159
|
+
if endpoint.postfix:
|
|
160
|
+
args.extend(endpoint.postfix)
|
|
161
|
+
|
|
162
|
+
return http_utils.join_str(*args, append_last_sep=True)
|
|
163
|
+
|
|
164
|
+
async def send_and_validate(self, request, expected_status: int | None = 200,
|
|
165
|
+
ignore_status: int | Collection[int] = None):
|
|
166
|
+
""" Вызов внешнего сервиса и проверка его статуса"""
|
|
167
|
+
return await http_utils.send_and_validate(
|
|
168
|
+
self.service, request, expected_status=expected_status, ignore_status=ignore_status, policy=self.policy
|
|
169
|
+
)
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: easy-logging-py
|
|
3
|
+
Version: 1.1.5
|
|
4
|
+
Summary: Python sdk for Easy Logging
|
|
5
|
+
Author: Anton Gorinenko
|
|
6
|
+
Author-email: anton.gorinenko@gmail.com
|
|
7
|
+
Keywords: python,utils,easy logging
|
|
8
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
9
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
10
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
13
|
+
Classifier: Operating System :: OS Independent
|
|
14
|
+
Requires-Python: >=3.13
|
|
15
|
+
Description-Content-Type: text/markdown
|
|
16
|
+
License-File: LICENSE
|
|
17
|
+
Requires-Dist: http-misc[aiohttp]<4.0,>=3.0
|
|
18
|
+
Provides-Extra: test
|
|
19
|
+
Requires-Dist: pytest; extra == "test"
|
|
20
|
+
Requires-Dist: python-dotenv; extra == "test"
|
|
21
|
+
Requires-Dist: envparse; extra == "test"
|
|
22
|
+
Requires-Dist: pytest-asyncio; extra == "test"
|
|
23
|
+
Requires-Dist: pytest-mock; extra == "test"
|
|
24
|
+
Requires-Dist: pytest-env; extra == "test"
|
|
25
|
+
Dynamic: author
|
|
26
|
+
Dynamic: author-email
|
|
27
|
+
Dynamic: classifier
|
|
28
|
+
Dynamic: description
|
|
29
|
+
Dynamic: description-content-type
|
|
30
|
+
Dynamic: keywords
|
|
31
|
+
Dynamic: license-file
|
|
32
|
+
Dynamic: provides-extra
|
|
33
|
+
Dynamic: requires-dist
|
|
34
|
+
Dynamic: requires-python
|
|
35
|
+
Dynamic: summary
|
|
36
|
+
|
|
37
|
+
# Клиент Easy Logging на Python.
|
|
38
|
+
|
|
39
|
+
Библиотека утилитарных модулей для работы с распределенной системой логирования Easy Logging на Python.
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
setup.py
|
|
4
|
+
easy_logging_py/__init__.py
|
|
5
|
+
easy_logging_py/clients.py
|
|
6
|
+
easy_logging_py/handlers.py
|
|
7
|
+
easy_logging_py/transports.py
|
|
8
|
+
easy_logging_py.egg-info/PKG-INFO
|
|
9
|
+
easy_logging_py.egg-info/SOURCES.txt
|
|
10
|
+
easy_logging_py.egg-info/dependency_links.txt
|
|
11
|
+
easy_logging_py.egg-info/requires.txt
|
|
12
|
+
easy_logging_py.egg-info/top_level.txt
|
|
13
|
+
tests/test_easy_logging.py
|
|
14
|
+
tests/test_http_transport.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
easy_logging_py
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
from os.path import dirname, join
|
|
2
|
+
|
|
3
|
+
import setuptools
|
|
4
|
+
|
|
5
|
+
LONG_DESCRIPTION = """
|
|
6
|
+
# Клиент Easy Logging на Python.
|
|
7
|
+
|
|
8
|
+
Библиотека утилитарных модулей для работы с распределенной системой логирования Easy Logging на Python.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def long_description():
|
|
13
|
+
try:
|
|
14
|
+
return open(join(dirname(__file__), 'README.md')).read()
|
|
15
|
+
except IOError:
|
|
16
|
+
return LONG_DESCRIPTION
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
setuptools.setup(
|
|
20
|
+
name='easy-logging-py',
|
|
21
|
+
version='1.1.5',
|
|
22
|
+
author='Anton Gorinenko',
|
|
23
|
+
author_email='anton.gorinenko@gmail.com',
|
|
24
|
+
description='Python sdk for Easy Logging',
|
|
25
|
+
long_description=long_description(),
|
|
26
|
+
keywords='python, utils, easy logging',
|
|
27
|
+
long_description_content_type='text/markdown',
|
|
28
|
+
packages=setuptools.find_packages('.', exclude=['tests', 'django_start', 'docs']),
|
|
29
|
+
classifiers=[
|
|
30
|
+
'Programming Language :: Python :: 3.10',
|
|
31
|
+
'Programming Language :: Python :: 3.11',
|
|
32
|
+
'Programming Language :: Python :: 3.12',
|
|
33
|
+
'Programming Language :: Python :: 3.13',
|
|
34
|
+
'Programming Language :: Python :: 3.14',
|
|
35
|
+
'Operating System :: OS Independent',
|
|
36
|
+
],
|
|
37
|
+
install_requires=[
|
|
38
|
+
'http-misc[aiohttp] >= 3.0, < 4.0',
|
|
39
|
+
],
|
|
40
|
+
extras_require={
|
|
41
|
+
'test': [
|
|
42
|
+
'pytest',
|
|
43
|
+
'python-dotenv',
|
|
44
|
+
'envparse',
|
|
45
|
+
'pytest-asyncio',
|
|
46
|
+
'pytest-mock',
|
|
47
|
+
'pytest-env'
|
|
48
|
+
]
|
|
49
|
+
},
|
|
50
|
+
python_requires='>=3.13',
|
|
51
|
+
)
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import time
|
|
3
|
+
import uuid
|
|
4
|
+
from unittest.mock import ANY
|
|
5
|
+
|
|
6
|
+
import pytest
|
|
7
|
+
from http_misc import retry_policy
|
|
8
|
+
|
|
9
|
+
from easy_logging_py import transports, clients, handlers
|
|
10
|
+
from tests.conftest import BASE_HTTP_URL
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@pytest.mark.integration
|
|
14
|
+
async def test_async_logging():
|
|
15
|
+
handler = handlers.AsyncQueuedHandler(
|
|
16
|
+
organization='yar',
|
|
17
|
+
folder_id='dev',
|
|
18
|
+
client=clients.AsyncEasyLoggingClient(transport=transports.AsyncHttpTransport(
|
|
19
|
+
BASE_HTTP_URL, policy=retry_policy.AsyncRetryPolicy(max_retry=1))),
|
|
20
|
+
batch_config=handlers.LogBatchConfig(max_queue_size=50_000, buffer_size=1000, num_workers=4, emit_timeout=1.0)
|
|
21
|
+
)
|
|
22
|
+
await handler.start()
|
|
23
|
+
|
|
24
|
+
async def __send_log_message(i: int):
|
|
25
|
+
for j in range(100):
|
|
26
|
+
log_data = {
|
|
27
|
+
'streamName': 'dev-payment-service',
|
|
28
|
+
'level': 'ERROR',
|
|
29
|
+
'message': f'Возникла неожиданная ошибка {i}.{j}',
|
|
30
|
+
'requestId': f'YAR-#{uuid.uuid4()}',
|
|
31
|
+
'resource': {
|
|
32
|
+
'type': 'web-app',
|
|
33
|
+
'id': 'dev-payment-service-web'
|
|
34
|
+
},
|
|
35
|
+
'payload': {
|
|
36
|
+
'region.id': 76,
|
|
37
|
+
'region.code': 'RU-c',
|
|
38
|
+
'region.name': 'Ярославская область'
|
|
39
|
+
},
|
|
40
|
+
'timestamp': time.time() * 1000,
|
|
41
|
+
}
|
|
42
|
+
await handler.emit(log_data)
|
|
43
|
+
|
|
44
|
+
tasks = []
|
|
45
|
+
for i in range(2000):
|
|
46
|
+
tasks.append(__send_log_message(i))
|
|
47
|
+
|
|
48
|
+
await asyncio.gather(*tasks, return_exceptions=True)
|
|
49
|
+
stats = await handler.get_stats()
|
|
50
|
+
print(stats)
|
|
51
|
+
await handler.flush()
|
|
52
|
+
await handler.stop()
|
|
53
|
+
stats = await handler.get_stats()
|
|
54
|
+
|
|
55
|
+
assert stats == {
|
|
56
|
+
'sent_batches': ANY,
|
|
57
|
+
'failed_batches': 0,
|
|
58
|
+
'dropped_logs': 0,
|
|
59
|
+
'received_logs': 200000,
|
|
60
|
+
'sent_logs': ANY,
|
|
61
|
+
'queue_size': ANY,
|
|
62
|
+
'buffer_size': ANY,
|
|
63
|
+
'batch_size_bytes': ANY,
|
|
64
|
+
'flush_interval_seconds': ANY,
|
|
65
|
+
'is_running': ANY
|
|
66
|
+
}
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
import time
|
|
2
|
+
import uuid
|
|
3
|
+
from unittest.mock import ANY
|
|
4
|
+
|
|
5
|
+
import pytest
|
|
6
|
+
from http_misc import testing_utils
|
|
7
|
+
|
|
8
|
+
from tests.utils import create_organization, organization_pipeline, create_folder
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@pytest.mark.integration
|
|
12
|
+
async def test_devices_client(resources_client):
|
|
13
|
+
""" Работа с devices """
|
|
14
|
+
resource_id = 'c3c2c90daf4ecb6c77242324a59af2ef7372cb774067f2d717d9c5f236bca28b'
|
|
15
|
+
|
|
16
|
+
response_json = await resources_client.devices.create(resource_id, 'terminal.inpas')
|
|
17
|
+
device_num = response_json['deviceNum']
|
|
18
|
+
|
|
19
|
+
response_json = await resources_client.devices.get(resource_id, device_num)
|
|
20
|
+
assert response_json['extraConfig'] == None
|
|
21
|
+
|
|
22
|
+
extra_config = {
|
|
23
|
+
'additionalProp1': {'v': 1}
|
|
24
|
+
}
|
|
25
|
+
response_json = await resources_client.devices.update(resource_id, device_num, extra_config=extra_config)
|
|
26
|
+
assert response_json['extraConfig'] == extra_config
|
|
27
|
+
await resources_client.devices.delete(resource_id, device_num)
|
|
28
|
+
|
|
29
|
+
response_json = await resources_client.devices.get(resource_id, device_num, ignore_status=[404])
|
|
30
|
+
assert response_json == {'detail': f'Устройство с номером #{device_num} не найдено.'}
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@pytest.mark.integration
|
|
34
|
+
async def test_heartbeat_client(resources_client):
|
|
35
|
+
""" Работа с heartbeat """
|
|
36
|
+
resource_id = 'resource_1'
|
|
37
|
+
resource_type = 'test_agent'
|
|
38
|
+
|
|
39
|
+
response_json = await resources_client.heartbeats.push(resource_id, resource_type)
|
|
40
|
+
assert response_json == {
|
|
41
|
+
'errors': [],
|
|
42
|
+
'meta': ANY,
|
|
43
|
+
'status': True
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
response_json = await resources_client.heartbeats.shutdown(resource_id, resource_type)
|
|
47
|
+
assert response_json == {
|
|
48
|
+
'errors': [],
|
|
49
|
+
'meta': ANY,
|
|
50
|
+
'status': True
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@pytest.mark.integration
|
|
55
|
+
async def test_admin_organizations(logging_client):
|
|
56
|
+
""" Работа с организациями """
|
|
57
|
+
name = str(uuid.uuid4())
|
|
58
|
+
internal_name = f'{uuid.uuid4().hex}'[:16]
|
|
59
|
+
|
|
60
|
+
response_json = await create_organization(logging_client, name=name, internal_name=internal_name)
|
|
61
|
+
testing_utils.validate_dict_fields(response_json, (
|
|
62
|
+
('id', ANY),
|
|
63
|
+
('name', name),
|
|
64
|
+
('internalName', internal_name),
|
|
65
|
+
('createdAt', ANY),
|
|
66
|
+
('updatedAt', ANY),
|
|
67
|
+
|
|
68
|
+
))
|
|
69
|
+
item_id = response_json['id']
|
|
70
|
+
|
|
71
|
+
response_json = await logging_client.organizations.get(item_id)
|
|
72
|
+
assert 'id' in response_json
|
|
73
|
+
|
|
74
|
+
await logging_client.organizations.delete(item_id)
|
|
75
|
+
|
|
76
|
+
response_json = await logging_client.organizations.get(item_id, ignore_status=[404])
|
|
77
|
+
assert 'id' not in response_json
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
@pytest.mark.integration
|
|
81
|
+
async def test_admin_folders(logging_client):
|
|
82
|
+
""" Работа с папками """
|
|
83
|
+
async with organization_pipeline(logging_client) as organization_id:
|
|
84
|
+
name = str(uuid.uuid4())
|
|
85
|
+
folder_id = f'{uuid.uuid4().hex}'
|
|
86
|
+
description = 'description123'
|
|
87
|
+
response_json = await create_folder(logging_client, name=name, folder_id=folder_id,
|
|
88
|
+
organization_id=organization_id,
|
|
89
|
+
description=description)
|
|
90
|
+
testing_utils.validate_dict_fields(response_json, (
|
|
91
|
+
('id', ANY),
|
|
92
|
+
('name', name),
|
|
93
|
+
('folderId', folder_id),
|
|
94
|
+
('organizationId', organization_id),
|
|
95
|
+
('description', description),
|
|
96
|
+
('createdAt', ANY),
|
|
97
|
+
('updatedAt', ANY),
|
|
98
|
+
|
|
99
|
+
))
|
|
100
|
+
item_id = response_json['id']
|
|
101
|
+
|
|
102
|
+
response_json = await logging_client.folders.get(item_id)
|
|
103
|
+
assert 'id' in response_json
|
|
104
|
+
|
|
105
|
+
await logging_client.folders.delete(item_id)
|
|
106
|
+
|
|
107
|
+
response_json = await logging_client.folders.get(item_id, ignore_status=[404])
|
|
108
|
+
assert 'id' not in response_json
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
@pytest.mark.integration
|
|
112
|
+
async def test_create_documents(logging_client):
|
|
113
|
+
""" Запись логов """
|
|
114
|
+
organization_internal_name = 'yar'
|
|
115
|
+
folder_id = 'dev'
|
|
116
|
+
request_id_1 = f'YAR-#{uuid.uuid4()}'
|
|
117
|
+
request_id_2 = f'RQST#{uuid.uuid4()}'
|
|
118
|
+
defaults = {
|
|
119
|
+
'streamName': 'dev-payment-service',
|
|
120
|
+
'level': 'INFO',
|
|
121
|
+
'requestId': request_id_2,
|
|
122
|
+
'payload': {
|
|
123
|
+
'region': 'Воронежская область'
|
|
124
|
+
},
|
|
125
|
+
'resource': {
|
|
126
|
+
'type': 'python-agent',
|
|
127
|
+
'id': 'agent01'
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
entries = [
|
|
131
|
+
{
|
|
132
|
+
'streamName': 'dev-payment-service',
|
|
133
|
+
'level': 'ERROR',
|
|
134
|
+
'message': 'Возникла неожиданная ошибка',
|
|
135
|
+
'requestId': request_id_1,
|
|
136
|
+
'resource': {
|
|
137
|
+
'type': 'web-app',
|
|
138
|
+
'id': 'dev-payment-service-web'
|
|
139
|
+
},
|
|
140
|
+
'payload': {
|
|
141
|
+
'region.id': 76,
|
|
142
|
+
'region.code': 'RU-c',
|
|
143
|
+
'region.name': 'Ярославская область'
|
|
144
|
+
},
|
|
145
|
+
'timestamp': time.time() * 1000,
|
|
146
|
+
},
|
|
147
|
+
{
|
|
148
|
+
'message': 'У пользователя отсутствует профиль',
|
|
149
|
+
'timestamp': time.time() * 1000,
|
|
150
|
+
}
|
|
151
|
+
]
|
|
152
|
+
response_json = await logging_client.organizations.create_documents(organization_internal_name, folder_id,
|
|
153
|
+
entries=entries, defaults=defaults)
|
|
154
|
+
assert response_json == {'errors': [], 'status': True}
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
@pytest.mark.integration
|
|
158
|
+
async def test_propagate_folder(logging_client):
|
|
159
|
+
""" Запись логов """
|
|
160
|
+
organization_internal_name = 'yar'
|
|
161
|
+
folder_id = 'dev'
|
|
162
|
+
response_json = await logging_client.propagate_folder(organization_internal_name, folder_id)
|
|
163
|
+
assert response_json == {'errors': [], 'status': True}
|