unitlog 0.0.1__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.
- unitlog-0.0.1/LICENSE +201 -0
- unitlog-0.0.1/PKG-INFO +11 -0
- unitlog-0.0.1/README.md +0 -0
- unitlog-0.0.1/setup.cfg +4 -0
- unitlog-0.0.1/setup.py +69 -0
- unitlog-0.0.1/unitlog/__init__.py +1 -0
- unitlog-0.0.1/unitlog/handlers.py +64 -0
- unitlog-0.0.1/unitlog/unit.py +133 -0
- unitlog-0.0.1/unitlog/util_log.py +166 -0
- unitlog-0.0.1/unitlog.egg-info/PKG-INFO +11 -0
- unitlog-0.0.1/unitlog.egg-info/SOURCES.txt +11 -0
- unitlog-0.0.1/unitlog.egg-info/dependency_links.txt +1 -0
- unitlog-0.0.1/unitlog.egg-info/top_level.txt +1 -0
unitlog-0.0.1/LICENSE
ADDED
|
@@ -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.
|
unitlog-0.0.1/PKG-INFO
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: unitlog
|
|
3
|
+
Version: 0.0.1
|
|
4
|
+
Home-page: https://github.com/yujun2647/unitlog
|
|
5
|
+
Download-URL:
|
|
6
|
+
Author: walkerjun
|
|
7
|
+
Author-email: yujun2647@163.com
|
|
8
|
+
License: Apache-2.0
|
|
9
|
+
Requires-Python: >=3.6
|
|
10
|
+
Description-Content-Type: text/markdown
|
|
11
|
+
License-File: LICENSE
|
unitlog-0.0.1/README.md
ADDED
|
File without changes
|
unitlog-0.0.1/setup.cfg
ADDED
unitlog-0.0.1/setup.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
#!/usr/bin/env python
|
|
2
|
+
import os
|
|
3
|
+
|
|
4
|
+
from setuptools import setup
|
|
5
|
+
from unitlog import __version__
|
|
6
|
+
|
|
7
|
+
with open("README.md", "r") as fp:
|
|
8
|
+
README = fp.read()
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _get_requires(filename):
|
|
12
|
+
with open(filename, "r") as fp:
|
|
13
|
+
lines = fp.readlines()
|
|
14
|
+
return [l.replace("\n", "") for l in lines
|
|
15
|
+
if not l.startswith("#") and not l.startswith("-")]
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def walk_package(package):
|
|
19
|
+
packages = []
|
|
20
|
+
package_data = {}
|
|
21
|
+
for name, folders, files in os.walk(package):
|
|
22
|
+
folders = [f for f in folders if not f.startswith("__")]
|
|
23
|
+
files = [f for f in files if not f.endswith(".pyc")]
|
|
24
|
+
if "__init__.py" in files:
|
|
25
|
+
packages.append(name)
|
|
26
|
+
for folder in folders:
|
|
27
|
+
sub_name = os.path.join(name, folder)
|
|
28
|
+
_packages, _package_data = walk_package(sub_name)
|
|
29
|
+
packages.extend(_packages)
|
|
30
|
+
for name, values in _package_data.items():
|
|
31
|
+
if name in package_data:
|
|
32
|
+
package_data[name].extend(values)
|
|
33
|
+
else:
|
|
34
|
+
package_data[name] = values
|
|
35
|
+
else:
|
|
36
|
+
items = name.split("/")
|
|
37
|
+
top_name = items[0]
|
|
38
|
+
rest_header = "/".join(items[1:])
|
|
39
|
+
if folders or files:
|
|
40
|
+
package_data.setdefault(top_name, [])
|
|
41
|
+
for folder in folders:
|
|
42
|
+
data = (f"{rest_header}/{folder}/*" if rest_header
|
|
43
|
+
else f"{folder}/*")
|
|
44
|
+
package_data[top_name].append(data)
|
|
45
|
+
for file in files:
|
|
46
|
+
data = (f"{rest_header}/{file}" if rest_header
|
|
47
|
+
else file)
|
|
48
|
+
package_data[top_name].append(data)
|
|
49
|
+
return packages, package_data
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
all_packages, all_package_data = walk_package("unitlog")
|
|
53
|
+
|
|
54
|
+
setup(
|
|
55
|
+
name="unitlog",
|
|
56
|
+
version=__version__,
|
|
57
|
+
description="",
|
|
58
|
+
python_requires=">=3.6",
|
|
59
|
+
install_requires=[],
|
|
60
|
+
url="https://github.com/yujun2647/unitlog",
|
|
61
|
+
license='Apache-2.0',
|
|
62
|
+
author="walkerjun",
|
|
63
|
+
author_email="yujun2647@163.com",
|
|
64
|
+
download_url="",
|
|
65
|
+
packages=all_packages,
|
|
66
|
+
package_data=all_package_data,
|
|
67
|
+
long_description=README,
|
|
68
|
+
long_description_content_type='text/markdown'
|
|
69
|
+
)
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.0.1"
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
import multiprocessing as mp
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class LogBox(object):
|
|
6
|
+
def __init__(self, log_msg, log_type="console",
|
|
7
|
+
log_filepath="", file_mode="a"):
|
|
8
|
+
self.log_msg = log_msg
|
|
9
|
+
self.log_type = log_type
|
|
10
|
+
self.log_filepath = log_filepath
|
|
11
|
+
self.file_mode = file_mode
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class UnitHandler(logging.StreamHandler):
|
|
15
|
+
LOG_TYPE = "console"
|
|
16
|
+
DEFAULT_LOG_QUEUE = mp.Queue()
|
|
17
|
+
|
|
18
|
+
def handle(self, record):
|
|
19
|
+
""" without acquiring lock
|
|
20
|
+
"""
|
|
21
|
+
rv = self.filter(record)
|
|
22
|
+
if rv:
|
|
23
|
+
self.emit(record)
|
|
24
|
+
# self.acquire()
|
|
25
|
+
# try:
|
|
26
|
+
# self.emit(record)
|
|
27
|
+
# finally:
|
|
28
|
+
# self.release()
|
|
29
|
+
return rv
|
|
30
|
+
|
|
31
|
+
def wrap_msg(self, log_msg) -> LogBox:
|
|
32
|
+
return LogBox(log_msg=log_msg, log_type=self.LOG_TYPE)
|
|
33
|
+
|
|
34
|
+
def emit(self, record):
|
|
35
|
+
""" send to queue
|
|
36
|
+
"""
|
|
37
|
+
# noinspection PyBroadException
|
|
38
|
+
try:
|
|
39
|
+
msg = self.format(record)
|
|
40
|
+
# issue 35046: merged two stream.writes into one.
|
|
41
|
+
log_msg = msg + self.terminator
|
|
42
|
+
UnitHandler.DEFAULT_LOG_QUEUE.put(self.wrap_msg(log_msg))
|
|
43
|
+
except RecursionError: # See issue 36272
|
|
44
|
+
raise
|
|
45
|
+
except Exception:
|
|
46
|
+
self.handleError(record)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class UnitConsoleHandler(UnitHandler):
|
|
50
|
+
LOG_TYPE = "console"
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class UnitFileHandler(UnitHandler):
|
|
54
|
+
LOG_TYPE = "file"
|
|
55
|
+
|
|
56
|
+
def __init__(self, log_filepath, mode):
|
|
57
|
+
super().__init__()
|
|
58
|
+
self.log_filepath = log_filepath
|
|
59
|
+
self.mode = mode
|
|
60
|
+
|
|
61
|
+
def wrap_msg(self, log_msg) -> LogBox:
|
|
62
|
+
return LogBox(log_msg=log_msg, log_type=self.LOG_TYPE,
|
|
63
|
+
log_filepath=self.log_filepath,
|
|
64
|
+
file_mode=self.mode)
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import sys
|
|
3
|
+
import atexit
|
|
4
|
+
import logging
|
|
5
|
+
import traceback
|
|
6
|
+
from queue import Empty
|
|
7
|
+
import multiprocessing as mp
|
|
8
|
+
from multiprocessing.synchronize import Event
|
|
9
|
+
|
|
10
|
+
from unitlog.handlers import (LogBox, UnitHandler, UnitFileHandler,
|
|
11
|
+
UnitConsoleHandler)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class PoxyConsoleLogWriter(object):
|
|
15
|
+
|
|
16
|
+
def __init__(self, stream=sys.stdout):
|
|
17
|
+
self.stream = stream
|
|
18
|
+
|
|
19
|
+
def emit(self, log_msg):
|
|
20
|
+
self.stream.write(log_msg)
|
|
21
|
+
self.stream.flush()
|
|
22
|
+
|
|
23
|
+
def close(self):
|
|
24
|
+
self.stream.close()
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class PoxyFileLogWriter(PoxyConsoleLogWriter):
|
|
28
|
+
def __init__(self, log_filepath, file_mode="a"):
|
|
29
|
+
super().__init__(stream=open(log_filepath, file_mode))
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class UnitLog(object):
|
|
33
|
+
|
|
34
|
+
def __init__(self):
|
|
35
|
+
self.started: Event = mp.Event()
|
|
36
|
+
self.stopped: Event = mp.Event()
|
|
37
|
+
self.log_num = mp.Value('i', 0)
|
|
38
|
+
self.worker = mp.Process(target=self.listening_log_msg, daemon=False)
|
|
39
|
+
self._proxy_handler_map = {}
|
|
40
|
+
|
|
41
|
+
def _init_proxy_handler(self, log_box: LogBox) -> PoxyConsoleLogWriter:
|
|
42
|
+
hkey = f"{log_box.log_type}-{log_box.log_filepath}"
|
|
43
|
+
if hkey not in self._proxy_handler_map:
|
|
44
|
+
if log_box.log_type == "console":
|
|
45
|
+
self._proxy_handler_map[hkey] = PoxyConsoleLogWriter()
|
|
46
|
+
elif log_box.log_type == "file":
|
|
47
|
+
abs_log_filepath = os.path.abspath(log_box.log_filepath)
|
|
48
|
+
dir_path = os.path.dirname(abs_log_filepath)
|
|
49
|
+
if not os.path.exists(dir_path):
|
|
50
|
+
os.makedirs(dir_path, exist_ok=True)
|
|
51
|
+
|
|
52
|
+
self._proxy_handler_map[hkey] = PoxyFileLogWriter(
|
|
53
|
+
log_filepath=abs_log_filepath,
|
|
54
|
+
file_mode=log_box.file_mode
|
|
55
|
+
)
|
|
56
|
+
else:
|
|
57
|
+
raise TypeError(f"Unsupported log type: {log_box.log_type}")
|
|
58
|
+
return self._proxy_handler_map[hkey]
|
|
59
|
+
|
|
60
|
+
def listening_log_msg(self):
|
|
61
|
+
while True:
|
|
62
|
+
self.started.set()
|
|
63
|
+
try:
|
|
64
|
+
log_box: LogBox = UnitHandler.DEFAULT_LOG_QUEUE.get(timeout=0.1)
|
|
65
|
+
except Empty:
|
|
66
|
+
if self.stopped.is_set():
|
|
67
|
+
break
|
|
68
|
+
continue
|
|
69
|
+
try:
|
|
70
|
+
handler = self._init_proxy_handler(log_box)
|
|
71
|
+
|
|
72
|
+
handler.emit(log_box.log_msg)
|
|
73
|
+
if os.environ.get("ENV-TEST", "prod") == "test":
|
|
74
|
+
self.log_num.value += 1
|
|
75
|
+
except Exception as e:
|
|
76
|
+
print(f"unexpect exception: {e}\n "
|
|
77
|
+
f"{traceback.format_exc()}")
|
|
78
|
+
if os.environ.get("ENV-TEST", "prod") == "test":
|
|
79
|
+
print(f"all log num: {self.log_num.value}")
|
|
80
|
+
|
|
81
|
+
def register_logger(self, name, level=logging.INFO,
|
|
82
|
+
console_log=True, file_log=False, file_log_mode="a",
|
|
83
|
+
log_filepath=None,
|
|
84
|
+
parent_logger_name=None) -> logging.Logger:
|
|
85
|
+
if not self.started.is_set():
|
|
86
|
+
self.worker.start()
|
|
87
|
+
if not self.started.wait(timeout=3):
|
|
88
|
+
raise ValueError("unit log process is not started")
|
|
89
|
+
|
|
90
|
+
logger = logging.getLogger(name)
|
|
91
|
+
logger.setLevel(level)
|
|
92
|
+
if parent_logger_name is not None:
|
|
93
|
+
parent_logger = logging.getLogger(parent_logger_name)
|
|
94
|
+
logger.parent = parent_logger
|
|
95
|
+
logger.propagate = True
|
|
96
|
+
else:
|
|
97
|
+
logger.propagate = False
|
|
98
|
+
|
|
99
|
+
simple_formatter = logging.Formatter(
|
|
100
|
+
fmt="%(asctime)s [line:%(lineno)d] %(levelname)s %(message)s",
|
|
101
|
+
datefmt="%a, %d %b %Y %H:%M:%S"
|
|
102
|
+
)
|
|
103
|
+
full_formatter = logging.Formatter(
|
|
104
|
+
fmt="%(asctime)s %(filename)s [line:%(lineno)d] %(levelname)s "
|
|
105
|
+
"%(message)s",
|
|
106
|
+
datefmt="%a, %d %b %Y %H:%M:%S"
|
|
107
|
+
)
|
|
108
|
+
if console_log:
|
|
109
|
+
console_handler = UnitConsoleHandler()
|
|
110
|
+
console_handler.setFormatter(simple_formatter)
|
|
111
|
+
logger.handlers.append(console_handler)
|
|
112
|
+
if file_log:
|
|
113
|
+
assert log_filepath, "log_filepath must be set"
|
|
114
|
+
file_handler = UnitFileHandler(log_filepath, mode=file_log_mode)
|
|
115
|
+
file_handler.setFormatter(full_formatter)
|
|
116
|
+
logger.handlers.append(file_handler)
|
|
117
|
+
logger.info("\nLog_filename: {}".format(log_filepath))
|
|
118
|
+
|
|
119
|
+
return logger
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
DEFAULT_LOG = UnitLog()
|
|
123
|
+
|
|
124
|
+
register_logger = DEFAULT_LOG.register_logger
|
|
125
|
+
atexit.register(lambda: DEFAULT_LOG.stopped.set())
|
|
126
|
+
|
|
127
|
+
if __name__ == "__main__":
|
|
128
|
+
import time
|
|
129
|
+
|
|
130
|
+
_logger = logging.getLogger("test")
|
|
131
|
+
register_logger(name="test", level=logging.DEBUG,
|
|
132
|
+
log_filepath="./temp/test.log")
|
|
133
|
+
_logger.info("lllll")
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import sys
|
|
3
|
+
import json
|
|
4
|
+
import time
|
|
5
|
+
import logging
|
|
6
|
+
import functools
|
|
7
|
+
import threading
|
|
8
|
+
|
|
9
|
+
LOG_LEVEL_METHOD_MAP = {
|
|
10
|
+
logging.INFO: logging.info,
|
|
11
|
+
logging.DEBUG: logging.debug,
|
|
12
|
+
logging.WARNING: logging.warning,
|
|
13
|
+
logging.ERROR: logging.ERROR
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def get_log_cost_msg(cost_second):
|
|
18
|
+
msg = "{cost_num} {unit}"
|
|
19
|
+
if cost_second < 1:
|
|
20
|
+
cost_num = cost_second * 1000
|
|
21
|
+
unit = "ms"
|
|
22
|
+
elif cost_second < 60:
|
|
23
|
+
cost_num = cost_second
|
|
24
|
+
unit = "second"
|
|
25
|
+
elif cost_second < 3600:
|
|
26
|
+
cost_num = cost_second / 60
|
|
27
|
+
unit = "min"
|
|
28
|
+
else:
|
|
29
|
+
cost_num = cost_second / 3600
|
|
30
|
+
unit = "hours"
|
|
31
|
+
return msg.format(cost_num=round(cost_num, 2), unit=unit)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def log_func_cost(start, func_obj, desc=None, insert_extra=True,
|
|
35
|
+
extra_key="time_cost", log_method=logging.debug, min_cost=1):
|
|
36
|
+
cost = time.time() - start
|
|
37
|
+
if cost * 1000 < min_cost:
|
|
38
|
+
return
|
|
39
|
+
|
|
40
|
+
desc = f"[{desc}]" if desc else ""
|
|
41
|
+
# 日志统计使用 毫秒
|
|
42
|
+
extra = {extra_key: cost * 1000} if insert_extra else {}
|
|
43
|
+
# src_filepath, src_lines, line_no = get_source_info(func_obj)
|
|
44
|
+
# line_no += 1
|
|
45
|
+
# src_filename = os.path.basename(src_filepath)
|
|
46
|
+
func_name = func_obj.__name__
|
|
47
|
+
log_msg = (f"【FUNC TIME COST】: {desc} "
|
|
48
|
+
f"{func_name}(**) cost {get_log_cost_msg(cost)}")
|
|
49
|
+
if log_method in (logging.info, logging.debug, logging.error,
|
|
50
|
+
logging.warning):
|
|
51
|
+
log_method(log_msg, extra=extra)
|
|
52
|
+
else:
|
|
53
|
+
log_method(log_msg)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def time_cost_log(func):
|
|
57
|
+
# 打印各个函数执行时间,用于优化代码
|
|
58
|
+
@functools.wraps(func)
|
|
59
|
+
def wrapper(*args, **kwargs):
|
|
60
|
+
start = time.time()
|
|
61
|
+
try:
|
|
62
|
+
result = func(*args, **kwargs)
|
|
63
|
+
log_func_cost(start, func, insert_extra=True)
|
|
64
|
+
except Exception as exp:
|
|
65
|
+
log_func_cost(start, func)
|
|
66
|
+
raise exp
|
|
67
|
+
return result
|
|
68
|
+
|
|
69
|
+
return wrapper
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def time_cost_log_with_desc(desc="", insert_extra=True, extra_key="time_cost",
|
|
73
|
+
log_method=logging.debug, min_cost=1):
|
|
74
|
+
"""
|
|
75
|
+
:param: desc
|
|
76
|
+
:param: insert_extra 是否注入进 extra, 默认开启,会往 record 中注入耗时信息
|
|
77
|
+
:param: extra_key
|
|
78
|
+
"""
|
|
79
|
+
|
|
80
|
+
def outer_wrapper(func):
|
|
81
|
+
# 打印各个函数执行时间,用于优化代码
|
|
82
|
+
@functools.wraps(func)
|
|
83
|
+
def inner_wrapper(*args, **kwargs):
|
|
84
|
+
start = time.time()
|
|
85
|
+
try:
|
|
86
|
+
result = func(*args, **kwargs)
|
|
87
|
+
log_func_cost(start, func, desc=desc,
|
|
88
|
+
insert_extra=insert_extra, extra_key=extra_key,
|
|
89
|
+
log_method=log_method, min_cost=min_cost)
|
|
90
|
+
except Exception as exp:
|
|
91
|
+
log_func_cost(start, func, desc=desc)
|
|
92
|
+
raise exp
|
|
93
|
+
return result
|
|
94
|
+
|
|
95
|
+
return inner_wrapper
|
|
96
|
+
|
|
97
|
+
return outer_wrapper
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def set_scripts_logging(_file_, level=logging.DEBUG):
|
|
101
|
+
"""
|
|
102
|
+
为了是脚本log安装正确,请把此函数的调用放在脚本的最上面, 例:
|
|
103
|
+
from commons import set_scripts_logging
|
|
104
|
+
set_scripts_logging(__file__)
|
|
105
|
+
|
|
106
|
+
import logging
|
|
107
|
+
import ..others..
|
|
108
|
+
|
|
109
|
+
@_file_:
|
|
110
|
+
@level:
|
|
111
|
+
@return:
|
|
112
|
+
"""
|
|
113
|
+
log_filename = "./test.log"
|
|
114
|
+
root_logger = logging.getLogger()
|
|
115
|
+
# 解除第三方 logger 广播日志
|
|
116
|
+
for logger_name, logger in root_logger.manager.loggerDict.items():
|
|
117
|
+
if (isinstance(logger, logging.Logger)
|
|
118
|
+
and logger_name != root_logger.name
|
|
119
|
+
and logger.parent.name == root_logger.name):
|
|
120
|
+
logger.propagate = False
|
|
121
|
+
if root_logger.handlers: # 防止有多个 handler
|
|
122
|
+
root_logger.handlers.clear()
|
|
123
|
+
|
|
124
|
+
logging.basicConfig(level=level,
|
|
125
|
+
format=("%(asctime)s %(filename)s "
|
|
126
|
+
"[line:%(lineno)d] %(levelname)s %(message)s"),
|
|
127
|
+
datefmt="%a, %d %b %Y %H:%M:%S",
|
|
128
|
+
filename=log_filename)
|
|
129
|
+
console_handler = logging.StreamHandler(sys.stdout)
|
|
130
|
+
console_handler.setFormatter(
|
|
131
|
+
logging.Formatter("%(asctime)s [line:%(lineno)d] %(levelname)s "
|
|
132
|
+
"%(message)s"))
|
|
133
|
+
console_handler.setLevel(level=level)
|
|
134
|
+
root_logger.addHandler(console_handler)
|
|
135
|
+
root_logger.setLevel(level=level)
|
|
136
|
+
logging.info("\nLog_filename: {}".format(log_filename))
|
|
137
|
+
return log_filename
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
@time_cost_log_with_desc(desc="test")
|
|
141
|
+
def cost_test():
|
|
142
|
+
time.sleep(1.2)
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def log_thread_msg(func):
|
|
146
|
+
# 打印各个函数执行时间,用于优化代码
|
|
147
|
+
@functools.wraps(func)
|
|
148
|
+
def wrapper(*args, **kwargs):
|
|
149
|
+
try:
|
|
150
|
+
thread_id = threading.get_ident()
|
|
151
|
+
thread_name = threading.current_thread().name
|
|
152
|
+
logging.debug(f"[thread log] def {func.__name__} "
|
|
153
|
+
f"thread_id: {thread_id} "
|
|
154
|
+
f"thread_name: {thread_name}")
|
|
155
|
+
result = func(*args, **kwargs)
|
|
156
|
+
except Exception as exp:
|
|
157
|
+
raise exp
|
|
158
|
+
return result
|
|
159
|
+
|
|
160
|
+
return wrapper
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
if __name__ == "__main__":
|
|
165
|
+
set_scripts_logging(__file__)
|
|
166
|
+
logging.info("llll")
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: unitlog
|
|
3
|
+
Version: 0.0.1
|
|
4
|
+
Home-page: https://github.com/yujun2647/unitlog
|
|
5
|
+
Download-URL:
|
|
6
|
+
Author: walkerjun
|
|
7
|
+
Author-email: yujun2647@163.com
|
|
8
|
+
License: Apache-2.0
|
|
9
|
+
Requires-Python: >=3.6
|
|
10
|
+
Description-Content-Type: text/markdown
|
|
11
|
+
License-File: LICENSE
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
unitlog
|