servly 0.2.0__tar.gz → 0.3.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.
- {servly-0.2.0 → servly-0.3.1}/PKG-INFO +3 -1
- {servly-0.2.0 → servly-0.3.1}/pyproject.toml +3 -1
- servly-0.3.1/servly/cli.py +287 -0
- servly-0.3.1/servly/logs.py +233 -0
- {servly-0.2.0 → servly-0.3.1}/servly/service.py +139 -3
- {servly-0.2.0 → servly-0.3.1}/servly.egg-info/PKG-INFO +3 -1
- servly-0.3.1/servly.egg-info/requires.txt +3 -0
- {servly-0.2.0 → servly-0.3.1}/tests/test_advanced.py +82 -0
- servly-0.2.0/servly/cli.py +0 -295
- servly-0.2.0/servly/logs.py +0 -266
- servly-0.2.0/servly.egg-info/requires.txt +0 -1
- {servly-0.2.0 → servly-0.3.1}/README.md +0 -0
- {servly-0.2.0 → servly-0.3.1}/servly/__init__.py +0 -0
- {servly-0.2.0 → servly-0.3.1}/servly.egg-info/SOURCES.txt +0 -0
- {servly-0.2.0 → servly-0.3.1}/servly.egg-info/dependency_links.txt +0 -0
- {servly-0.2.0 → servly-0.3.1}/servly.egg-info/entry_points.txt +0 -0
- {servly-0.2.0 → servly-0.3.1}/servly.egg-info/top_level.txt +0 -0
- {servly-0.2.0 → servly-0.3.1}/setup.cfg +0 -0
- {servly-0.2.0 → servly-0.3.1}/tests/test_config.py +0 -0
- {servly-0.2.0 → servly-0.3.1}/tests/test_integration.py +0 -0
- {servly-0.2.0 → servly-0.3.1}/tests/test_logs.py +0 -0
- {servly-0.2.0 → servly-0.3.1}/tests/test_service_management.py +0 -0
@@ -1,6 +1,6 @@
|
|
1
1
|
Metadata-Version: 2.4
|
2
2
|
Name: servly
|
3
|
-
Version: 0.
|
3
|
+
Version: 0.3.1
|
4
4
|
Summary: simple process manager
|
5
5
|
Author-email: simpxx <simpxx@gmail.com>
|
6
6
|
License: MIT
|
@@ -10,7 +10,9 @@ Classifier: License :: OSI Approved :: MIT License
|
|
10
10
|
Classifier: Operating System :: OS Independent
|
11
11
|
Requires-Python: >=3.12
|
12
12
|
Description-Content-Type: text/markdown
|
13
|
+
Requires-Dist: psutil>=7.0.0
|
13
14
|
Requires-Dist: pyyaml>=6.0.2
|
15
|
+
Requires-Dist: rich>=14.0.0
|
14
16
|
|
15
17
|
# SERVLY
|
16
18
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
4
4
|
|
5
5
|
[project]
|
6
6
|
name = "servly"
|
7
|
-
version = "0.
|
7
|
+
version = "0.3.1"
|
8
8
|
description = "simple process manager"
|
9
9
|
readme = "README.md"
|
10
10
|
requires-python = ">=3.12"
|
@@ -19,7 +19,9 @@ classifiers = [
|
|
19
19
|
"Operating System :: OS Independent",
|
20
20
|
]
|
21
21
|
dependencies = [
|
22
|
+
"psutil>=7.0.0",
|
22
23
|
"pyyaml>=6.0.2",
|
24
|
+
"rich>=14.0.0",
|
23
25
|
]
|
24
26
|
|
25
27
|
[project.scripts]
|
@@ -0,0 +1,287 @@
|
|
1
|
+
#!/usr/bin/env python3
|
2
|
+
"""
|
3
|
+
Command-line interface for Servly process manager.
|
4
|
+
使用Rich库进行终端输出格式化
|
5
|
+
"""
|
6
|
+
import os
|
7
|
+
import sys
|
8
|
+
import argparse
|
9
|
+
import logging
|
10
|
+
from pathlib import Path
|
11
|
+
from typing import List, Dict, Optional
|
12
|
+
|
13
|
+
from servly.service import ServiceManager
|
14
|
+
from servly.logs import LogManager, Emojis
|
15
|
+
from servly.logs import console, print_header, print_info, print_warning, print_error, print_success, print_service_table
|
16
|
+
|
17
|
+
from rich.logging import RichHandler
|
18
|
+
from rich.traceback import install
|
19
|
+
from rich.markup import escape
|
20
|
+
|
21
|
+
# 安装Rich的异常格式化器
|
22
|
+
install()
|
23
|
+
|
24
|
+
# 配置Rich日志处理
|
25
|
+
logging.basicConfig(
|
26
|
+
level=logging.INFO,
|
27
|
+
format="%(message)s",
|
28
|
+
datefmt="[%X]",
|
29
|
+
handlers=[RichHandler(rich_tracebacks=True, markup=True)]
|
30
|
+
)
|
31
|
+
|
32
|
+
logger = logging.getLogger("servly")
|
33
|
+
|
34
|
+
def setup_arg_parser() -> argparse.ArgumentParser:
|
35
|
+
"""设置命令行参数解析器"""
|
36
|
+
parser = argparse.ArgumentParser(
|
37
|
+
description=f"{Emojis.SERVICE} Servly - Modern process manager",
|
38
|
+
formatter_class=argparse.RawDescriptionHelpFormatter
|
39
|
+
)
|
40
|
+
|
41
|
+
# 全局参数
|
42
|
+
parser.add_argument('-f', '--config',
|
43
|
+
help='配置文件路径 (默认: servly.yml)',
|
44
|
+
default='servly.yml')
|
45
|
+
|
46
|
+
subparsers = parser.add_subparsers(dest='command', help='要执行的命令')
|
47
|
+
|
48
|
+
# Start 命令
|
49
|
+
start_parser = subparsers.add_parser('start', help=f'{Emojis.START} 启动服务')
|
50
|
+
start_parser.add_argument('service', nargs='?', default='all',
|
51
|
+
help='服务名称或 "all" 启动所有服务')
|
52
|
+
|
53
|
+
# Stop 命令
|
54
|
+
stop_parser = subparsers.add_parser('stop', help=f'{Emojis.STOP} 停止服务')
|
55
|
+
stop_parser.add_argument('service', nargs='?', default='all',
|
56
|
+
help='服务名称或 "all" 停止所有服务')
|
57
|
+
|
58
|
+
# Restart 命令
|
59
|
+
restart_parser = subparsers.add_parser('restart', help=f'{Emojis.RESTART} 重启服务')
|
60
|
+
restart_parser.add_argument('service', nargs='?', default='all',
|
61
|
+
help='服务名称或 "all" 重启所有服务')
|
62
|
+
|
63
|
+
# Log 命令
|
64
|
+
log_parser = subparsers.add_parser('log', help=f'{Emojis.LOG} 查看服务日志')
|
65
|
+
log_parser.add_argument('service', nargs='?', default='all',
|
66
|
+
help='服务名称或 "all" 查看所有日志')
|
67
|
+
log_parser.add_argument('--no-follow', '-n', action='store_true',
|
68
|
+
help='不实时跟踪日志')
|
69
|
+
log_parser.add_argument('--lines', '-l', type=int, default=10,
|
70
|
+
help='初始显示的行数')
|
71
|
+
|
72
|
+
# List 命令 - 保留原命令名,不改为 ps
|
73
|
+
list_parser = subparsers.add_parser('list', help='列出服务')
|
74
|
+
|
75
|
+
return parser
|
76
|
+
|
77
|
+
def handle_start(manager: ServiceManager, service_name: str) -> bool:
|
78
|
+
"""处理启动命令"""
|
79
|
+
if service_name == 'all':
|
80
|
+
service_names = manager.get_service_names()
|
81
|
+
if not service_names:
|
82
|
+
print_warning("配置中没有定义任何服务。")
|
83
|
+
return False
|
84
|
+
|
85
|
+
console.print(f"{Emojis.START} 正在启动所有服务...", style="running")
|
86
|
+
success = True
|
87
|
+
for name in service_names:
|
88
|
+
if not manager.start(name):
|
89
|
+
print_error(f"启动服务 '{name}' 失败")
|
90
|
+
success = False
|
91
|
+
else:
|
92
|
+
print_success(f"服务 '{name}' 已成功启动")
|
93
|
+
|
94
|
+
if success:
|
95
|
+
print_success("所有服务已成功启动!")
|
96
|
+
else:
|
97
|
+
print_warning("有些服务启动失败,请检查日志获取详情。")
|
98
|
+
|
99
|
+
return success
|
100
|
+
else:
|
101
|
+
result = manager.start(service_name)
|
102
|
+
if result:
|
103
|
+
print_success(f"服务 '{service_name}' 已成功启动")
|
104
|
+
else:
|
105
|
+
print_error(f"启动服务 '{service_name}' 失败")
|
106
|
+
return result
|
107
|
+
|
108
|
+
def handle_stop(manager: ServiceManager, service_name: str) -> bool:
|
109
|
+
"""处理停止命令"""
|
110
|
+
if service_name == 'all':
|
111
|
+
service_names = manager.get_running_services()
|
112
|
+
if not service_names:
|
113
|
+
console.print(f"{Emojis.INFO} 当前没有正在运行的服务。", style="dim")
|
114
|
+
return True
|
115
|
+
|
116
|
+
console.print(f"{Emojis.STOP} 正在停止所有服务...", style="warning")
|
117
|
+
success = True
|
118
|
+
for name in service_names:
|
119
|
+
if not manager.stop(name):
|
120
|
+
print_error(f"停止服务 '{name}' 失败")
|
121
|
+
success = False
|
122
|
+
else:
|
123
|
+
console.print(f"{Emojis.STOPPED} 服务 '{name}' 已停止", style="stopped")
|
124
|
+
|
125
|
+
if success:
|
126
|
+
console.print(f"\n{Emojis.STOPPED} 所有服务已成功停止!", style="warning")
|
127
|
+
else:
|
128
|
+
print_warning("有些服务停止失败,请检查日志获取详情。")
|
129
|
+
|
130
|
+
return success
|
131
|
+
else:
|
132
|
+
result = manager.stop(service_name)
|
133
|
+
if result:
|
134
|
+
console.print(f"{Emojis.STOPPED} 服务 '{service_name}' 已成功停止", style="warning")
|
135
|
+
else:
|
136
|
+
print_error(f"停止服务 '{service_name}' 失败")
|
137
|
+
return result
|
138
|
+
|
139
|
+
def handle_restart(manager: ServiceManager, service_name: str) -> bool:
|
140
|
+
"""处理重启命令"""
|
141
|
+
if service_name == 'all':
|
142
|
+
service_names = manager.get_service_names()
|
143
|
+
if not service_names:
|
144
|
+
print_warning("配置中没有定义任何服务。")
|
145
|
+
return False
|
146
|
+
|
147
|
+
console.print(f"{Emojis.RESTART} 正在重启所有服务...", style="restart")
|
148
|
+
success = True
|
149
|
+
for name in service_names:
|
150
|
+
if not manager.restart(name):
|
151
|
+
print_error(f"重启服务 '{name}' 失败")
|
152
|
+
success = False
|
153
|
+
else:
|
154
|
+
console.print(f"{Emojis.RUNNING} 服务 '{name}' 已成功重启", style="restart")
|
155
|
+
|
156
|
+
if success:
|
157
|
+
print_success("所有服务已成功重启!")
|
158
|
+
else:
|
159
|
+
print_warning("有些服务重启失败,请检查日志获取详情。")
|
160
|
+
|
161
|
+
return success
|
162
|
+
else:
|
163
|
+
result = manager.restart(service_name)
|
164
|
+
if result:
|
165
|
+
console.print(f"{Emojis.RUNNING} 服务 '{service_name}' 已成功重启", style="restart")
|
166
|
+
else:
|
167
|
+
print_error(f"重启服务 '{service_name}' 失败")
|
168
|
+
return result
|
169
|
+
|
170
|
+
def handle_log(manager: ServiceManager, log_manager: LogManager, args) -> bool:
|
171
|
+
"""处理日志查看命令"""
|
172
|
+
service_name = args.service
|
173
|
+
follow = not args.no_follow
|
174
|
+
lines = args.lines
|
175
|
+
|
176
|
+
if service_name == 'all':
|
177
|
+
services = manager.get_service_names()
|
178
|
+
if not services:
|
179
|
+
print_warning("配置中没有定义任何服务。")
|
180
|
+
return False
|
181
|
+
else:
|
182
|
+
if service_name not in manager.get_service_names():
|
183
|
+
print_error(f"服务 '{service_name}' 在配置中未找到。")
|
184
|
+
return False
|
185
|
+
services = [service_name]
|
186
|
+
|
187
|
+
# 使用LogManager查看日志
|
188
|
+
log_manager.tail_logs(services, follow=follow, lines=lines)
|
189
|
+
return True
|
190
|
+
|
191
|
+
def handle_list(manager: ServiceManager) -> bool:
|
192
|
+
"""处理列出服务命令"""
|
193
|
+
service_names = manager.get_service_names()
|
194
|
+
|
195
|
+
if not service_names:
|
196
|
+
print_warning("配置中没有定义任何服务。")
|
197
|
+
return True
|
198
|
+
|
199
|
+
print_header("服务列表")
|
200
|
+
|
201
|
+
# 构建服务列表数据
|
202
|
+
services = []
|
203
|
+
for name in service_names:
|
204
|
+
is_running = manager.is_running(name)
|
205
|
+
pid = manager.get_service_pid(name)
|
206
|
+
|
207
|
+
# 获取服务运行时间
|
208
|
+
uptime_seconds = manager.get_uptime(name) if is_running else None
|
209
|
+
uptime = manager.format_uptime(uptime_seconds) if is_running else "-"
|
210
|
+
|
211
|
+
# 获取 CPU 和内存使用情况
|
212
|
+
cpu_mem_stats = {}
|
213
|
+
if is_running:
|
214
|
+
stats = manager.get_process_stats(name)
|
215
|
+
cpu_mem_stats["cpu"] = manager.format_cpu_percent(stats["cpu_percent"])
|
216
|
+
cpu_mem_stats["memory"] = manager.format_memory(stats["memory_mb"], stats["memory_percent"])
|
217
|
+
else:
|
218
|
+
cpu_mem_stats["cpu"] = "0%"
|
219
|
+
cpu_mem_stats["memory"] = "0b"
|
220
|
+
|
221
|
+
services.append({
|
222
|
+
"name": name,
|
223
|
+
"status": "running" if is_running else "stopped",
|
224
|
+
"pid": pid,
|
225
|
+
"uptime": uptime,
|
226
|
+
"cpu": cpu_mem_stats["cpu"],
|
227
|
+
"memory": cpu_mem_stats["memory"]
|
228
|
+
})
|
229
|
+
|
230
|
+
# 使用Rich表格显示服务列表
|
231
|
+
print_service_table(services)
|
232
|
+
|
233
|
+
console.print(f"[dim]配置文件: {manager.config_path}[/]")
|
234
|
+
console.print(f"[dim]运行中服务: {len(manager.get_running_services())}/{len(service_names)}[/]")
|
235
|
+
console.print()
|
236
|
+
|
237
|
+
return True
|
238
|
+
|
239
|
+
def main():
|
240
|
+
"""CLI 应用程序入口点"""
|
241
|
+
# 显示头部
|
242
|
+
print_header("SERVLY - Modern Process Manager")
|
243
|
+
|
244
|
+
parser = setup_arg_parser()
|
245
|
+
args = parser.parse_args()
|
246
|
+
|
247
|
+
if not args.command:
|
248
|
+
parser.print_help()
|
249
|
+
return 1
|
250
|
+
|
251
|
+
# 创建服务管理器
|
252
|
+
try:
|
253
|
+
service_manager = ServiceManager(config_path=args.config)
|
254
|
+
except Exception as e:
|
255
|
+
print_error(f"加载配置文件时出错: {escape(str(e))}")
|
256
|
+
return 1
|
257
|
+
|
258
|
+
# 创建日志管理器
|
259
|
+
log_manager = LogManager(service_manager.log_dir)
|
260
|
+
|
261
|
+
# 处理命令
|
262
|
+
try:
|
263
|
+
if args.command == 'start':
|
264
|
+
success = handle_start(service_manager, args.service)
|
265
|
+
elif args.command == 'stop':
|
266
|
+
success = handle_stop(service_manager, args.service)
|
267
|
+
elif args.command == 'restart':
|
268
|
+
success = handle_restart(service_manager, args.service)
|
269
|
+
elif args.command == 'log':
|
270
|
+
success = handle_log(service_manager, log_manager, args)
|
271
|
+
elif args.command == 'list':
|
272
|
+
success = handle_list(service_manager)
|
273
|
+
else:
|
274
|
+
parser.print_help()
|
275
|
+
return 1
|
276
|
+
except KeyboardInterrupt:
|
277
|
+
console.print(f"\n{Emojis.STOP} 操作被用户中断", style="dim")
|
278
|
+
return 1
|
279
|
+
except Exception as e:
|
280
|
+
print_error(f"执行命令时出错: {escape(str(e))}")
|
281
|
+
logger.exception("命令执行异常")
|
282
|
+
return 1
|
283
|
+
|
284
|
+
return 0 if success else 1
|
285
|
+
|
286
|
+
if __name__ == "__main__":
|
287
|
+
sys.exit(main())
|
@@ -0,0 +1,233 @@
|
|
1
|
+
"""
|
2
|
+
Log management functionality for Servly.
|
3
|
+
使用Rich库进行日志格式化和展示,实现PM2风格的日志效果。
|
4
|
+
"""
|
5
|
+
import os
|
6
|
+
import sys
|
7
|
+
import time
|
8
|
+
import re
|
9
|
+
from pathlib import Path
|
10
|
+
from typing import List, Dict, Optional, Tuple
|
11
|
+
|
12
|
+
from rich.console import Console
|
13
|
+
from rich.theme import Theme
|
14
|
+
from rich.text import Text
|
15
|
+
from rich.panel import Panel
|
16
|
+
from rich.table import Table
|
17
|
+
from rich.live import Live
|
18
|
+
from rich import box
|
19
|
+
|
20
|
+
# 自定义Rich主题
|
21
|
+
custom_theme = Theme({
|
22
|
+
"warning": "yellow",
|
23
|
+
"error": "bold red",
|
24
|
+
"info": "green",
|
25
|
+
"dim": "dim",
|
26
|
+
"stdout_service": "green",
|
27
|
+
"stderr_service": "red",
|
28
|
+
"header": "cyan bold",
|
29
|
+
"subheader": "bright_black",
|
30
|
+
"running": "green",
|
31
|
+
"stopped": "bright_black",
|
32
|
+
"restart": "magenta",
|
33
|
+
"separator": "cyan",
|
34
|
+
})
|
35
|
+
|
36
|
+
# 创建Rich控制台对象
|
37
|
+
console = Console(theme=custom_theme)
|
38
|
+
|
39
|
+
# 服务相关的 emoji
|
40
|
+
class Emojis:
|
41
|
+
"""服务状态相关的emoji图标"""
|
42
|
+
SERVICE = "🔧"
|
43
|
+
START = "🟢"
|
44
|
+
STOP = "🔴"
|
45
|
+
RESTART = "🔄"
|
46
|
+
INFO = "ℹ️ "
|
47
|
+
WARNING = "⚠️ "
|
48
|
+
ERROR = "❌"
|
49
|
+
LOG = "📝"
|
50
|
+
STDOUT = "📤"
|
51
|
+
STDERR = "📥"
|
52
|
+
TIME = "🕒"
|
53
|
+
RUNNING = "✅"
|
54
|
+
STOPPED = "⛔"
|
55
|
+
LOADING = "⏳"
|
56
|
+
|
57
|
+
# Rich格式化输出工具函数
|
58
|
+
def print_header(title: str):
|
59
|
+
"""打印美化的标题"""
|
60
|
+
console.print()
|
61
|
+
console.rule(f"[header]{Emojis.SERVICE} {title}[/]", style="separator")
|
62
|
+
console.print()
|
63
|
+
|
64
|
+
def print_info(message: str):
|
65
|
+
"""打印信息消息"""
|
66
|
+
console.print(f"{Emojis.INFO} {message}", style="info")
|
67
|
+
|
68
|
+
def print_warning(message: str):
|
69
|
+
"""打印警告消息"""
|
70
|
+
console.print(f"{Emojis.WARNING} {message}", style="warning")
|
71
|
+
|
72
|
+
def print_error(message: str):
|
73
|
+
"""打印错误消息"""
|
74
|
+
console.print(f"{Emojis.ERROR} {message}", style="error")
|
75
|
+
|
76
|
+
def print_success(message: str):
|
77
|
+
"""打印成功消息"""
|
78
|
+
console.print(f"{Emojis.RUNNING} {message}", style="running")
|
79
|
+
|
80
|
+
def print_service_table(services: List[Dict]):
|
81
|
+
"""打印服务状态表格,PM2风格紧凑布局"""
|
82
|
+
table = Table(show_header=True, header_style="header", expand=True, box=box.SIMPLE)
|
83
|
+
|
84
|
+
# PM2风格紧凑表头
|
85
|
+
table.add_column("name", style="cyan")
|
86
|
+
table.add_column("pid", justify="right")
|
87
|
+
table.add_column("uptime", justify="right")
|
88
|
+
table.add_column("cpu", justify="right")
|
89
|
+
table.add_column("mem", justify="right")
|
90
|
+
|
91
|
+
for service in services:
|
92
|
+
name = service["name"]
|
93
|
+
pid = service["pid"] or "-"
|
94
|
+
uptime = service.get("uptime", "-")
|
95
|
+
cpu = service.get("cpu", "0%")
|
96
|
+
memory = service.get("memory", "0b")
|
97
|
+
|
98
|
+
status_style = "running" if service["status"] == "running" else "stopped"
|
99
|
+
|
100
|
+
table.add_row(
|
101
|
+
Text(name, style=status_style),
|
102
|
+
Text(str(pid), style=status_style),
|
103
|
+
Text(str(uptime), style=status_style),
|
104
|
+
Text(str(cpu), style=status_style),
|
105
|
+
Text(str(memory), style=status_style)
|
106
|
+
)
|
107
|
+
|
108
|
+
console.print(table)
|
109
|
+
console.print()
|
110
|
+
|
111
|
+
|
112
|
+
class LogManager:
|
113
|
+
"""管理和显示服务日志"""
|
114
|
+
|
115
|
+
def __init__(self, log_dir: Path):
|
116
|
+
self.log_dir = log_dir
|
117
|
+
self.default_tail_lines = 15 # 默认展示最后15行日志
|
118
|
+
|
119
|
+
def get_log_files(self, service_name: str) -> Dict[str, Path]:
|
120
|
+
"""获取服务的stdout和stderr日志文件路径"""
|
121
|
+
return {
|
122
|
+
'stdout': self.log_dir / f"{service_name}-out.log",
|
123
|
+
'stderr': self.log_dir / f"{service_name}-error.log"
|
124
|
+
}
|
125
|
+
|
126
|
+
def _parse_log_line(self, line: str) -> Tuple[str, str]:
|
127
|
+
"""解析日志行,提取时间戳和内容"""
|
128
|
+
timestamp = ""
|
129
|
+
content = line.rstrip()
|
130
|
+
|
131
|
+
# 尝试提取时间戳
|
132
|
+
timestamp_match = re.search(r'(\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2})', line)
|
133
|
+
if timestamp_match:
|
134
|
+
timestamp = timestamp_match.group(1)
|
135
|
+
# 移除行中已有的时间戳部分
|
136
|
+
content = line.replace(timestamp, "", 1).lstrip().rstrip()
|
137
|
+
else:
|
138
|
+
timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
|
139
|
+
|
140
|
+
return timestamp, content
|
141
|
+
|
142
|
+
def tail_logs(self, service_names: List[str], follow: bool = True, lines: int = None):
|
143
|
+
"""
|
144
|
+
显示服务日志
|
145
|
+
|
146
|
+
Args:
|
147
|
+
service_names: 要查看的服务名称列表
|
148
|
+
follow: 是否实时跟踪日志(类似tail -f)
|
149
|
+
lines: 初始显示的行数,默认为self.default_tail_lines
|
150
|
+
"""
|
151
|
+
if lines is None:
|
152
|
+
lines = self.default_tail_lines
|
153
|
+
|
154
|
+
if not service_names:
|
155
|
+
print_warning("未指定要查看日志的服务。")
|
156
|
+
return
|
157
|
+
|
158
|
+
# 检查日志文件是否存在
|
159
|
+
log_files = []
|
160
|
+
for service in service_names:
|
161
|
+
service_logs = self.get_log_files(service)
|
162
|
+
for log_type, log_path in service_logs.items():
|
163
|
+
if log_path.exists():
|
164
|
+
log_files.append((service, log_type, log_path))
|
165
|
+
else:
|
166
|
+
style = "stderr_service" if log_type == "stderr" else "stdout_service"
|
167
|
+
console.print(f"{Emojis.WARNING} 未找到服务 [{style}]{service}[/] 的 {log_type} 日志。", style="warning")
|
168
|
+
|
169
|
+
if not log_files:
|
170
|
+
print_warning("未找到指定服务的日志文件。")
|
171
|
+
return
|
172
|
+
|
173
|
+
if follow:
|
174
|
+
# 首先显示最后几行,然后再开始跟踪
|
175
|
+
self._display_recent_logs(log_files, lines)
|
176
|
+
self._follow_logs(log_files)
|
177
|
+
else:
|
178
|
+
self._display_recent_logs(log_files, lines)
|
179
|
+
|
180
|
+
def _display_recent_logs(self, log_files: List[Tuple[str, str, Path]], lines: int):
|
181
|
+
"""显示最近的日志行"""
|
182
|
+
for service, log_type, log_path in log_files:
|
183
|
+
# PM2风格的标题
|
184
|
+
console.print(f"\n[dim]{log_path} last {lines} lines:[/]")
|
185
|
+
|
186
|
+
try:
|
187
|
+
# 读取最后N行
|
188
|
+
with open(log_path, 'r') as f:
|
189
|
+
content = f.readlines()
|
190
|
+
last_lines = content[-lines:] if len(content) >= lines else content
|
191
|
+
|
192
|
+
# 打印每一行,PM2格式
|
193
|
+
for line in last_lines:
|
194
|
+
timestamp, message = self._parse_log_line(line)
|
195
|
+
style = "stderr_service" if log_type == "stderr" else "stdout_service"
|
196
|
+
console.print(f"[{style}]{service}[/] | {timestamp}: {message}")
|
197
|
+
except Exception as e:
|
198
|
+
print_error(f"读取日志文件出错: {str(e)}")
|
199
|
+
|
200
|
+
def _follow_logs(self, log_files: List[Tuple[str, str, Path]]):
|
201
|
+
"""实时跟踪日志(类似tail -f)"""
|
202
|
+
file_handlers = {}
|
203
|
+
|
204
|
+
try:
|
205
|
+
# 打开所有日志文件
|
206
|
+
for service, log_type, log_path in log_files:
|
207
|
+
f = open(log_path, 'r')
|
208
|
+
# 移动到文件末尾
|
209
|
+
f.seek(0, os.SEEK_END)
|
210
|
+
file_handlers[(service, log_type)] = f
|
211
|
+
|
212
|
+
console.print(f"\n[dim]正在跟踪日志... (按Ctrl+C停止)[/]")
|
213
|
+
|
214
|
+
while True:
|
215
|
+
has_new_data = False
|
216
|
+
|
217
|
+
for (service, log_type), f in file_handlers.items():
|
218
|
+
line = f.readline()
|
219
|
+
if line:
|
220
|
+
has_new_data = True
|
221
|
+
timestamp, message = self._parse_log_line(line)
|
222
|
+
style = "stderr_service" if log_type == "stderr" else "stdout_service"
|
223
|
+
console.print(f"[{style}]{service}[/] | {timestamp}: {message}")
|
224
|
+
|
225
|
+
if not has_new_data:
|
226
|
+
time.sleep(0.1)
|
227
|
+
|
228
|
+
except KeyboardInterrupt:
|
229
|
+
console.print(f"\n[dim]已停止日志跟踪[/]")
|
230
|
+
finally:
|
231
|
+
# 关闭所有文件
|
232
|
+
for f in file_handlers.values():
|
233
|
+
f.close()
|