crawlo 1.3.4__py3-none-any.whl → 1.3.5__py3-none-any.whl
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.
Potentially problematic release.
This version of crawlo might be problematic. Click here for more details.
- crawlo/__version__.py +1 -1
- crawlo/pipelines/mysql_pipeline.py +7 -0
- crawlo/templates/run.py.tmpl +2 -2
- crawlo/utils/log.py +42 -6
- {crawlo-1.3.4.dist-info → crawlo-1.3.5.dist-info}/METADATA +1 -1
- {crawlo-1.3.4.dist-info → crawlo-1.3.5.dist-info}/RECORD +19 -9
- tests/debug_log_config.py +127 -0
- tests/detailed_log_test.py +234 -0
- tests/final_log_test.py +261 -0
- tests/fix_log_test.py +143 -0
- tests/log_buffering_test.py +112 -0
- tests/log_generation_timing_test.py +154 -0
- tests/simple_log_test2.py +138 -0
- tests/spider_log_timing_test.py +178 -0
- tests/test_get_component_logger.py +84 -0
- tests/test_logging_system.py +283 -0
- {crawlo-1.3.4.dist-info → crawlo-1.3.5.dist-info}/WHEEL +0 -0
- {crawlo-1.3.4.dist-info → crawlo-1.3.5.dist-info}/entry_points.txt +0 -0
- {crawlo-1.3.4.dist-info → crawlo-1.3.5.dist-info}/top_level.txt +0 -0
tests/final_log_test.py
ADDED
|
@@ -0,0 +1,261 @@
|
|
|
1
|
+
#!/usr/bin/env python
|
|
2
|
+
# -*- coding: UTF-8 -*-
|
|
3
|
+
"""
|
|
4
|
+
最终日志系统功能验证测试
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import os
|
|
8
|
+
import sys
|
|
9
|
+
import tempfile
|
|
10
|
+
import shutil
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
# 添加项目根目录到Python路径
|
|
14
|
+
project_root = Path(__file__).parent.parent
|
|
15
|
+
sys.path.insert(0, str(project_root))
|
|
16
|
+
|
|
17
|
+
from crawlo.logging import configure_logging as configure, get_logger, LogManager
|
|
18
|
+
from crawlo.logging.config import LogConfig
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def test_complete_log_functionality():
|
|
22
|
+
"""测试完整的日志功能"""
|
|
23
|
+
print("=== 测试完整的日志功能 ===")
|
|
24
|
+
|
|
25
|
+
# 创建临时目录
|
|
26
|
+
temp_dir = tempfile.mkdtemp()
|
|
27
|
+
log_file = os.path.join(temp_dir, 'complete_test.log')
|
|
28
|
+
|
|
29
|
+
try:
|
|
30
|
+
print(f"日志文件路径: {log_file}")
|
|
31
|
+
|
|
32
|
+
# 1. 测试完整的日志配置
|
|
33
|
+
print("1. 测试完整的日志配置...")
|
|
34
|
+
LogManager().reset()
|
|
35
|
+
|
|
36
|
+
# 使用正确的参数名
|
|
37
|
+
config = configure(
|
|
38
|
+
LOG_LEVEL='DEBUG',
|
|
39
|
+
LOG_FILE=log_file,
|
|
40
|
+
LOG_MAX_BYTES=2048, # 小的轮转大小用于测试
|
|
41
|
+
LOG_BACKUP_COUNT=2,
|
|
42
|
+
LOG_CONSOLE_ENABLED=True,
|
|
43
|
+
LOG_FILE_ENABLED=True,
|
|
44
|
+
LOG_ENCODING='utf-8'
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
current_config = LogManager().config
|
|
48
|
+
print(f" 配置级别: {current_config.level}")
|
|
49
|
+
print(f" 配置文件路径: {current_config.file_path}")
|
|
50
|
+
print(f" 轮转大小: {current_config.max_bytes}")
|
|
51
|
+
print(f" 备份数量: {current_config.backup_count}")
|
|
52
|
+
print(f" 控制台启用: {current_config.console_enabled}")
|
|
53
|
+
print(f" 文件启用: {current_config.file_enabled}")
|
|
54
|
+
print(f" 编码: {current_config.encoding}")
|
|
55
|
+
|
|
56
|
+
# 2. 测试Logger创建
|
|
57
|
+
print("2. 测试Logger创建...")
|
|
58
|
+
logger = get_logger('test.complete')
|
|
59
|
+
print(f" Logger名称: {logger.name}")
|
|
60
|
+
print(f" Handlers数量: {len(logger.handlers)}")
|
|
61
|
+
|
|
62
|
+
file_handler_found = False
|
|
63
|
+
console_handler_found = False
|
|
64
|
+
|
|
65
|
+
for handler in logger.handlers:
|
|
66
|
+
handler_type = type(handler).__name__
|
|
67
|
+
print(f" Handler类型: {handler_type}")
|
|
68
|
+
if 'FileHandler' in handler_type:
|
|
69
|
+
file_handler_found = True
|
|
70
|
+
if hasattr(handler, 'baseFilename'):
|
|
71
|
+
print(f" 文件路径: {handler.baseFilename}")
|
|
72
|
+
elif 'StreamHandler' in handler_type:
|
|
73
|
+
console_handler_found = True
|
|
74
|
+
|
|
75
|
+
print(f" 文件处理器找到: {file_handler_found}")
|
|
76
|
+
print(f" 控制台处理器找到: {console_handler_found}")
|
|
77
|
+
|
|
78
|
+
# 3. 测试日志输出
|
|
79
|
+
print("3. 测试日志输出...")
|
|
80
|
+
logger.debug("这是一条DEBUG消息")
|
|
81
|
+
logger.info("这是一条INFO消息")
|
|
82
|
+
logger.warning("这是一条WARNING消息")
|
|
83
|
+
logger.error("这是一条ERROR消息")
|
|
84
|
+
logger.critical("这是一条CRITICAL消息")
|
|
85
|
+
|
|
86
|
+
# 4. 测试日志轮转
|
|
87
|
+
print("4. 测试日志轮转...")
|
|
88
|
+
for i in range(20):
|
|
89
|
+
logger.info(f"测试轮转消息 {i+1} - 这是一条比较长的消息,用于快速达到轮转大小限制")
|
|
90
|
+
|
|
91
|
+
# 5. 检查日志文件
|
|
92
|
+
print("5. 检查日志文件...")
|
|
93
|
+
if os.path.exists(log_file):
|
|
94
|
+
file_size = os.path.getsize(log_file)
|
|
95
|
+
print(f" 主日志文件大小: {file_size} 字节")
|
|
96
|
+
|
|
97
|
+
with open(log_file, 'r', encoding='utf-8') as f:
|
|
98
|
+
lines = f.readlines()
|
|
99
|
+
print(f" 主日志文件行数: {len(lines)}")
|
|
100
|
+
if lines:
|
|
101
|
+
print(f" 最后几行: {''.join(lines[-3:])}")
|
|
102
|
+
else:
|
|
103
|
+
print(" 主日志文件不存在!")
|
|
104
|
+
|
|
105
|
+
# 检查备份文件
|
|
106
|
+
for i in range(1, 3):
|
|
107
|
+
backup_file = f"{log_file}.{i}"
|
|
108
|
+
if os.path.exists(backup_file):
|
|
109
|
+
backup_size = os.path.getsize(backup_file)
|
|
110
|
+
print(f" 备份文件 {i} 大小: {backup_size} 字节")
|
|
111
|
+
else:
|
|
112
|
+
print(f" 备份文件 {i} 不存在")
|
|
113
|
+
|
|
114
|
+
finally:
|
|
115
|
+
# 清理
|
|
116
|
+
shutil.rmtree(temp_dir, ignore_errors=True)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def test_module_specific_logging():
|
|
120
|
+
"""测试模块特定的日志配置"""
|
|
121
|
+
print("\n=== 测试模块特定的日志配置 ===")
|
|
122
|
+
|
|
123
|
+
# 1. 配置模块级别
|
|
124
|
+
print("1. 配置模块级别...")
|
|
125
|
+
LogManager().reset()
|
|
126
|
+
configure(
|
|
127
|
+
LOG_LEVEL='WARNING',
|
|
128
|
+
LOG_LEVELS={
|
|
129
|
+
'module.debug': 'DEBUG',
|
|
130
|
+
'module.info': 'INFO',
|
|
131
|
+
'module.error': 'ERROR'
|
|
132
|
+
}
|
|
133
|
+
)
|
|
134
|
+
|
|
135
|
+
current_config = LogManager().config
|
|
136
|
+
print(f" 默认级别: {current_config.level}")
|
|
137
|
+
print(f" 模块级别: {current_config.module_levels}")
|
|
138
|
+
|
|
139
|
+
# 2. 测试不同模块的日志级别
|
|
140
|
+
print("2. 测试不同模块的日志级别...")
|
|
141
|
+
|
|
142
|
+
# DEBUG模块(应该显示所有级别)
|
|
143
|
+
debug_logger = get_logger('module.debug')
|
|
144
|
+
print(f" DEBUG模块级别: {debug_logger.handlers[0].level}")
|
|
145
|
+
debug_logger.debug("DEBUG模块 - DEBUG消息")
|
|
146
|
+
debug_logger.info("DEBUG模块 - INFO消息")
|
|
147
|
+
debug_logger.warning("DEBUG模块 - WARNING消息")
|
|
148
|
+
debug_logger.error("DEBUG模块 - ERROR消息")
|
|
149
|
+
|
|
150
|
+
# INFO模块(应该显示INFO及以上)
|
|
151
|
+
info_logger = get_logger('module.info')
|
|
152
|
+
print(f" INFO模块级别: {info_logger.handlers[0].level}")
|
|
153
|
+
info_logger.debug("INFO模块 - DEBUG消息(不应该显示)")
|
|
154
|
+
info_logger.info("INFO模块 - INFO消息")
|
|
155
|
+
info_logger.warning("INFO模块 - WARNING消息")
|
|
156
|
+
info_logger.error("INFO模块 - ERROR消息")
|
|
157
|
+
|
|
158
|
+
# ERROR模块(应该只显示ERROR及以上)
|
|
159
|
+
error_logger = get_logger('module.error')
|
|
160
|
+
print(f" ERROR模块级别: {error_logger.handlers[0].level}")
|
|
161
|
+
error_logger.debug("ERROR模块 - DEBUG消息(不应该显示)")
|
|
162
|
+
error_logger.info("ERROR模块 - INFO消息(不应该显示)")
|
|
163
|
+
error_logger.warning("ERROR模块 - WARNING消息(不应该显示)")
|
|
164
|
+
error_logger.error("ERROR模块 - ERROR消息")
|
|
165
|
+
|
|
166
|
+
# 默认模块(应该只显示WARNING及以上)
|
|
167
|
+
default_logger = get_logger('module.default')
|
|
168
|
+
print(f" 默认模块级别: {default_logger.handlers[0].level}")
|
|
169
|
+
default_logger.debug("默认模块 - DEBUG消息(不应该显示)")
|
|
170
|
+
default_logger.info("默认模块 - INFO消息(不应该显示)")
|
|
171
|
+
default_logger.warning("默认模块 - WARNING消息")
|
|
172
|
+
default_logger.error("默认模块 - ERROR消息")
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def test_configuration_edge_cases():
|
|
176
|
+
"""测试配置边界情况"""
|
|
177
|
+
print("\n=== 测试配置边界情况 ===")
|
|
178
|
+
|
|
179
|
+
# 1. 测试仅文件日志
|
|
180
|
+
print("1. 测试仅文件日志...")
|
|
181
|
+
temp_dir = tempfile.mkdtemp()
|
|
182
|
+
log_file = os.path.join(temp_dir, 'file_only.log')
|
|
183
|
+
|
|
184
|
+
try:
|
|
185
|
+
LogManager().reset()
|
|
186
|
+
configure(
|
|
187
|
+
LOG_LEVEL='INFO',
|
|
188
|
+
LOG_FILE=log_file,
|
|
189
|
+
LOG_CONSOLE_ENABLED=False,
|
|
190
|
+
LOG_FILE_ENABLED=True
|
|
191
|
+
)
|
|
192
|
+
|
|
193
|
+
logger = get_logger('test.file_only')
|
|
194
|
+
logger.info("仅文件日志测试消息")
|
|
195
|
+
|
|
196
|
+
if os.path.exists(log_file):
|
|
197
|
+
with open(log_file, 'r', encoding='utf-8') as f:
|
|
198
|
+
content = f.read()
|
|
199
|
+
print(f" 文件内容存在: {len(content) > 0}")
|
|
200
|
+
else:
|
|
201
|
+
print(" 文件不存在!")
|
|
202
|
+
finally:
|
|
203
|
+
shutil.rmtree(temp_dir, ignore_errors=True)
|
|
204
|
+
|
|
205
|
+
# 2. 测试仅控制台日志
|
|
206
|
+
print("2. 测试仅控制台日志...")
|
|
207
|
+
LogManager().reset()
|
|
208
|
+
configure(
|
|
209
|
+
LOG_LEVEL='INFO',
|
|
210
|
+
LOG_CONSOLE_ENABLED=True,
|
|
211
|
+
LOG_FILE_ENABLED=False
|
|
212
|
+
)
|
|
213
|
+
|
|
214
|
+
logger = get_logger('test.console_only')
|
|
215
|
+
logger.info("仅控制台日志测试消息")
|
|
216
|
+
|
|
217
|
+
# 3. 测试无效配置处理
|
|
218
|
+
print("3. 测试无效配置处理...")
|
|
219
|
+
LogManager().reset()
|
|
220
|
+
|
|
221
|
+
# 测试无效级别(应该使用默认级别)
|
|
222
|
+
config = configure(LOG_LEVEL='INVALID')
|
|
223
|
+
print(f" 无效级别处理: {config.level}")
|
|
224
|
+
|
|
225
|
+
# 测试空配置
|
|
226
|
+
LogManager().reset()
|
|
227
|
+
config = configure()
|
|
228
|
+
print(f" 默认配置级别: {config.level}")
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def main():
|
|
232
|
+
"""主测试函数"""
|
|
233
|
+
print("开始最终测试Crawlo框架日志系统...")
|
|
234
|
+
|
|
235
|
+
try:
|
|
236
|
+
# 运行所有测试
|
|
237
|
+
test_complete_log_functionality()
|
|
238
|
+
test_module_specific_logging()
|
|
239
|
+
test_configuration_edge_cases()
|
|
240
|
+
|
|
241
|
+
print("\n=== 最终测试完成 ===")
|
|
242
|
+
print("\n日志系统功能总结:")
|
|
243
|
+
print("✅ 基本日志配置")
|
|
244
|
+
print("✅ 文件和控制台输出")
|
|
245
|
+
print("✅ 日志级别控制")
|
|
246
|
+
print("✅ 模块特定日志级别")
|
|
247
|
+
print("✅ 日志轮转功能")
|
|
248
|
+
print("✅ 配置验证")
|
|
249
|
+
print("✅ 边界情况处理")
|
|
250
|
+
|
|
251
|
+
except Exception as e:
|
|
252
|
+
print(f"\n测试过程中出现错误: {e}")
|
|
253
|
+
import traceback
|
|
254
|
+
traceback.print_exc()
|
|
255
|
+
return 1
|
|
256
|
+
|
|
257
|
+
return 0
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
if __name__ == '__main__':
|
|
261
|
+
sys.exit(main())
|
tests/fix_log_test.py
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
#!/usr/bin/env python
|
|
2
|
+
# -*- coding: UTF-8 -*-
|
|
3
|
+
"""
|
|
4
|
+
测试日志配置修复
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import os
|
|
8
|
+
import sys
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
# 添加项目根目录到Python路径
|
|
12
|
+
project_root = Path(__file__).parent.parent
|
|
13
|
+
sys.path.insert(0, str(project_root))
|
|
14
|
+
|
|
15
|
+
from crawlo.logging import configure_logging as configure, get_logger, LogManager
|
|
16
|
+
from crawlo.logging.config import LogConfig
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def test_correct_configuration():
|
|
20
|
+
"""测试正确的配置方式"""
|
|
21
|
+
print("=== 测试正确的配置方式 ===")
|
|
22
|
+
|
|
23
|
+
# 1. 使用配置字典(推荐方式)
|
|
24
|
+
print("1. 使用配置字典...")
|
|
25
|
+
LogManager().reset()
|
|
26
|
+
|
|
27
|
+
config_dict = {
|
|
28
|
+
'level': 'DEBUG',
|
|
29
|
+
'file_path': 'fix_test.log',
|
|
30
|
+
'max_bytes': 2048,
|
|
31
|
+
'backup_count': 2,
|
|
32
|
+
'console_enabled': True,
|
|
33
|
+
'file_enabled': True,
|
|
34
|
+
'encoding': 'utf-8'
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
config = configure(**config_dict)
|
|
38
|
+
print(f" 配置文件路径: {config.file_path}")
|
|
39
|
+
|
|
40
|
+
logger = get_logger('test.fix')
|
|
41
|
+
file_handler_found = False
|
|
42
|
+
for handler in logger.handlers:
|
|
43
|
+
if 'FileHandler' in type(handler).__name__:
|
|
44
|
+
file_handler_found = True
|
|
45
|
+
print(f" 文件处理器文件名: {handler.baseFilename}")
|
|
46
|
+
|
|
47
|
+
print(f" 文件处理器找到: {file_handler_found}")
|
|
48
|
+
logger.info("修复测试消息")
|
|
49
|
+
|
|
50
|
+
# 2. 使用LogConfig对象
|
|
51
|
+
print("2. 使用LogConfig对象...")
|
|
52
|
+
LogManager().reset()
|
|
53
|
+
|
|
54
|
+
log_config = LogConfig(
|
|
55
|
+
level='INFO',
|
|
56
|
+
file_path='object_test.log',
|
|
57
|
+
max_bytes=1024,
|
|
58
|
+
backup_count=1,
|
|
59
|
+
console_enabled=True,
|
|
60
|
+
file_enabled=True
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
config = configure(log_config)
|
|
64
|
+
print(f" 配置文件路径: {config.file_path}")
|
|
65
|
+
|
|
66
|
+
logger = get_logger('test.object')
|
|
67
|
+
file_handler_found = False
|
|
68
|
+
for handler in logger.handlers:
|
|
69
|
+
if 'FileHandler' in type(handler).__name__:
|
|
70
|
+
file_handler_found = True
|
|
71
|
+
print(f" 文件处理器文件名: {handler.baseFilename}")
|
|
72
|
+
|
|
73
|
+
print(f" 文件处理器找到: {file_handler_found}")
|
|
74
|
+
logger.info("对象配置测试消息")
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def create_settings_class():
|
|
78
|
+
"""创建一个模拟的settings类来测试from_settings方法"""
|
|
79
|
+
print("\n=== 测试from_settings方法 ===")
|
|
80
|
+
|
|
81
|
+
class MockSettings:
|
|
82
|
+
def __init__(self):
|
|
83
|
+
self.LOG_LEVEL = 'DEBUG'
|
|
84
|
+
self.LOG_FILE = 'settings_test.log'
|
|
85
|
+
self.LOG_MAX_BYTES = 1024
|
|
86
|
+
self.LOG_BACKUP_COUNT = 2
|
|
87
|
+
self.LOG_ENCODING = 'utf-8'
|
|
88
|
+
self.LOG_CONSOLE_ENABLED = True
|
|
89
|
+
self.LOG_FILE_ENABLED = True
|
|
90
|
+
self.LOG_LEVELS = {}
|
|
91
|
+
|
|
92
|
+
# 测试from_settings方法
|
|
93
|
+
settings = MockSettings()
|
|
94
|
+
config = LogConfig.from_settings(settings)
|
|
95
|
+
|
|
96
|
+
print(f" 从settings创建的配置:")
|
|
97
|
+
print(f" 级别: {config.level}")
|
|
98
|
+
print(f" 文件路径: {config.file_path}")
|
|
99
|
+
print(f" 轮转大小: {config.max_bytes}")
|
|
100
|
+
print(f" 备份数量: {config.backup_count}")
|
|
101
|
+
print(f" 控制台启用: {config.console_enabled}")
|
|
102
|
+
print(f" 文件启用: {config.file_enabled}")
|
|
103
|
+
|
|
104
|
+
# 应用配置
|
|
105
|
+
LogManager().reset()
|
|
106
|
+
configure(config)
|
|
107
|
+
|
|
108
|
+
logger = get_logger('test.settings')
|
|
109
|
+
file_handler_found = False
|
|
110
|
+
for handler in logger.handlers:
|
|
111
|
+
if 'FileHandler' in type(handler).__name__:
|
|
112
|
+
file_handler_found = True
|
|
113
|
+
print(f" 文件处理器文件名: {handler.baseFilename}")
|
|
114
|
+
|
|
115
|
+
print(f" 文件处理器找到: {file_handler_found}")
|
|
116
|
+
logger.info("Settings配置测试消息")
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def main():
|
|
120
|
+
"""主函数"""
|
|
121
|
+
print("测试日志配置修复...")
|
|
122
|
+
|
|
123
|
+
try:
|
|
124
|
+
test_correct_configuration()
|
|
125
|
+
create_settings_class()
|
|
126
|
+
|
|
127
|
+
print("\n=== 修复测试完成 ===")
|
|
128
|
+
print("\n推荐的日志配置方式:")
|
|
129
|
+
print("1. 使用配置字典: configure(level='DEBUG', file_path='test.log', ...)")
|
|
130
|
+
print("2. 使用LogConfig对象: configure(LogConfig(...))")
|
|
131
|
+
print("3. 使用settings对象: configure(settings_object)")
|
|
132
|
+
|
|
133
|
+
except Exception as e:
|
|
134
|
+
print(f"\n测试过程中出现错误: {e}")
|
|
135
|
+
import traceback
|
|
136
|
+
traceback.print_exc()
|
|
137
|
+
return 1
|
|
138
|
+
|
|
139
|
+
return 0
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
if __name__ == '__main__':
|
|
143
|
+
sys.exit(main())
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
#!/usr/bin/env python
|
|
2
|
+
# -*- coding: UTF-8 -*-
|
|
3
|
+
"""
|
|
4
|
+
测试日志缓冲问题
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import os
|
|
8
|
+
import sys
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
# 添加项目根目录到Python路径
|
|
12
|
+
project_root = Path(__file__).parent.parent
|
|
13
|
+
sys.path.insert(0, str(project_root))
|
|
14
|
+
|
|
15
|
+
from crawlo.logging import configure_logging as configure, get_logger
|
|
16
|
+
import logging
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def test_log_buffering():
|
|
20
|
+
"""测试日志缓冲行为"""
|
|
21
|
+
print("=== 测试日志缓冲行为 ===")
|
|
22
|
+
|
|
23
|
+
# 设置日志文件路径
|
|
24
|
+
log_file = "logs/buffering_test2.log"
|
|
25
|
+
|
|
26
|
+
# 删除可能存在的旧日志文件
|
|
27
|
+
if os.path.exists(log_file):
|
|
28
|
+
os.remove(log_file)
|
|
29
|
+
|
|
30
|
+
# 配置日志系统
|
|
31
|
+
configure(
|
|
32
|
+
level='INFO',
|
|
33
|
+
file_path=log_file,
|
|
34
|
+
console_enabled=True,
|
|
35
|
+
file_enabled=True
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
# 获取logger
|
|
39
|
+
logger = get_logger('buffering.test2')
|
|
40
|
+
|
|
41
|
+
print("1. 检查handler的自动刷新设置...")
|
|
42
|
+
for handler in logger.handlers:
|
|
43
|
+
handler_type = type(handler).__name__
|
|
44
|
+
print(f" Handler类型: {handler_type}")
|
|
45
|
+
if hasattr(handler, 'stream'):
|
|
46
|
+
print(f" 流类型: {type(handler.stream).__name__}")
|
|
47
|
+
if hasattr(handler.stream, 'flush'):
|
|
48
|
+
print(f" 支持flush方法: True")
|
|
49
|
+
|
|
50
|
+
# 检查是否有自动刷新设置
|
|
51
|
+
if hasattr(handler, 'flush'):
|
|
52
|
+
print(f" Handler有flush方法")
|
|
53
|
+
|
|
54
|
+
print("\n2. 写入日志并强制刷新...")
|
|
55
|
+
logger.info("测试日志1")
|
|
56
|
+
logger.info("测试日志2")
|
|
57
|
+
|
|
58
|
+
# 强制刷新所有handler
|
|
59
|
+
for handler in logger.handlers:
|
|
60
|
+
if hasattr(handler, 'flush'):
|
|
61
|
+
handler.flush()
|
|
62
|
+
print(f" 已刷新 {type(handler).__name__}")
|
|
63
|
+
|
|
64
|
+
# 检查文件内容
|
|
65
|
+
if os.path.exists(log_file):
|
|
66
|
+
with open(log_file, 'r', encoding='utf-8') as f:
|
|
67
|
+
content = f.read()
|
|
68
|
+
print(f"\n日志文件内容:")
|
|
69
|
+
print(f" 行数: {len(content.splitlines())}")
|
|
70
|
+
print(f" 内容: {repr(content)}")
|
|
71
|
+
|
|
72
|
+
print("\n3. 测试不同日志级别的缓冲...")
|
|
73
|
+
logger.debug("DEBUG消息(不应显示)")
|
|
74
|
+
logger.info("INFO消息")
|
|
75
|
+
logger.warning("WARNING消息")
|
|
76
|
+
logger.error("ERROR消息")
|
|
77
|
+
|
|
78
|
+
# 再次强制刷新
|
|
79
|
+
for handler in logger.handlers:
|
|
80
|
+
if hasattr(handler, 'flush'):
|
|
81
|
+
handler.flush()
|
|
82
|
+
|
|
83
|
+
# 检查最终文件内容
|
|
84
|
+
if os.path.exists(log_file):
|
|
85
|
+
with open(log_file, 'r', encoding='utf-8') as f:
|
|
86
|
+
lines = f.readlines()
|
|
87
|
+
print(f"\n最终日志文件内容:")
|
|
88
|
+
print(f" 总行数: {len(lines)}")
|
|
89
|
+
for i, line in enumerate(lines):
|
|
90
|
+
print(f" {i+1}: {line.strip()}")
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def main():
|
|
94
|
+
"""主函数"""
|
|
95
|
+
print("开始测试日志缓冲问题...")
|
|
96
|
+
|
|
97
|
+
try:
|
|
98
|
+
test_log_buffering()
|
|
99
|
+
|
|
100
|
+
print("\n=== 所有测试完成 ===")
|
|
101
|
+
|
|
102
|
+
except Exception as e:
|
|
103
|
+
print(f"\n测试过程中出现错误: {e}")
|
|
104
|
+
import traceback
|
|
105
|
+
traceback.print_exc()
|
|
106
|
+
return 1
|
|
107
|
+
|
|
108
|
+
return 0
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
if __name__ == '__main__':
|
|
112
|
+
sys.exit(main())
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
#!/usr/bin/env python
|
|
2
|
+
# -*- coding: UTF-8 -*-
|
|
3
|
+
"""
|
|
4
|
+
测试日志文件的生成时机
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import os
|
|
8
|
+
import sys
|
|
9
|
+
import time
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
# 添加项目根目录到Python路径
|
|
13
|
+
project_root = Path(__file__).parent.parent
|
|
14
|
+
sys.path.insert(0, str(project_root))
|
|
15
|
+
|
|
16
|
+
from crawlo.logging import configure_logging as configure, get_logger
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def test_log_file_generation_timing():
|
|
20
|
+
"""测试日志文件的生成时机"""
|
|
21
|
+
print("=== 测试日志文件的生成时机 ===")
|
|
22
|
+
|
|
23
|
+
# 设置日志文件路径
|
|
24
|
+
log_file = "logs/timing_test.log"
|
|
25
|
+
|
|
26
|
+
# 确保日志目录存在
|
|
27
|
+
os.makedirs("logs", exist_ok=True)
|
|
28
|
+
|
|
29
|
+
# 删除可能存在的旧日志文件
|
|
30
|
+
if os.path.exists(log_file):
|
|
31
|
+
os.remove(log_file)
|
|
32
|
+
print(f"已删除旧日志文件: {log_file}")
|
|
33
|
+
|
|
34
|
+
print(f"日志文件路径: {log_file}")
|
|
35
|
+
print(f"日志文件是否存在: {os.path.exists(log_file)}")
|
|
36
|
+
|
|
37
|
+
# 配置日志系统
|
|
38
|
+
print("\n1. 配置日志系统...")
|
|
39
|
+
configure(
|
|
40
|
+
level='INFO',
|
|
41
|
+
file_path=log_file,
|
|
42
|
+
console_enabled=True,
|
|
43
|
+
file_enabled=True
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
print(f"配置后日志文件是否存在: {os.path.exists(log_file)}")
|
|
47
|
+
|
|
48
|
+
# 获取logger
|
|
49
|
+
print("\n2. 获取logger...")
|
|
50
|
+
logger = get_logger('timing.test')
|
|
51
|
+
print(f"获取logger后日志文件是否存在: {os.path.exists(log_file)}")
|
|
52
|
+
|
|
53
|
+
# 立即写入日志
|
|
54
|
+
print("\n3. 立即写入日志...")
|
|
55
|
+
logger.info("立即写入的第一条日志")
|
|
56
|
+
print(f"写入第一条日志后日志文件是否存在: {os.path.exists(log_file)}")
|
|
57
|
+
|
|
58
|
+
# 检查文件内容
|
|
59
|
+
if os.path.exists(log_file):
|
|
60
|
+
with open(log_file, 'r', encoding='utf-8') as f:
|
|
61
|
+
content = f.read()
|
|
62
|
+
print(f"日志文件内容行数: {len(content.splitlines())}")
|
|
63
|
+
print(f"日志文件大小: {os.path.getsize(log_file)} 字节")
|
|
64
|
+
|
|
65
|
+
# 等待一小段时间
|
|
66
|
+
print("\n4. 等待1秒...")
|
|
67
|
+
time.sleep(1)
|
|
68
|
+
print(f"等待后日志文件是否存在: {os.path.exists(log_file)}")
|
|
69
|
+
|
|
70
|
+
# 再写入一些日志
|
|
71
|
+
print("\n5. 再写入一些日志...")
|
|
72
|
+
for i in range(5):
|
|
73
|
+
logger.info(f"第{i+1}条测试日志")
|
|
74
|
+
time.sleep(0.1)
|
|
75
|
+
|
|
76
|
+
print(f"写入多条日志后日志文件是否存在: {os.path.exists(log_file)}")
|
|
77
|
+
|
|
78
|
+
# 检查最终文件内容
|
|
79
|
+
if os.path.exists(log_file):
|
|
80
|
+
with open(log_file, 'r', encoding='utf-8') as f:
|
|
81
|
+
lines = f.readlines()
|
|
82
|
+
print(f"\n最终日志文件内容:")
|
|
83
|
+
print(f" 总行数: {len(lines)}")
|
|
84
|
+
print(f" 文件大小: {os.path.getsize(log_file)} 字节")
|
|
85
|
+
if lines:
|
|
86
|
+
print(f" 第一行: {lines[0].strip()}")
|
|
87
|
+
print(f" 最后一行: {lines[-1].strip()}")
|
|
88
|
+
|
|
89
|
+
print("\n=== 测试完成 ===")
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def test_buffering_behavior():
|
|
93
|
+
"""测试日志缓冲行为"""
|
|
94
|
+
print("\n=== 测试日志缓冲行为 ===")
|
|
95
|
+
|
|
96
|
+
# 设置日志文件路径
|
|
97
|
+
log_file = "logs/buffering_test.log"
|
|
98
|
+
|
|
99
|
+
# 删除可能存在的旧日志文件
|
|
100
|
+
if os.path.exists(log_file):
|
|
101
|
+
os.remove(log_file)
|
|
102
|
+
|
|
103
|
+
# 配置日志系统
|
|
104
|
+
configure(
|
|
105
|
+
level='INFO',
|
|
106
|
+
file_path=log_file,
|
|
107
|
+
console_enabled=True,
|
|
108
|
+
file_enabled=True
|
|
109
|
+
)
|
|
110
|
+
|
|
111
|
+
logger = get_logger('buffering.test')
|
|
112
|
+
|
|
113
|
+
print("1. 写入日志后立即检查文件...")
|
|
114
|
+
logger.info("缓冲测试日志1")
|
|
115
|
+
print(f" 写入后文件是否存在: {os.path.exists(log_file)}")
|
|
116
|
+
|
|
117
|
+
if os.path.exists(log_file):
|
|
118
|
+
with open(log_file, 'r', encoding='utf-8') as f:
|
|
119
|
+
content = f.read()
|
|
120
|
+
print(f" 文件内容: '{content.strip()}'")
|
|
121
|
+
|
|
122
|
+
print("2. 强制刷新并检查...")
|
|
123
|
+
# 获取文件处理器并强制刷新
|
|
124
|
+
for handler in logger.handlers:
|
|
125
|
+
if hasattr(handler, 'flush'):
|
|
126
|
+
handler.flush()
|
|
127
|
+
|
|
128
|
+
if os.path.exists(log_file):
|
|
129
|
+
with open(log_file, 'r', encoding='utf-8') as f:
|
|
130
|
+
content = f.read()
|
|
131
|
+
print(f" 刷新后文件内容: '{content.strip()}'")
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def main():
|
|
135
|
+
"""主函数"""
|
|
136
|
+
print("开始测试日志文件的生成时机...")
|
|
137
|
+
|
|
138
|
+
try:
|
|
139
|
+
test_log_file_generation_timing()
|
|
140
|
+
test_buffering_behavior()
|
|
141
|
+
|
|
142
|
+
print("\n=== 所有测试完成 ===")
|
|
143
|
+
|
|
144
|
+
except Exception as e:
|
|
145
|
+
print(f"\n测试过程中出现错误: {e}")
|
|
146
|
+
import traceback
|
|
147
|
+
traceback.print_exc()
|
|
148
|
+
return 1
|
|
149
|
+
|
|
150
|
+
return 0
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
if __name__ == '__main__':
|
|
154
|
+
sys.exit(main())
|