fix: improve log reliability and correlation
This commit is contained in:
1 parent
8eea1cb7a4
commit
8a7ca8a654
21 files changed
+698
-91
No files matched your search
+73
-26
@@ -1566,10 +1566,9 @@ class AgentLoop:
|
||||
try:
|
||||
await delivery.abort_stream()
|
||||
except Exception:
|
||||
logger.debug(
|
||||
logger.opt(exception=log_content).debug(
|
||||
"Could not close stream for cancelled session {}",
|
||||
session_key,
|
||||
exc_info=True,
|
||||
)
|
||||
# An explicit turn stop materializes partial context so
|
||||
# the next prompt can see completed tool results. Gateway
|
||||
@@ -1591,10 +1590,9 @@ class AgentLoop:
|
||||
key,
|
||||
)
|
||||
except Exception:
|
||||
logger.debug(
|
||||
logger.opt(exception=log_content).debug(
|
||||
"Could not restore checkpoint for cancelled session {}",
|
||||
session_key,
|
||||
exc_info=True,
|
||||
)
|
||||
raise
|
||||
except Exception as exc:
|
||||
@@ -1779,15 +1777,18 @@ class AgentLoop:
|
||||
|
||||
ctx.events = EventSink(track_output, ctx.events.accepts)
|
||||
|
||||
await self._run_turn_stage(ctx, "restore", self._restore_turn)
|
||||
await self._run_turn_stage(ctx, "compact", self._compact_session)
|
||||
if await self._run_turn_stage(ctx, "command", self._dispatch_command):
|
||||
with logger.contextualize(turn_id=ctx.turn_id, session_key=ctx.session_key):
|
||||
await self._run_turn_stage(ctx, "restore", self._restore_turn)
|
||||
await self._run_turn_stage(ctx, "compact", self._compact_session)
|
||||
if await self._run_turn_stage(ctx, "command", self._dispatch_command):
|
||||
self._log_turn_completion(ctx, outcome="command")
|
||||
return ctx.outbound
|
||||
await self._run_turn_stage(ctx, "build", self._build_turn)
|
||||
await self._run_turn_stage(ctx, "run", self._run_turn)
|
||||
await self._run_turn_stage(ctx, "save", self._persist_turn)
|
||||
await self._run_turn_stage(ctx, "respond", self._prepare_outbound)
|
||||
self._log_turn_completion(ctx)
|
||||
return ctx.outbound
|
||||
await self._run_turn_stage(ctx, "build", self._build_turn)
|
||||
await self._run_turn_stage(ctx, "run", self._run_turn)
|
||||
await self._run_turn_stage(ctx, "save", self._persist_turn)
|
||||
await self._run_turn_stage(ctx, "respond", self._prepare_outbound)
|
||||
return ctx.outbound
|
||||
|
||||
async def _run_turn_stage(
|
||||
self,
|
||||
@@ -1800,22 +1801,76 @@ class AgentLoop:
|
||||
result = await handler(ctx)
|
||||
except Exception:
|
||||
duration_ms = (time.perf_counter() - started_at) * 1000
|
||||
logger.debug(
|
||||
"[turn {}] Stage {} failed after {:.1f}ms",
|
||||
ctx.turn_id,
|
||||
log_content = not ctx.ephemeral and (
|
||||
ctx.session is None
|
||||
or (ctx.session.policy.persist and ctx.session.policy.log_content)
|
||||
)
|
||||
logger.opt(exception=log_content).bind(
|
||||
event="turn_stage",
|
||||
stage=name,
|
||||
outcome="error",
|
||||
duration_ms=round(duration_ms, 1),
|
||||
).error(
|
||||
"Stage {} failed after {:.1f}ms",
|
||||
name,
|
||||
duration_ms,
|
||||
)
|
||||
raise
|
||||
duration_ms = (time.perf_counter() - started_at) * 1000
|
||||
logger.debug(
|
||||
"[turn {}] Stage {} completed in {:.1f}ms",
|
||||
ctx.turn_id,
|
||||
logger.bind(
|
||||
event="turn_stage",
|
||||
stage=name,
|
||||
outcome="success",
|
||||
duration_ms=round(duration_ms, 1),
|
||||
).debug(
|
||||
"Stage {} completed in {:.1f}ms",
|
||||
name,
|
||||
duration_ms,
|
||||
)
|
||||
return result
|
||||
|
||||
def _log_turn_completion(self, ctx: TurnContext, *, outcome: str | None = None) -> None:
|
||||
duration_ms = ctx.turn_latency_ms
|
||||
if duration_ms is None:
|
||||
duration_ms = max(0, round((time.time() - ctx.turn_wall_started_at) * 1000))
|
||||
runtime = ctx.runtime
|
||||
provider = runtime.provider.provider_name if runtime is not None else None
|
||||
model = runtime.model if runtime is not None else None
|
||||
response_preview = "[content hidden]"
|
||||
if (
|
||||
ctx.kind is TurnKind.USER
|
||||
and ctx.session is not None
|
||||
and not ctx.ephemeral
|
||||
and ctx.session.policy.persist
|
||||
and ctx.session.policy.log_content
|
||||
and ctx.final_content is not None
|
||||
):
|
||||
response_preview = (
|
||||
f"{ctx.final_content[:120]}..."
|
||||
if len(ctx.final_content) > 120
|
||||
else ctx.final_content
|
||||
)
|
||||
final_outcome = outcome or ctx.stop_reason or "completed"
|
||||
logger.bind(
|
||||
event="turn_completed",
|
||||
outcome=final_outcome,
|
||||
duration_ms=duration_ms,
|
||||
provider=provider,
|
||||
model=model,
|
||||
channel=ctx.msg.channel,
|
||||
chat_id=ctx.msg.chat_id,
|
||||
).info(
|
||||
"Turn completed channel={} chat_id={} outcome={} duration_ms={} "
|
||||
"provider={} model={} response={}",
|
||||
ctx.msg.channel,
|
||||
ctx.msg.chat_id,
|
||||
final_outcome,
|
||||
duration_ms,
|
||||
provider or "-",
|
||||
model or "-",
|
||||
response_preview,
|
||||
)
|
||||
|
||||
def _assemble_outbound(
|
||||
self,
|
||||
msg: InboundMessage,
|
||||
@@ -1823,16 +1878,9 @@ class AgentLoop:
|
||||
stop_reason: str,
|
||||
streamed_content: bool,
|
||||
*,
|
||||
log_content: bool = True,
|
||||
turn_latency_ms: int | None = None,
|
||||
) -> OutboundMessage | None:
|
||||
"""Assemble the final outbound message from turn results."""
|
||||
if log_content:
|
||||
preview = final_content[:120] + "..." if len(final_content) > 120 else final_content
|
||||
logger.info("Response to {}:{}: {}", msg.channel, msg.sender_id, preview)
|
||||
else:
|
||||
logger.info("Response to {}:{}: [content hidden]", msg.channel, msg.sender_id)
|
||||
|
||||
event = None
|
||||
meta = dict(msg.metadata or {})
|
||||
if streamed_content and stop_reason not in {"error", "tool_error"}:
|
||||
@@ -2184,7 +2232,6 @@ class AgentLoop:
|
||||
cast(str, ctx.final_content),
|
||||
ctx.stop_reason,
|
||||
ctx.streamed_content,
|
||||
log_content=ctx.require_session().policy.log_content,
|
||||
turn_latency_ms=ctx.turn_latency_ms,
|
||||
)
|
||||
if ctx.ephemeral and ctx.outbound is not None:
|
||||
|
||||
+57
-1
@@ -51,6 +51,7 @@ _MODEL_NAME_KEY = web.AppKey[str]("model_name")
|
||||
_REQUEST_TIMEOUT_KEY = web.AppKey[float]("request_timeout")
|
||||
_SESSION_LOCKS_KEY = web.AppKey[dict[str, asyncio.Lock]]("session_locks")
|
||||
_PREPARE_AGENT_KEY = web.AppKey[Callable[[], Awaitable[None]] | None]("prepare_agent")
|
||||
_REQUEST_ID_KEY = web.RequestKey[str]("request_id")
|
||||
_MISSING = object()
|
||||
|
||||
|
||||
@@ -498,6 +499,60 @@ def create_app(
|
||||
app[_SESSION_LOCKS_KEY] = {} # per-user locks, keyed by session_key
|
||||
app[_PREPARE_AGENT_KEY] = prepare_agent
|
||||
|
||||
@web.middleware
|
||||
async def request_logging_middleware(
|
||||
request: web.Request,
|
||||
handler: Callable[[web.Request], Awaitable[web.StreamResponse]],
|
||||
) -> web.StreamResponse:
|
||||
request_id = uuid.uuid4().hex[:16]
|
||||
request[_REQUEST_ID_KEY] = request_id
|
||||
started_at = time.perf_counter()
|
||||
with logger.contextualize(request_id=request_id):
|
||||
try:
|
||||
response = await handler(request)
|
||||
except Exception:
|
||||
duration_ms = round((time.perf_counter() - started_at) * 1000, 1)
|
||||
logger.opt(exception=True).bind(
|
||||
event="http_request",
|
||||
outcome="error",
|
||||
duration_ms=duration_ms,
|
||||
method=request.method,
|
||||
path=request.path,
|
||||
).error(
|
||||
"HTTP request failed method={} path={} duration_ms={}",
|
||||
request.method,
|
||||
request.path,
|
||||
duration_ms,
|
||||
)
|
||||
raise
|
||||
|
||||
duration_ms = round((time.perf_counter() - started_at) * 1000, 1)
|
||||
request_log = logger.bind(
|
||||
event="http_request",
|
||||
outcome="success" if response.status < 400 else "error",
|
||||
duration_ms=duration_ms,
|
||||
method=request.method,
|
||||
path=request.path,
|
||||
status_code=response.status,
|
||||
)
|
||||
log_method = request_log.debug if request.path == "/health" else request_log.info
|
||||
log_method(
|
||||
"HTTP request completed method={} path={} status={} duration_ms={}",
|
||||
request.method,
|
||||
request.path,
|
||||
response.status,
|
||||
duration_ms,
|
||||
)
|
||||
return response
|
||||
|
||||
async def add_request_id_header(
|
||||
request: web.Request,
|
||||
response: web.StreamResponse,
|
||||
) -> None:
|
||||
request_id = request.get(_REQUEST_ID_KEY)
|
||||
if request_id:
|
||||
response.headers["X-Request-ID"] = request_id
|
||||
|
||||
@web.middleware
|
||||
async def auth_middleware(
|
||||
request: web.Request,
|
||||
@@ -515,7 +570,8 @@ def create_app(
|
||||
return _error_json(401, "Invalid API key")
|
||||
return await handler(request)
|
||||
|
||||
app.middlewares.append(auth_middleware)
|
||||
app.middlewares.extend((request_logging_middleware, auth_middleware))
|
||||
app.on_response_prepare.append(add_request_id_header)
|
||||
|
||||
app.router.add_post("/v1/chat/completions", handle_chat_completions)
|
||||
app.router.add_get("/v1/models", handle_models)
|
||||
|
||||
@@ -188,7 +188,9 @@ class NanobotDingTalkHandler(_CallbackHandlerBase):
|
||||
)
|
||||
return AckMessage.STATUS_OK, "OK"
|
||||
|
||||
self.channel.logger.info("Received message from {} ({}): {}", sender_name, sender_id, content)
|
||||
self.channel.logger.debug(
|
||||
"Received DingTalk message from {} ({})", sender_name, sender_id
|
||||
)
|
||||
|
||||
# Forward to Nanobot via _on_message (non-blocking).
|
||||
# Store reference to prevent GC before task completes.
|
||||
@@ -367,7 +369,7 @@ class DingTalkChannel(BaseChannel):
|
||||
if isawaitable(result):
|
||||
await result
|
||||
except Exception:
|
||||
self.logger.debug("DingTalk stream client close failed", exc_info=True)
|
||||
self.logger.opt(exception=True).debug("DingTalk stream client close failed")
|
||||
|
||||
async def _get_access_token(self) -> str | None:
|
||||
"""Get or refresh Access Token."""
|
||||
@@ -824,7 +826,6 @@ class DingTalkChannel(BaseChannel):
|
||||
permission checks before publishing to the bus.
|
||||
"""
|
||||
try:
|
||||
self.logger.info("inbound: {} from {}", content, sender_name)
|
||||
if not sender_id:
|
||||
self.logger.warning("dropping DingTalk message without a sender ID")
|
||||
return
|
||||
|
||||
@@ -536,7 +536,7 @@ class MatrixChannel(BaseChannel):
|
||||
try:
|
||||
response = await self.client.content_repository_config()
|
||||
except Exception:
|
||||
self.logger.error("Failed to fetch server upload limit", exc_info=True)
|
||||
self.logger.opt(exception=True).error("Failed to fetch server upload limit")
|
||||
return None
|
||||
upload_size = getattr(response, "upload_size", None)
|
||||
if isinstance(upload_size, int) and upload_size > 0:
|
||||
@@ -582,7 +582,7 @@ class MatrixChannel(BaseChannel):
|
||||
filesize=size_bytes,
|
||||
)
|
||||
except Exception:
|
||||
self.logger.error("Matrix media upload failed for {}", filename, exc_info=True)
|
||||
self.logger.opt(exception=True).error("Matrix media upload failed for {}", filename)
|
||||
return fail
|
||||
|
||||
is_tuple_result = isinstance(cast(object, upload_result), tuple)
|
||||
@@ -607,7 +607,9 @@ class MatrixChannel(BaseChannel):
|
||||
try:
|
||||
await self._send_room_content(room_id, content)
|
||||
except Exception:
|
||||
self.logger.error("Matrix room content send failed for room_id={}", room_id, exc_info=True)
|
||||
self.logger.opt(exception=True).error(
|
||||
"Matrix room content send failed for room_id={}", room_id
|
||||
)
|
||||
return fail
|
||||
return None
|
||||
|
||||
@@ -712,7 +714,9 @@ class MatrixChannel(BaseChannel):
|
||||
buf.text = previous_text
|
||||
if created_buf:
|
||||
self._stream_bufs.pop(stream_key, None)
|
||||
self.logger.error("Stream send/edit failed for chat_id={}", chat_id, exc_info=True)
|
||||
self.logger.opt(exception=True).error(
|
||||
"Stream send/edit failed for chat_id={}", chat_id
|
||||
)
|
||||
await self._stop_typing_keepalive(chat_id, clear_typing=True)
|
||||
raise
|
||||
|
||||
@@ -1011,7 +1015,9 @@ class MatrixChannel(BaseChannel):
|
||||
),
|
||||
)
|
||||
except Exception:
|
||||
self.logger.error("Matrix join request exception for room={}", room_id, exc_info=True)
|
||||
self.logger.opt(exception=True).error(
|
||||
"Matrix join request exception for room={}", room_id
|
||||
)
|
||||
return False
|
||||
if isinstance(resp, JoinError):
|
||||
self.logger.error("Matrix auto-join failed for room={}: {}", room_id, resp)
|
||||
@@ -1287,7 +1293,7 @@ class MatrixChannel(BaseChannel):
|
||||
except _MediaTooLargeError:
|
||||
raise
|
||||
except (aiohttp.ClientError, asyncio.TimeoutError, OSError):
|
||||
self.logger.warning("download failed for {}", mxc_url, exc_info=True)
|
||||
self.logger.opt(exception=True).warning("download failed for {}", mxc_url)
|
||||
return None
|
||||
|
||||
def _decrypt_media_bytes(self, event: MatrixMediaEvent, ciphertext: bytes) -> bytes | None:
|
||||
|
||||
@@ -1838,8 +1838,9 @@ async def test_send_handles_upload_exception_and_reports_failure(tmp_path) -> No
|
||||
client.room_send_calls[0]["content"]["body"]
|
||||
== "Please review.\n[attachment: broken.txt - upload failed]"
|
||||
)
|
||||
channel.logger.error.assert_called_once_with(
|
||||
"Matrix media upload failed for {}", "broken.txt", exc_info=True
|
||||
channel.logger.opt.assert_called_once_with(exception=True)
|
||||
channel.logger.opt.return_value.error.assert_called_once_with(
|
||||
"Matrix media upload failed for {}", "broken.txt"
|
||||
)
|
||||
|
||||
|
||||
@@ -1861,10 +1862,10 @@ async def test_attachment_room_send_error_logs_room_id(tmp_path) -> None:
|
||||
)
|
||||
|
||||
assert failure == "[attachment: report.txt - upload failed]"
|
||||
channel.logger.error.assert_called_once_with(
|
||||
channel.logger.opt.assert_called_once_with(exception=True)
|
||||
channel.logger.opt.return_value.error.assert_called_once_with(
|
||||
"Matrix room content send failed for room_id={}",
|
||||
"!room:matrix.org",
|
||||
exc_info=True,
|
||||
)
|
||||
|
||||
|
||||
@@ -2509,8 +2510,9 @@ async def test_send_delta_on_error_restores_buffer_and_raises(monkeypatch) -> No
|
||||
assert len(client.room_send_calls) == 1
|
||||
|
||||
assert len(client.typing_calls) == 1
|
||||
channel.logger.error.assert_called_once_with(
|
||||
"Stream send/edit failed for chat_id={}", "!room:matrix.org", exc_info=True
|
||||
channel.logger.opt.assert_called_once_with(exception=True)
|
||||
channel.logger.opt.return_value.error.assert_called_once_with(
|
||||
"Stream send/edit failed for chat_id={}", "!room:matrix.org"
|
||||
)
|
||||
|
||||
client.raise_on_send = False
|
||||
|
||||
@@ -624,10 +624,6 @@ class SignalChannel(BaseChannel):
|
||||
if not self._running:
|
||||
break
|
||||
|
||||
# Debug: log raw SSE lines (except keepalive pings)
|
||||
if line and line != ":":
|
||||
self.logger.debug("SSE line received: {}", line[:200])
|
||||
|
||||
# SSE format handling
|
||||
if isinstance(line, str): # pyright: ignore[reportUnnecessaryIsInstance]
|
||||
# Empty line signals end of event
|
||||
@@ -641,7 +637,6 @@ class SignalChannel(BaseChannel):
|
||||
if data is None:
|
||||
self.logger.warning("Ignoring non-object SSE event: {}", data_str[:200])
|
||||
continue
|
||||
self.logger.debug("SSE event parsed: {}", data)
|
||||
await self._handle_receive_notification(data)
|
||||
except json.JSONDecodeError as e:
|
||||
self.logger.warning(
|
||||
@@ -690,13 +685,10 @@ class SignalChannel(BaseChannel):
|
||||
|
||||
async def _handle_receive_notification(self, params: dict[str, Any]) -> None:
|
||||
"""Handle incoming message notification from signal-cli."""
|
||||
self.logger.debug("_handle_receive_notification called with: {}", params)
|
||||
async with self._safe_handle("receive notification", params):
|
||||
# Extract envelope from SSE notification: {"envelope": {...}}
|
||||
envelope = _as_json_object(params.get("envelope"))
|
||||
|
||||
self.logger.debug("Extracted envelope: {}", envelope)
|
||||
|
||||
if envelope is None:
|
||||
self.logger.debug("No envelope found in params")
|
||||
return
|
||||
@@ -814,7 +806,7 @@ class SignalChannel(BaseChannel):
|
||||
chat_id=chat_id,
|
||||
)
|
||||
|
||||
self.logger.debug("Signal message from {}: {}...", sender_number, content[:50])
|
||||
self.logger.debug("Received Signal message from {}", sender_number)
|
||||
|
||||
await self._start_typing(chat_id)
|
||||
try:
|
||||
|
||||
@@ -423,7 +423,7 @@ class WeixinChannel(BaseChannel):
|
||||
self.config.base_url = base_url
|
||||
return bool(self._token)
|
||||
except Exception:
|
||||
self.logger.error("Failed to load Weixin account state", exc_info=True)
|
||||
self.logger.opt(exception=True).error("Failed to load Weixin account state")
|
||||
return False
|
||||
|
||||
def _save_state(self, *, force: bool = False) -> None:
|
||||
|
||||
+3
-13
@@ -25,20 +25,10 @@ import typer # noqa: E402
|
||||
from loguru import logger # noqa: E402
|
||||
from typer.core import TyperGroup # noqa: E402
|
||||
|
||||
from nanobot.utils.log_config import configure_console_logging # noqa: E402
|
||||
|
||||
# Remove default handler and re-add with unified nanobot format
|
||||
logger.remove()
|
||||
_log_handler_id = logger.add(
|
||||
sys.stderr,
|
||||
format=(
|
||||
"<green>{time:YYYY-MM-DD HH:mm:ss}</green> | "
|
||||
"<level>{level: <5}</level> | "
|
||||
"<cyan>{extra[channel]}</cyan> | "
|
||||
"<level>{message}</level>"
|
||||
),
|
||||
level="INFO",
|
||||
colorize=None,
|
||||
filter=lambda record: record["extra"].setdefault("channel", "-") or True,
|
||||
)
|
||||
_log_handler_id = configure_console_logging(sys.stderr)
|
||||
|
||||
|
||||
from rich.console import Console # noqa: E402
|
||||
|
||||
@@ -7,6 +7,8 @@ import sys
|
||||
from contextlib import suppress
|
||||
|
||||
from nanobot.cli.process_identity import set_cli_process_identity
|
||||
from nanobot.utils.log_config import configure_console_logging
|
||||
from nanobot.utils.rotating_output import configure_background_output_from_env
|
||||
|
||||
_ROOT_OPTIONS = frozenset(
|
||||
{
|
||||
@@ -58,6 +60,7 @@ def _configure_windows_console() -> None:
|
||||
|
||||
def _run_agent(args: list[str], *, prog_name: str) -> None:
|
||||
"""Run the shared agent command without importing the complete CLI graph."""
|
||||
configure_console_logging(sys.stderr)
|
||||
import typer
|
||||
|
||||
from nanobot.cli.agent import agent
|
||||
@@ -70,6 +73,7 @@ def _run_agent(args: list[str], *, prog_name: str) -> None:
|
||||
|
||||
def main() -> None:
|
||||
"""Dispatch native TUI startup without importing the complete CLI graph."""
|
||||
configure_background_output_from_env()
|
||||
raw_args = sys.argv[1:]
|
||||
# Installed completion scripts call ``nanobot`` without positional arguments
|
||||
# and pass the request through this environment variable. Keep those requests
|
||||
|
||||
+2
-12
@@ -26,6 +26,7 @@ from nanobot.gateway.service import (
|
||||
GatewayServiceResult,
|
||||
ServiceManagerKind,
|
||||
)
|
||||
from nanobot.utils.log_config import add_console_log_sink
|
||||
from nanobot.webui.build import BuildMode
|
||||
|
||||
RuntimeConfigLoader = Callable[[str | None, str | None], Config]
|
||||
@@ -66,18 +67,7 @@ def create_gateway_app(
|
||||
if not verbose:
|
||||
return
|
||||
logger.remove(log_handler_id)
|
||||
logger.add(
|
||||
sys.stderr,
|
||||
format=(
|
||||
"<green>{time:YYYY-MM-DD HH:mm:ss}</green> | "
|
||||
"<level>{level: <5}</level> | "
|
||||
"<cyan>{extra[channel]}</cyan> | "
|
||||
"<level>{message}</level>"
|
||||
),
|
||||
level="DEBUG",
|
||||
colorize=None,
|
||||
filter=lambda record: record["extra"].setdefault("channel", "-") or True,
|
||||
)
|
||||
add_console_log_sink(sys.stderr, level="DEBUG")
|
||||
|
||||
def instance_for_selectors(
|
||||
*,
|
||||
|
||||
@@ -23,6 +23,14 @@ from typing import Any, Generic, Literal, TypeVar, cast
|
||||
|
||||
from filelock import FileLock
|
||||
|
||||
from nanobot.utils.rotating_output import (
|
||||
BACKGROUND_LOG_BACKUP_COUNT_ENV,
|
||||
BACKGROUND_LOG_MAX_BYTES_ENV,
|
||||
BACKGROUND_LOG_PATH_ENV,
|
||||
DEFAULT_BACKUP_COUNT,
|
||||
DEFAULT_MAX_BYTES,
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ProcessStartOptions:
|
||||
@@ -110,12 +118,17 @@ class ManagedProcessRuntime(Generic[_StartOptionsT]):
|
||||
self.paths.run_dir.mkdir(parents=True, exist_ok=True)
|
||||
self.paths.logs_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
child_env = os.environ.copy()
|
||||
child_env[BACKGROUND_LOG_PATH_ENV] = str(self.paths.log_path)
|
||||
child_env[BACKGROUND_LOG_MAX_BYTES_ENV] = str(DEFAULT_MAX_BYTES)
|
||||
child_env[BACKGROUND_LOG_BACKUP_COUNT_ENV] = str(DEFAULT_BACKUP_COUNT)
|
||||
with self.paths.log_path.open("a", encoding="utf-8") as log_handle:
|
||||
process = self._popen(
|
||||
command,
|
||||
stdin=subprocess.DEVNULL,
|
||||
stdout=log_handle,
|
||||
stderr=subprocess.STDOUT,
|
||||
env=child_env,
|
||||
**self._popen_platform_kwargs(),
|
||||
)
|
||||
self._owned_process = process
|
||||
@@ -229,10 +242,22 @@ class ManagedProcessRuntime(Generic[_StartOptionsT]):
|
||||
"""Return the last ``tail`` log lines."""
|
||||
if tail <= 0 or not self.paths.log_path.exists():
|
||||
return []
|
||||
try:
|
||||
lines = self.paths.log_path.read_text(encoding="utf-8", errors="replace").splitlines()
|
||||
except OSError:
|
||||
return []
|
||||
lines: list[str] = []
|
||||
paths = [
|
||||
self.paths.log_path,
|
||||
*(
|
||||
self.paths.log_path.with_name(f"{self.paths.log_path.name}.{index}")
|
||||
for index in range(1, DEFAULT_BACKUP_COUNT + 1)
|
||||
),
|
||||
]
|
||||
for path in paths:
|
||||
try:
|
||||
older_lines = path.read_text(encoding="utf-8", errors="replace").splitlines()
|
||||
except OSError:
|
||||
continue
|
||||
lines = older_lines + lines
|
||||
if len(lines) >= tail:
|
||||
break
|
||||
return lines[-tail:]
|
||||
|
||||
def follow_logs(self, *, tail: int = 200) -> int:
|
||||
@@ -241,17 +266,35 @@ class ManagedProcessRuntime(Generic[_StartOptionsT]):
|
||||
print(line)
|
||||
self.paths.logs_dir.mkdir(parents=True, exist_ok=True)
|
||||
self.paths.log_path.touch(exist_ok=True)
|
||||
handle = self.paths.log_path.open("r", encoding="utf-8", errors="replace")
|
||||
try:
|
||||
with self.paths.log_path.open("r", encoding="utf-8", errors="replace") as handle:
|
||||
try:
|
||||
handle.seek(0, os.SEEK_END)
|
||||
while True:
|
||||
line = handle.readline()
|
||||
if line:
|
||||
print(line.rstrip("\n"))
|
||||
elif self._log_file_replaced(handle):
|
||||
handle.close()
|
||||
handle = self.paths.log_path.open(
|
||||
"r", encoding="utf-8", errors="replace"
|
||||
)
|
||||
else:
|
||||
self._sleep(0.5)
|
||||
except KeyboardInterrupt:
|
||||
return 130
|
||||
except KeyboardInterrupt:
|
||||
return 130
|
||||
finally:
|
||||
handle.close()
|
||||
|
||||
def _log_file_replaced(self, handle: Any) -> bool:
|
||||
"""Return whether rotation replaced or truncated the followed log file."""
|
||||
try:
|
||||
opened = os.fstat(handle.fileno())
|
||||
current = self.paths.log_path.stat()
|
||||
same_file = (opened.st_dev, opened.st_ino) == (current.st_dev, current.st_ino)
|
||||
return not same_file or current.st_size < handle.tell()
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
def process_identity(self, pid: int) -> str | int | None:
|
||||
"""Return an identity that changes when an operating-system PID is reused."""
|
||||
|
||||
@@ -1750,7 +1750,7 @@ class SessionManager:
|
||||
self.save(session, fsync=True)
|
||||
flushed += 1
|
||||
except Exception:
|
||||
logger.warning("Failed to flush session {}", key, exc_info=True)
|
||||
logger.opt(exception=True).warning("Failed to flush session {}", key)
|
||||
return flushed
|
||||
|
||||
def invalidate(self, key: str) -> None:
|
||||
|
||||
@@ -275,7 +275,9 @@ async def maybe_generate_webui_title(
|
||||
retry_mode="standard",
|
||||
)
|
||||
except Exception:
|
||||
logger.debug("Failed to generate webui session title for {}", session_key, exc_info=True)
|
||||
logger.opt(exception=True).debug(
|
||||
"Failed to generate webui session title for {}", session_key
|
||||
)
|
||||
return False
|
||||
|
||||
title = clean_generated_title(response.content)
|
||||
@@ -650,10 +652,9 @@ class WebuiTurnCoordinator:
|
||||
session_message=public_metadata,
|
||||
)
|
||||
except (OSError, TypeError, ValueError):
|
||||
logger.warning(
|
||||
logger.opt(exception=True).warning(
|
||||
"Failed to persist session input {}",
|
||||
envelope["message_id"],
|
||||
exc_info=True,
|
||||
)
|
||||
await self.bus.publish_outbound(outbound_message_for_event(
|
||||
channel="websocket",
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
"""Shared configuration for human-readable nanobot logs."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from loguru import logger
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from loguru import Record
|
||||
|
||||
LOG_FORMAT = (
|
||||
"<green>{time:YYYY-MM-DDTHH:mm:ss.SSSZZ}</green> | "
|
||||
"<level>{level: <7}</level> | "
|
||||
"<cyan>{extra[channel]}</cyan> | "
|
||||
"<cyan>{extra[log_context]}</cyan> | "
|
||||
"<level>{extra[safe_message]}</level>"
|
||||
)
|
||||
|
||||
|
||||
def _single_line(value: object) -> str:
|
||||
return str(value).replace("\r", "\\r").replace("\n", "\\n")
|
||||
|
||||
|
||||
def prepare_log_record(record: "Record") -> bool:
|
||||
"""Populate display fields without altering the structured log record."""
|
||||
extra = record["extra"]
|
||||
extra.setdefault("channel", "-")
|
||||
extra["channel"] = _single_line(extra["channel"])
|
||||
extra["safe_message"] = _single_line(record["message"])
|
||||
|
||||
context: list[str] = []
|
||||
for label, field in (
|
||||
("request", "request_id"),
|
||||
("turn", "turn_id"),
|
||||
("session", "session_key"),
|
||||
):
|
||||
value = extra.get(field)
|
||||
if value not in (None, "", "-"):
|
||||
context.append(f"{label}={_single_line(value)}")
|
||||
extra["log_context"] = " ".join(context) or "-"
|
||||
return True
|
||||
|
||||
|
||||
def add_console_log_sink(stream: Any, *, level: str = "INFO") -> int:
|
||||
"""Add the standard nanobot console sink and return its handler id."""
|
||||
return logger.add(
|
||||
stream,
|
||||
format=LOG_FORMAT,
|
||||
level=level,
|
||||
colorize=None,
|
||||
filter=prepare_log_record,
|
||||
)
|
||||
|
||||
|
||||
def configure_console_logging(stream: Any, *, level: str = "INFO") -> int:
|
||||
"""Replace existing handlers with the standard nanobot console sink."""
|
||||
logger.remove()
|
||||
return add_console_log_sink(stream, level=level)
|
||||
@@ -0,0 +1,168 @@
|
||||
"""Bounded text output for detached nanobot processes."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
import threading
|
||||
from contextlib import suppress
|
||||
from pathlib import Path
|
||||
from typing import BinaryIO
|
||||
|
||||
BACKGROUND_LOG_PATH_ENV = "_NANOBOT_BACKGROUND_LOG_PATH"
|
||||
BACKGROUND_LOG_MAX_BYTES_ENV = "_NANOBOT_BACKGROUND_LOG_MAX_BYTES"
|
||||
BACKGROUND_LOG_BACKUP_COUNT_ENV = "_NANOBOT_BACKGROUND_LOG_BACKUP_COUNT"
|
||||
|
||||
DEFAULT_MAX_BYTES = 10 * 1024 * 1024
|
||||
DEFAULT_BACKUP_COUNT = 5
|
||||
|
||||
|
||||
class RotatingTextOutput(io.TextIOBase):
|
||||
"""A UTF-8 text stream that rotates a file before it exceeds its size cap."""
|
||||
|
||||
def __init__(self, path: Path, *, max_bytes: int, backup_count: int) -> None:
|
||||
super().__init__()
|
||||
self._path = path
|
||||
self._max_bytes = max(1, max_bytes)
|
||||
self._backup_count = max(0, backup_count)
|
||||
self._handle: BinaryIO | None = None
|
||||
self._size = 0
|
||||
self._lock = threading.RLock()
|
||||
|
||||
@property
|
||||
def encoding(self) -> str: # pyright: ignore[reportIncompatibleVariableOverride]
|
||||
return "utf-8"
|
||||
|
||||
@property
|
||||
def errors(self) -> str: # pyright: ignore[reportIncompatibleVariableOverride]
|
||||
return "replace"
|
||||
|
||||
def writable(self) -> bool:
|
||||
return True
|
||||
|
||||
def isatty(self) -> bool:
|
||||
return False
|
||||
|
||||
def fileno(self) -> int:
|
||||
with self._lock:
|
||||
self._ensure_open()
|
||||
assert self._handle is not None
|
||||
return self._handle.fileno()
|
||||
|
||||
def write(self, text: str) -> int:
|
||||
if not text:
|
||||
return 0
|
||||
data = text.encode(self.encoding, errors=self.errors)
|
||||
with self._lock:
|
||||
self._ensure_open()
|
||||
if self._size and self._size + len(data) > self._max_bytes:
|
||||
self._rotate()
|
||||
self._ensure_open()
|
||||
assert self._handle is not None
|
||||
self._handle.write(data)
|
||||
self._handle.flush()
|
||||
self._size += len(data)
|
||||
return len(text)
|
||||
|
||||
def flush(self) -> None:
|
||||
with self._lock:
|
||||
if self._handle is not None:
|
||||
self._handle.flush()
|
||||
|
||||
def close(self) -> None:
|
||||
with self._lock:
|
||||
if self._handle is not None:
|
||||
self._handle.close()
|
||||
self._handle = None
|
||||
super().close()
|
||||
|
||||
def _ensure_open(self) -> None:
|
||||
if self._handle is not None:
|
||||
return
|
||||
self._path.parent.mkdir(parents=True, exist_ok=True)
|
||||
size = self._path.stat().st_size if self._path.exists() else 0
|
||||
if size >= self._max_bytes:
|
||||
self._rotate()
|
||||
size = self._path.stat().st_size if self._path.exists() else 0
|
||||
self._handle = self._path.open("ab")
|
||||
self._size = size
|
||||
|
||||
def _rotate(self) -> None:
|
||||
if self._handle is not None:
|
||||
self._handle.flush()
|
||||
self._handle.close()
|
||||
self._handle = None
|
||||
|
||||
if self._backup_count == 0:
|
||||
try:
|
||||
self._path.unlink(missing_ok=True)
|
||||
self._size = 0
|
||||
except OSError:
|
||||
self._size = self._path.stat().st_size if self._path.exists() else 0
|
||||
return
|
||||
|
||||
try:
|
||||
oldest = self._backup_path(self._backup_count)
|
||||
oldest.unlink(missing_ok=True)
|
||||
for index in range(self._backup_count - 1, 0, -1):
|
||||
source = self._backup_path(index)
|
||||
if source.exists():
|
||||
source.replace(self._backup_path(index + 1))
|
||||
if self._path.exists():
|
||||
try:
|
||||
self._path.replace(self._backup_path(1))
|
||||
except PermissionError:
|
||||
# A Windows ``gateway logs --follow`` reader can prevent rename.
|
||||
# Copy and truncate preserves both retention and the live stream.
|
||||
shutil.copyfile(self._path, self._backup_path(1))
|
||||
self._path.open("wb").close()
|
||||
self._size = 0
|
||||
except OSError:
|
||||
# Logging must remain available even when rotation is temporarily blocked.
|
||||
self._size = self._path.stat().st_size if self._path.exists() else 0
|
||||
|
||||
def _backup_path(self, index: int) -> Path:
|
||||
return self._path.with_name(f"{self._path.name}.{index}")
|
||||
|
||||
|
||||
def _positive_int(value: str | None, default: int, *, minimum: int) -> int:
|
||||
try:
|
||||
return max(minimum, int(value or ""))
|
||||
except ValueError:
|
||||
return default
|
||||
|
||||
|
||||
def configure_background_output_from_env() -> RotatingTextOutput | None:
|
||||
"""Replace inherited output handles when launched by ``ManagedProcessRuntime``."""
|
||||
raw_path = os.environ.pop(BACKGROUND_LOG_PATH_ENV, "")
|
||||
if not raw_path:
|
||||
return None
|
||||
max_bytes = _positive_int(
|
||||
os.environ.pop(BACKGROUND_LOG_MAX_BYTES_ENV, None),
|
||||
DEFAULT_MAX_BYTES,
|
||||
minimum=1,
|
||||
)
|
||||
backup_count = _positive_int(
|
||||
os.environ.pop(BACKGROUND_LOG_BACKUP_COUNT_ENV, None),
|
||||
DEFAULT_BACKUP_COUNT,
|
||||
minimum=0,
|
||||
)
|
||||
stream = RotatingTextOutput(
|
||||
Path(raw_path),
|
||||
max_bytes=max_bytes,
|
||||
backup_count=backup_count,
|
||||
)
|
||||
|
||||
replaced = {id(output): output for output in (sys.stdout, sys.stderr)}
|
||||
sys.stdout = stream
|
||||
sys.stderr = stream
|
||||
sys.__stdout__ = stream
|
||||
sys.__stderr__ = stream
|
||||
for output in replaced.values():
|
||||
with suppress(Exception):
|
||||
output.flush()
|
||||
with suppress(Exception):
|
||||
output.close()
|
||||
return stream
|
||||
Reference in new issue
Block a user