> For the complete documentation index, see [llms.txt](https://docs.convai.com/api-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/advanced-topics/performance-and-optimization.md).

# 日志、指标和重试策略

按子系统配置 SDK 日志详细程度，将日志发送到自定义接收端，读取 RTVI 管线延迟指标，并调整连接重试策略。

Convai Unity SDK 提供的默认设置适用于训练模拟、交互式体验和游戏。当你需要诊断延迟、减少生产环境中的日志噪声、了解 AI 流水线的耗时，或调整重连行为时，本页介绍了可用的控制选项。

**跳转到所需主题：**

* [日志级别配置](#log-level-configuration) — 减少生产版本中的控制台噪声
* [自定义日志接收器](#custom-log-sinks) — 将日志发送到文件或远程服务
* [RTVI 服务端调试指标](#rtvi-server-side-debug-metrics) — 测量每轮 AI 流水线延迟
* [重试策略](#retry-policy) — 为不稳定的网络调整重连行为

***

### 日志级别配置

#### 日志级别

| 级别        | 枚举值 | 适用场景                 |
| --------- | --- | -------------------- |
| `Off`     | `0` | 禁用所有 SDK 日志。         |
| `Error`   | `1` | 生产版本 — 仅记录错误。        |
| `Warning` | `2` | 预发布阶段 — 记录警告和错误。     |
| `Info`    | `3` | **默认值。** 常规运行消息。     |
| `Debug`   | `4` | 积极开发阶段 — 详细记录生命周期事件。 |
| `Trace`   | `5` | 深度调试 — 高频记录内部状态。     |

这些值对应于 `Convai.Domain.Logging.LogLevel` 枚举。

{% hint style="warning" %}
`Trace` 和 `Debug` 级别会产生大量输出。Unity Editor 和 Development Builds 中会启用 SDK 调试日志。在发布版本中，编译器会将其剥离，除非将 `CONVAI_DEBUG_LOGGING` 添加到 Scripting Define Symbols。请勿在发布时启用 `Trace` 。
{% endhint %}

#### 在 Inspector 中配置

打开 **Project Settings → Convai** （或选择位于 `ConvaiSettings` 的资源 `Assets/Resources/ConvaiSettings.asset`）。在 **Logging** 部分中：

| 字段                     | 说明                             |
| ---------------------- | ------------------------------ |
| `Global Log Level`     | 所有 SDK 子系统的最低日志级别。             |
| `Include Stack Traces` | 在 Warning 和 Error 消息中附加堆栈跟踪。   |
| `Colored Output`       | 在 Unity Console 中为日志消息添加颜色。    |
| `Category Overrides`   | 按子系统覆盖级别 — 添加条目，为特定类别设置更精细的级别。 |

#### 日志类别

| 类别             | 子系统                            |
| -------------- | ------------------------------ |
| `SDK`          | 常规操作                           |
| `Character`    | 每个角色的会话生命周期                    |
| `Audio`        | 麦克风采集、播放、音频设备                  |
| `UI`           | UI 组件生命周期                      |
| `REST`         | REST API 通信                    |
| `Transport`    | WebRTC / WebSocket 连接层         |
| `Events`       | 内部事件总线                         |
| `Player`       | 玩家身份和输入                        |
| `Editor`       | 仅限编辑器的操作                       |
| `Vision`       | 摄像头采集和视频发布                     |
| `Bootstrap`    | SDK 启动和初始化                     |
| `Transcript`   | 转录处理和路由                        |
| `Narrative`    | 叙事设计系统                         |
| `LipSync`      | 口型同步处理和混合形状播放                  |
| `Animation`    | 身体动画系统 — 图层、过渡和移动              |
| `Gaze`         | 视线系统 — 目标定位、策略以及眼部/头部/身体求解器    |
| `BodyLanguage` | 肢体语言系统 — 手势、姿势、呼吸和小动作          |
| `Actions`      | 动作系统 — 收到哪些命令、哪些命令被丢弃，以及目标如何解析 |

这些值对应于 `Convai.Domain.Logging.LogCategory` 枚举。

#### 在运行时进行配置

```csharp
using Convai.Runtime;
using Convai.Domain.Logging;

// 设置全局级别 — 立即应用于之后的所有日志调用。
ConvaiSettings.Instance.SetGlobalLogLevel(LogLevel.Debug);

// 覆盖特定子系统的级别，不更改全局级别。
ConvaiSettings.Instance.SetCategoryOverrides(new[]
{
    new LogLevelOverride(LogCategory.Audio,     LogLevel.Debug),
    new LogLevelOverride(LogCategory.Transport, LogLevel.Warning)
});
```

`LogLevelOverride` 是一个包含两个字段的结构体： `LogCategory Category` 和 `LogLevel Level`.

#### `CONVAI_DEBUG_LOGGING` 脚本定义

`ConvaiLogger.Debug(...)` 调用受以下三个 `[Conditional]` 特性控制： `UNITY_EDITOR`, `DEVELOPMENT_BUILD`以及 `CONVAI_DEBUG_LOGGING`。如果未定义其中任何一个符号，编译器就会将这些调用从构建中剔除 — 在生产发布版本中不会产生任何开销。

若要在发布版本中启用调试日志，请将 `CONVAI_DEBUG_LOGGING` 添加到 **项目设置 → Player → Scripting Define Symbols**。开发版本会自动启用这些日志，无需定义此符号。

***

### 自定义日志接收器

实现 `ILogSink` 并注册它，即可将 SDK 日志输出路由到文件、远程日志服务或任意目标。 `ConvaiLogger`.

```csharp
// FileSink.cs
using System;
using System.IO;
using Convai.Domain.Logging;

public class FileSink : ILogSink
{
    private readonly StreamWriter _writer;

    public string Name      => "FileSink";
    public bool   IsEnabled { get; private set; } = true;

    public FileSink(string path)
        => _writer = new StreamWriter(path, append: true);

    public void Write(LogEntry entry)
        => _writer.WriteLine($"[{entry.Timestamp:HH:mm:ss.fff}] [{entry.Level}] [{entry.Category}] {entry.Message}");

    public void Flush()             => _writer.Flush();
    public void SetEnabled(bool en) => IsEnabled = en;
    public void Dispose()           => _writer?.Dispose();
}
```

在初始化 `ConvaiLogger` 之后注册：

```csharp
using Convai.Runtime.Logging;

// OnInitializationCompleted 在 ConvaiLogger 就绪时触发——始终在此处注册日志接收器，
// 不要提前注册，以免错过初始化时机。
ConvaiLogger.OnInitializationCompleted += _ =>
{
    string logPath = Path.Combine(Application.persistentDataPath, "convai_session.log");
    ConvaiLogger.RegisterSink(new FileSink(logPath));
};
```

**接收器生命周期：**

* `ILogSink` 继承自 `IDisposable` ——实现类必须提供 `Dispose()` 方法。
* 释放接收器之前，请调用 `ConvaiLogger.UnregisterSink(sink)` 。
* 在应用程序退出时调用 `ConvaiLogger.FlushAllSinks()` ，确保缓冲的日志条目已写入。

***

### RTVI 服务端调试指标

RTVI（实时语音交互）是 Convai 的会话协议。当 `ConvaiRoomManager.Debug` 为 `true`时，服务器会在每次 AI 轮次结束后向客户端传输管线指标，显示各个阶段（语音转文本、LLM、文本转语音等）耗时。需要确定管线中的瓶颈时可使用此功能——例如，AI 响应缓慢究竟是因为转录延迟，还是 LLM 生成耗时过长？

#### 启用调试指标

`ConvaiRoomManager.Debug` 是只读运行时属性。进入播放模式之前，请在 Inspector 中勾选 **调试** 复选框，该复选框位于 `ConvaiRoomManager` 组件上。

{% hint style="warning" %}
调试指标会为每次轮次带来少量开销。仅在性能分析期间勾选此选项；发布时请勿启用。
{% endhint %}

#### 读取指标

```csharp
// MetricsLogger.cs
using Convai.Runtime.Adapters.Networking;
using Convai.Infrastructure.Protocol.Messages;
using UnityEngine;

public class MetricsLogger : MonoBehaviour
{
    [SerializeField] private ConvaiRoomManager _roomManager;

    private void OnEnable()
        => _roomManager.OnRtvMetricsReceived += OnMetricsReceived;

    private void OnDisable()
        => _roomManager.OnRtvMetricsReceived -= OnMetricsReceived;

    private void OnMetricsReceived(RTVIMetricsPayload payload)
    {
        if (payload.Ttfb       != null) Debug.Log($"[Metrics] TTFB: {payload.Ttfb}");
        if (payload.Processing != null) Debug.Log($"[Metrics] Processing: {payload.Processing}");
        if (payload.Custom     != null) Debug.Log($"[Metrics] Custom: {payload.Custom}");
    }
}
```

#### 指标字段

| 字段           | 类型        | 说明                                                                          |
| ------------ | --------- | --------------------------------------------------------------------------- |
| `Ttfb`       | `JToken?` | 每个处理器的首字节时间（秒）。数组中包含 `{processor, value}` 条目。                               |
| `Processing` | `JToken?` | 本轮中每个处理器的总处理时长（秒）。                                                          |
| `Custom`     | `JToken?` | 特定于提供方的指标——格式因处理器而异（例如， `output_fps`, `blendshapes_received` 来自 NeuroSync）。 |

`Ttfb` 和 `Processing` 是原始 `JToken` 值（来自 `Newtonsoft.Json.Linq`，通过 `com.unity.nuget.newtonsoft-json` 包包含在 Unity 中）。将它们反序列化为 `payload.Ttfb.ToObject<List<MetricEntry>>()` 其中 `MetricEntry` 是与 `{processor, value}` 结构匹配的结构体。并非每轮都会包含所有类型的指标——访问前务必检查是否为 null。

***

### 重试策略

SDK 使用 `ExponentialBackoffPolicy` 处理暂时性连接故障。默认行为：

| 尝试次数    | 重试前的延迟 |
| ------- | ------ |
| 1（初始尝试） | 0 秒    |
| 2       | 1 秒    |
| 3       | 2 秒    |
| 4       | 4 秒    |

总共尝试 4 次后（1 次初始尝试 + 3 次重试），操作将失败。该策略只会对暂时性错误进行重试：超时、网络中断以及 `OperationCanceledException`。非暂时性错误（身份验证失败、配置无效）会立即失败。

#### 何时自定义重试策略

默认策略（尝试 4 次，指数退避，最长延迟为 4 秒）适用于大多数使用者的网络状况。以下情况可考虑自定义策略：

* **部署在工业或嵌入式硬件上** 且已知连接时断时续——请增加 `MaxAttempts` 和延迟间隔。
* **自助服务终端或常开式安装** ——更积极的重试策略（增加尝试次数、延长最大延迟）可避免短暂断网后需要用户介入。
* **低延迟训练环境** 且网络可靠——请减少 `MaxAttempts` 以便快速失败，并将错误显示在你自己的重新连接界面中，而不是静默重试。

如果只需增加尝试次数而不更改延迟曲线，请增加 `maxRetryAttempts` 在 `ConvaiBootstrapConfigSnapshot` 中——无需自定义策略。

#### 自定义重试策略

实现 `IRetryPolicy` 并使用 `RetryExecutor` 来包装任意异步操作：

```csharp
// AggressiveRetryPolicy.cs
using System;
using Convai.Runtime.Core.Policies;

public class AggressiveRetryPolicy : IRetryPolicy
{
    public int MaxAttempts => 6;

    public TimeSpan GetDelay(int attempt) => attempt switch
    {
        0 => TimeSpan.Zero,
        1 => TimeSpan.FromSeconds(2),
        2 => TimeSpan.FromSeconds(5),
        3 => TimeSpan.FromSeconds(10),
        4 => TimeSpan.FromSeconds(20),
        _ => TimeSpan.FromSeconds(30)
    };

    public bool ShouldRetry(Exception exception, int attempt)
    {
        if (attempt >= MaxAttempts) return false;
        return exception is TimeoutException
            || exception is System.Net.WebException
            || exception is OperationCanceledException;
    }
}
```

```csharp
using Convai.Runtime.Core.Policies;

var executor = new RetryExecutor(new AggressiveRetryPolicy());

await executor.ExecuteAsync(async (attempt, ct) =>
{
    Debug.Log($"Connection attempt {attempt + 1}...");
    await someAsyncOperation(ct);
    return true;
}, cancellationToken);
```

***

### 生产环境检查清单

* [ ] `Global Log Level` 设为 `Warning` 或 `Error` 在生产环境中 `ConvaiSettings` 资源。
* [ ] `CONVAI_DEBUG_LOGGING` **未** 包含在发布版本的 Scripting Define Symbols 中。
* [ ] `ConvaiRoomManager.Debug` 复选框 **未选中** 生产场景中。
* [ ] `maxRetryAttempts` 在 `ConvaiBootstrapConfigSnapshot` 适合目标网络（默认值 `3` 适用于大多数消费级网络连接）。
* [ ] `connectionTimeoutSeconds` 应考虑部署中目标设备/网络的最慢情况（默认值 `30` 秒）。
* [ ] 自定义 `ILogSink` 实例会在应用退出时注销并释放。
* [ ] `ConvaiLogger.FlushAllSinks()` 在 `Application.quitting` 处理程序中调用（如果有任何接收器会缓冲输出）。

***

### 故障排查

| 症状                             | 可能原因                                                                 | 解决方法                                                                            |
| ------------------------------ | -------------------------------------------------------------------- | ------------------------------------------------------------------------------- |
| 发布版本中控制台被 SDK 消息刷屏             | `CONVAI_DEBUG_LOGGING` 定义已存在，或者 `GlobalLogLevel` 为 `Debug` 或 `Trace` | 移除脚本定义，并将全局级别设为 `Warning` 或 `Error`.                                            |
| `OnRtvMetricsReceived` 从未触发    | `ConvaiRoomManager.Debug` 未选中，或角色尚未完成完整回合                            | 启用 Debug 复选框，并确认已完成一个完整的 AI 回合（用户说话，角色回应）。                                      |
| `Ttfb` / `Processing` 字段为 null | 服务器未在本轮中包含这些指标类型                                                     | 访问前先处理 null。并非每一轮都会包含所有指标类型。                                                    |
| 尝试 4 次后连接失败，且不再重试              | 默认值 `ExponentialBackoffPolicy` 已达到 `MaxAttempts = 4`                 | 增加 `maxRetryAttempts` 在 `ConvaiBootstrapConfigSnapshot`，或实现自定义的 `IRetryPolicy`. |
| 自定义日志接收器未捕获启动早期的消息             | 接收器注册时， `ConvaiLogger.Initialize()` 已执行                              | 通过 `OnInitializationCompleted` 回调进行注册——切勿在初始化完成前注册接收器。                          |

***

### 后续步骤

{% content-ref url="/pages/aed151614a7019028126be07590213a17602a2f2" %}
[故障排查](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/troubleshooting.md)
{% endcontent-ref %}

{% content-ref url="/pages/007b237f8ee6f8a26b307152ee716a33905cd6da" %}
[运行时模块系统](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/advanced-topics/extending-the-sdk.md)
{% endcontent-ref %}

{% content-ref url="/pages/c94f3576730a705ef8d7adec01d712a12612b542" %}
[实现自定义模块](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/advanced-topics/implement-a-custom-module.md)
{% endcontent-ref %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/advanced-topics/performance-and-optimization.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
