沙箱指定路径日志采集最佳实践(Python)
在沙箱中运行的业务应用会将运行日志写入指定目录,但这些日志默认不会自动上报到日志服务。由于沙箱实例具有临时性,实例销毁后本地日志随之丢失,无法满足运维排障要求。您可以通过配置沙箱日志采集,将指定目录中的日志文件增量实时上报到华为云LTS(云日志服务),实现日志的持久化存储。
本文介绍如何通过Python SDK在沙箱自定义镜像中增加日志采集能力,将指定目录的日志文件增量上报到华为云LTS(云日志服务),实现日志的持久化存储和集中管理。
方案原理
本方案在用户自定义Sandbox镜像基础上增加“日志采集”能力,通过旁路进程监听指定目录的文件变化,增量读取新增日志行,输出到stdout/stderr,由系统日志采集组件上报到华为云LTS。
整体工作流程如下:
- 业务写入日志:用户应用按原有方式将日志写入指定目录(如/var/log/app/)
- 监听变化:监听进程持续扫描指定目录,检测到目录内文件的创建和修改事件
- 增量读取:从状态文件记录的上次偏移量位置读取新增的完整日志行
- 异步上报:通过输出到stdout/stderr,由系统日志采集组件上报到LTS,由LTS完成存储和索引
前提条件
华为云资源准备
| 资源 | 说明 |
|---|---|
| 日志组 | 在LTS控制台中新建日志组,用于归类同一业务的日志 |
| 日志流 | 在LTS控制台中新建日志流,日志流是日志上报的最小单元 |
| Project ID | 在控制台右上角账号信息中获取 |
LTS服务按日志写入量和存储量计费,具体计费标准请参考LTS产品价格。建议根据日志量预估费用,并设置合理的日志保留周期。
环境要求
| 要求 | 说明 |
|---|---|
| Python版本 | >=3.10 |
| 基础镜像 | 需包含 tini(进程管理)和 setpriv(用户降权,来自 util-linux) 说明: 如果基础镜像没有tini或setpriv,可在 Dockerfile 中添加安装命令: # Debian/Ubuntu 基础镜像 RUN apt-get update && apt-get install -y tini util-linux && rm -rf /var/lib/apt/lists/* # CentOS/RHEL 基础镜像 RUN yum install -y tini util-linux && yum clean all |
场景化示例
假设有一个AI推理沙箱,业务应用将推理日志写入/var/log/inference/目录,包含以下文件:
- app.log:主应用运行日志,持续追加
- tasks/:子目录,存放每个推理任务的独立日志
- audit.log:审计日志,记录每次API调用
配置LOG_DIR=/var/log/inference后,会递归监听该目录下所有文件,将新增日志行上报到LTS。在LTS控制台可以通过path字段区分日志来源(如/var/log/inference/app.log或/var/log/inference/tasks/task-001.log)。
步骤一:准备目录采集脚本
监听程序是日志采集的核心组件,负责读取指定目录(--log-dir或LOG_DIR)中的日志文件并输出到stdout。它定时扫描目录,仅读取每个文件上次之后新增的内容,将每行日志连同原文件路径封装成JSON,由系统日志采集组件采集后上报到LTS。
创建log-watcher.py文件:
#!/usr/bin/env python3
"""Send appended lines from a Sandbox directory to Huawei Cloud LTS."""
from __future__ import annotations
import argparse
import codecs
import io
import json
import math
import os
from pathlib import Path
import signal
import stat
import subprocess
import sys
import time
READ_SIZE = 65536
READ_BUDGET = 1024 * 1024 # Per file and scan; avoid starving other files.
CHECKPOINT_SIZE = 64
def diagnostic(event: str, **fields) -> None:
print(json.dumps({"component": "log-forwarder", "event": event, **fields},
ensure_ascii=True), file=sys.stderr, flush=True)
class FileState:
def __init__(self, path: str, offset: int):
self.path = path
self.offset = offset
self.checkpoint = b""
self.pending = ""
self.decoder = codecs.getincrementaldecoder("utf-8")(errors="replace")
class DirectoryReader:
def __init__(self, directory: str, *, recursive: bool, from_end: bool, max_line_chars: int):
self.directory = directory
self.recursive = recursive
self.from_end = from_end
self.max_line_chars = max_line_chars
self.files: dict[tuple[int, int], FileState] = {}
self.errors: dict[str, str] = {}
self.output_files = set()
for stream in (sys.stdout, sys.stderr):
info = os.fstat(stream.fileno())
if stat.S_ISREG(info.st_mode):
self.output_files.add((info.st_dev, info.st_ino))
def warn(self, path: str, error: OSError) -> None:
message = f"{type(error).__name__}: {error}"
if self.errors.get(path) != message:
diagnostic("read_error", path=path, message=message)
self.errors[path] = message
def discover(self, initial: bool) -> dict[tuple[int, int], list[str]]:
found: dict[tuple[int, int], list[str]] = {}
directories = [self.directory]
while directories:
directory = directories.pop()
try:
with os.scandir(directory) as scan:
entries = sorted(scan, key=lambda entry: entry.name)
self.errors.pop(directory, None)
except OSError as error:
if initial and directory == self.directory:
raise
self.warn(directory, error)
continue
for entry in entries:
try:
info = entry.stat(follow_symlinks=False)
if stat.S_ISDIR(info.st_mode) and self.recursive:
directories.append(entry.path)
elif stat.S_ISREG(info.st_mode):
identity = (info.st_dev, info.st_ino)
if identity not in self.output_files:
found.setdefault(identity, []).append(entry.path)
except OSError as error:
self.warn(entry.path, error)
return found
def emit(self, state: FileState, line: str, *, partial: bool = False) -> None:
record: dict[str, str | bool] = {"path": state.path, "message": line}
if partial:
record["partial"] = True
print(json.dumps(record, ensure_ascii=False), flush=True)
def emit_line(self, state: FileState, line: str, *, partial: bool = False) -> None:
while len(line) > self.max_line_chars:
self.emit(state, line[:self.max_line_chars], partial=True)
line = line[self.max_line_chars:]
self.emit(state, line, partial=partial)
def feed(self, state: FileState, text: str) -> None:
state.pending += text
while "\n" in state.pending:
line, state.pending = state.pending.split("\n", 1)
if line.endswith("\r"):
line = line[:-1]
self.emit_line(state, line)
while len(state.pending) > self.max_line_chars:
self.emit(state, state.pending[:self.max_line_chars], partial=True)
state.pending = state.pending[self.max_line_chars:]
def flush_partial(self, state: FileState) -> None:
self.feed(state, state.decoder.decode(b"", final=True))
if state.pending:
self.emit_line(state, state.pending, partial=True)
state.pending = ""
state.decoder.reset()
def read_file(self, identity: tuple[int, int], path: str, initial: bool) -> int:
flags = os.O_RDONLY | os.O_NONBLOCK | getattr(os, "O_NOFOLLOW", 0)
descriptor = os.open(path, flags)
try:
info = os.fstat(descriptor)
if not stat.S_ISREG(info.st_mode) or (info.st_dev, info.st_ino) != identity:
return 0 # A replacement raced with discovery; retry next scan.
read_bytes = 0
state = self.files.get(identity)
if state is None:
state = FileState(path, info.st_size if initial and self.from_end else 0)
self.files[identity] = state
state.path = path
if not initial:
checkpoint = os.pread(descriptor, len(state.checkpoint),
state.offset - len(state.checkpoint))
if info.st_size < state.offset or checkpoint != state.checkpoint:
self.flush_partial(state)
state.offset = 0
state.checkpoint = b""
diagnostic("file_reset", path=path)
remaining = READ_BUDGET
while remaining > 0:
chunk = os.pread(descriptor, min(READ_SIZE, remaining), state.offset)
if not chunk:
break
state.offset += len(chunk)
read_bytes += len(chunk)
remaining -= len(chunk)
self.feed(state, state.decoder.decode(chunk, final=False))
state.checkpoint = os.pread(descriptor, min(CHECKPOINT_SIZE, state.offset),
max(0, state.offset - CHECKPOINT_SIZE))
self.errors.pop(path, None)
return read_bytes
finally:
os.close(descriptor)
def poll(self, *, initial: bool = False) -> int:
found = self.discover(initial)
read_bytes = 0
for identity, paths in found.items():
previous = self.files.get(identity)
path = previous.path if previous is not None and previous.path in paths else min(paths)
try:
read_bytes += self.read_file(identity, path, initial)
except BrokenPipeError:
raise
except OSError as error:
self.warn(path, error)
for identity in set(self.files) - set(found):
self.flush_partial(self.files.pop(identity))
return read_bytes
def close(self) -> None:
for state in self.files.values():
self.flush_partial(state)
self.files.clear()
def stop_application(application: subprocess.Popen | None) -> None:
if application is None:
return
try:
os.killpg(application.pid, signal.SIGTERM)
except ProcessLookupError:
pass
try:
application.wait(timeout=3)
except subprocess.TimeoutExpired:
try:
os.killpg(application.pid, signal.SIGKILL)
except ProcessLookupError:
pass
application.wait()
def main() -> int:
if isinstance(sys.stdout, io.TextIOWrapper):
sys.stdout.reconfigure(encoding="utf-8", errors="backslashreplace", line_buffering=True)
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--log-dir", default=os.environ.get("LOG_DIR"),
help="Directory to follow; alternatively set LOG_DIR")
parser.add_argument("--poll-interval", type=float, default=1.0)
parser.add_argument("--from-end", action="store_true",
help="Skip initial content of files present before application launch")
parser.add_argument("--no-recursive", action="store_true")
parser.add_argument("--max-line-chars", type=int, default=16384)
parser.add_argument("command", nargs=argparse.REMAINDER,
help="Optional foreground command after --")
args = parser.parse_args()
if not args.log_dir:
parser.error("Set --log-dir or LOG_DIR")
if not math.isfinite(args.poll_interval) or args.poll_interval <= 0 or args.max_line_chars <= 0:
parser.error("Polling interval and maximum line length must be positive and finite")
command = args.command[1:] if args.command[:1] == ["--"] else args.command
directory = os.path.abspath(args.log_dir)
if os.path.islink(directory):
parser.error("Log directory must not be a symbolic link")
received_signal = 0
def request_stop(number, _frame):
nonlocal received_signal
received_signal = number
signal.signal(signal.SIGTERM, request_stop)
signal.signal(signal.SIGINT, request_stop)
reader = None
application = None
result = 0
output_broken = False
try:
Path(directory).mkdir(parents=True, exist_ok=True)
reader = DirectoryReader(directory, recursive=not args.no_recursive,
from_end=args.from_end, max_line_chars=args.max_line_chars)
reader.poll(initial=True)
if command and not received_signal:
application = subprocess.Popen(command, start_new_session=True)
diagnostic("started", log_dir=directory, recursive=not args.no_recursive,
from_end=args.from_end, poll_interval=args.poll_interval)
while not received_signal:
reader.poll()
if application is not None and application.poll() is not None:
code = application.returncode
assert code is not None
result = code if code >= 0 else 128 - code
break
deadline = time.monotonic() + args.poll_interval
while not received_signal and time.monotonic() < deadline:
time.sleep(min(0.1, max(0, deadline - time.monotonic())))
if received_signal:
result = 128 + received_signal
except BrokenPipeError:
output_broken = True
result = 1
except Exception as error:
diagnostic("fatal_error", message=f"{type(error).__name__}: {error}")
result = 1
finally:
stop_application(application)
if reader is not None and not output_broken:
try:
deadline = time.monotonic() + 2
while reader.poll() and time.monotonic() < deadline:
pass
reader.close()
except BrokenPipeError:
output_broken = True
result = 1
except Exception as error:
diagnostic("shutdown_error", message=f"{type(error).__name__}: {error}")
result = 1
if output_broken:
# Avoid an interpreter-shutdown flush traceback on a closed pipe.
with open(os.devnull, "w") as sink:
os.dup2(sink.fileno(), sys.stdout.fileno())
return result
if __name__ == "__main__":
raise SystemExit(main()) 核心机制说明:
- 文件追踪:使用dev:ino(设备号:inode号)作为文件唯一标识,正确处理文件轮转和重命名
- 增量读取:通过状态文件保存每个文件的读取偏移量,重启后从上次位置继续
- 完整行处理:只发送以换行符结束的完整行,避免截断日志
- 目录自动创建:如果监听目录不存在,程序会尝试自动创建
- 输出与诊断分离:每行日志封装成 {"path", "message"} 的 JSON 写到 stdout,交给平台的标准日志采集器上报 LTS;
步骤二:编写Dockerfile
在原始镜像基础上仅叠加采集所需的文件和依赖,不删除、覆盖或替换原始业务程序。
创建Dockerfile文件:
ARG BASE_IMAGE
FROM ${BASE_IMAGE}
COPY log-watcher.py /opt/sandbox-log/log-watcher.py 步骤三:构建并推送镜像到SWR
基于基础镜像构建包含日志采集能力的补丁镜像。构建过程中会自动验证依赖可用性,确保镜像可用后再发布。
执行构建和推送命令(amd64):
docker build --platform linux/amd64 \ --build-arg BASE_IMAGE="<已有业务镜像>" \ -t "<镜像仓库>/<名称>:<日志补丁版本>" . docker push "<镜像仓库>/<名称>:<日志补丁版本>"
步骤四:构建模板
template = (
Template()
.from_image("<your_image>")
.set_start_cmd("exec python3 /opt/sandbox-log/log-watcher.py \
--log-dir /app/logs \
-- <业务前台启动命令及参数>")
)
build = Template.build_in_background(
# 省略前面的配置参数
observability={
"logs": {
"enableStdLogs": True,
"ltsProjectId": "<LTS 项目 ID>",
"ltsGroupId": "<现有日志组 ID>",
"ltsStreamId": "<现有日志流 ID>"
},
},
) - --log-dir:指定采集目录,应用需将日志写入该目录;如需采集其他路径,修改此参数即可。
- --:分隔符。采集参数置于其前,业务前台命令及其参数置于其后。
如需采集启动时已有文件的新增内容,跳过这些文件的历史内容,可在采集参数中添加 --from-end:
exec python3 /opt/sandbox-log/log-watcher.py --log-dir /app/logs --from-end -- <业务前台启动命令及参数>
步骤五:创建沙箱验证日志采集
创建新的Sandbox,通过实际业务日志写入验证端到端的采集链路是否通畅。
镜像变更后必须创建新的Sandbox。已有Sandbox不会自动获得新的脚本或新的依赖。
配置参数说明
| 参数名 | 参数解释 | 约束限制 | 取值范围 | 默认值 | 示例 |
|---|---|---|---|---|---|
| --log-dir | 指定要采集的日志目录 | 不能是符号链接;缺省时改读LOG_DIR,两者都无则报错 | 任意可访问目录 | 环境变量LOG_DIR的值 | --log-dir /app/logs |
| LOG_DIR(环境变量) | --log-dir不存在时默认读取该变量 | - | LOG_DIR=/app/logs | ||
| --poll-interval | 扫描间隔秒数 | 正数 | 值 > 0 | 1.0 | --poll-interval 0.5 |
| --from-end | 是否追加采集日志 | 仅对启动前已存在的文件生效 | 开关 | 不开启 | --log-dir /app/logs --from-end |
| --no-recursive | 是否采集子目录 | - | 开关 | 不开启 | --log-dir /app/logs --no-recursive |
| --max-line-chars | 单条记录最大字符数 | 必须是正整数 | 整数 ≥ 1 | 16384 | --max-line-chars 8192 |
日志记录格式
结果日志示例
两个不同文件的新增行会输出为两条JSON,原文件路径位于日志正文:
{"path":"/app/logs/api.log","message":"service started"}
{"path":"/app/logs/worker/job.log","message":"task completed"} 原日志本身为JSON时,保留原文作为message:
{"path":"/app/logs/api.log","message":"{\"level\":\"ERROR\",\"message\":\"request failed\"}"} 长行分段,或退出、截断、文件离开采集目录时尚未换行的内容,使用partial标记:
{"path":"/app/logs/api.log","message":"尚未换行的日志内容","partial":true} 每条上报到LTS的记录包含以下字段:
| 字段 | 说明 | 示例 |
|---|---|---|
| message | 原始日志行 | 2026-09-07 10:30:45 INFO User login successful |
| path | 实际源文件的完整路径 | /var/log/app/application.log |
| __labels__.runtime_id | 系统标签,沙箱实例ID | 6b66314c-f10b-4a43-b28b-790eca8c394c |
| __labels__.sandbox_template_id | 系统标签,沙箱模板ID | ff7ae3a1-f579-47cc-92c6-2291fbbed247 |
| __labels__.sandbox_template_name | 系统标签,沙箱模板名称 | ukq0wpz4volwl1dn |
| __labels__.task_id | 系统标签,任务ID | 3cbeac8b-0481-4d5e-83ce-104446bf3d82 |
| __labels__.task_name | 系统标签,任务名称 | swe-bench-swere-py-algorand-sdk-171 |
path必须是实际路径,不能是通配符,这样才能在LTS中按业务文件追踪来源。
状态文件与持久化策略
状态文件决定重启后是否重复发送或遗漏日志。
| 策略 | 状态位置 | 适用场景 | 优缺点 |
|---|---|---|---|
| 临时状态 | 容器本地目录(如/tmp/) | 可接受重启后重新采集 | 简单,但重启后可能重复发送 |
| 持久状态 | Sandbox挂载工作目录 | 需要跨重启保持消费位置 | 避免重复,但需要持久化存储 |
状态文件使用dev:ino(设备号:inode号)作为文件标识,正确处理文件轮转和重命名。状态文件不包含日志服务访问凭据。
常见问题
日志质量问题
| 现象 | 常见原因 | 处理方式 |
|---|---|---|
| 日志重复 | 未保存偏移量或inode变化未处理 | 使用状态文件并识别截断/轮转 |
| 日志缺失 | 只依赖文件事件、watcher启动晚于写入 | 启动后扫描已有文件,并结合偏移量处理 |
| 日志路径含* | 将通配符作为真实文件路径传递 | 监听目录,输出实际文件路径 |
