fix: 修正异步运行时隔离并更新使用与迁移说明

This commit is contained in:
2026-03-21 18:40:16 +08:00
parent 8023bfe328
commit 2d6bbcbc9b
16 changed files with 635 additions and 319 deletions
+15 -3
View File
@@ -83,9 +83,17 @@ defer starlog.Shutdown(ctx)
说明:
- `Shutdown(ctx)` 会等待异步 handler drain,并统一关闭资源。
- `Shutdown(ctx)` 会等待当前 logger 的异步 handler drain,并统一关闭资源。
- `Close()` 仍可用,但不等待异步 handler 队列。
如果项目里主要使用自定义 logger,推荐直接写成:
```go
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
defer log.Shutdown(ctx)
```
## 常见旧写法到推荐写法
1. 配置项逐条 setter
@@ -106,6 +114,9 @@ defer starlog.Shutdown(ctx)
6.`StartArchive` 轮转启动
推荐:`StartRotatePolicy` / `StartManagedRotatePolicy`,模板场景可直接用 `StartRotateByTime/BySize/ByTimeSize`
7. 包级异步观测/回调入口
推荐:自定义 logger 优先使用实例方法,例如 `log.SetAsyncErrorHandler(...)``log.SetWriteErrorHandler(...)``log.GetAsyncDropCount()``log.GetWriteErrorCount()``log.Shutdown(ctx)`
## 旧 API 仍可用(重要)
以下旧/兼容路径当前仍可用:
@@ -114,6 +125,7 @@ defer starlog.Shutdown(ctx)
- 历史错拼兼容名仍可用(如 `EnbaleWrite``IsWriteStoed``HookBeforArchive`
- `Archive` 旧模型仍可用(建议新代码优先 `RotatePolicy`
- 旧生命周期入口仍可用(如 `CloseStd``Close`),但建议新代码优先 `Shutdown(ctx)` / `CloseLogFile`
- 包级异步/错误统计入口仍可用,但默认绑定全局 `Std` logger;自定义 logger 建议改用实例方法
## 升级后验证建议
@@ -123,7 +135,7 @@ defer starlog.Shutdown(ctx)
4. 重点验证:
- 级别过滤是否符合预期
- 归档文件数量/保留策略
- 异步丢弃计数和写入错误计数
- 异步丢弃计数和写入错误计数是否落在预期 logger 上
## 何时需要进一步迁移
@@ -135,5 +147,5 @@ defer starlog.Shutdown(ctx)
---
如果你希望,我可以基于你当前项目的实际日志初始化代码,给出一份“一次改完可落地”的迁移 patch 方案
自定义 logger 较多的项目,建议优先检查包级异步观测入口是否仍在使用,并逐步替换为实例方法
+17 -2
View File
@@ -421,9 +421,17 @@ log.SetPendingWriteLimit(1024)
log.SetPendingDropPolicy(starlog.PendingDropOldest)
```
说明:
- 每个 `StarLogger` 都有独立的异步运行时。
- `SetHandler``SetEntryHandler``SetAsyncErrorHandler``SetWriteErrorHandler``GetAsyncDropCount``GetWriteErrorCount``GetAsyncMetrics``Shutdown(ctx)` 都作用于当前 logger。
- 包级入口(如 `starlog.SetAsyncErrorHandler``starlog.GetAsyncDropCount``starlog.Shutdown(ctx)`)保留兼容,默认作用于全局 `Std` logger。
可观测项:
- `GetAsyncMetrics()`
- `GetAsyncDropCount()`
- `GetWriteErrorCount()`
- `GetPendingStats()`
## 11. 高频防爆(去重 / 采样 / 限流)
@@ -477,6 +485,8 @@ _ = snapshot
常用统计:
- `GetMetricsSnapshot()`
- `GetAsyncMetrics()`
- `GetPendingStats()`
- `GetSamplingStats()`
- `GetDedupStats()`
@@ -491,7 +501,7 @@ _ = snapshot
- `Flush()`:刷写 pending
- `Sync()``Flush + 底层 Sync()`(若支持)
- `Close()`:关闭资源,不等待异步队列 drain
- `Shutdown(ctx)`:等待异步 drain,再关闭资源
- `Shutdown(ctx)`:等待当前 logger 的异步 drain,再关闭资源
推荐:
@@ -501,7 +511,11 @@ defer cancel()
defer log.Shutdown(ctx)
```
全局 logger 可使用:`starlog.Shutdown(ctx)`
说明:
- 自定义 logger 优先使用 `log.Shutdown(ctx)`
- 全局 logger 可使用 `starlog.Shutdown(ctx)`
- `WaitAsyncDrain(ctx)` 作为兼容入口保留,默认等待全局 `Std` logger 的异步队列;自定义 logger 退出时直接使用 `log.Shutdown(ctx)` 更明确。
## 15. 标准库桥接
@@ -678,6 +692,7 @@ func main() {
- 显示回调链路:可能因超时或队列满发生丢弃,可通过计数观测
- writer/sink 主写链路:只要未被过滤(级别/去重/采样/限流)且写入正常,会落盘
- 多个自定义 logger 之间的异步丢弃计数、写入错误计数和关闭流程彼此独立
### Q3:新项目应该选 `Archive` 还是 `RotatePolicy`