AppBootstrapper 引导流程
AppBootstrapper 负责创建 Bootstrap Logger、Activity、捕获异常,并在宿主启动早期提供诊断能力。
SafeStartAsync
核心入口 AppBootstrapper.SafeStartAsync(Func<ILogger, CancellationToken, Task<int>> run, ...) 会:
- 创建
BootstrapLogger(Serilog),输出启动阶段日志。 - 生成启动 Activity:
ActivitySource "AgileLabs.AppBootstrapTracing"。 - 捕获未处理异常,写入引导日志目录。
- 在 finally 中关闭日志、清理资源。
Bootstrap Logger
var loggerConfiguration = new LoggerConfiguration()
.MinimumLevel.ControlledBy(LoggingLevelControl.LevelSwitch)
.WriteTo.Console(...);
- 默认输出模版:
[{Timestamp} {TraceId} {SpanId}[{ParentId}] {Level}] {SourceContext} {Message}。 - bootlog 默认目录来自
AppData.GetPath("bootlog"),可通过AppBuildOptions.BoostrapLogPath覆盖。 - bootlog 文件名形如
bootlog_{yyyyMMdd_HHmmss}_{MachineName}.txt。 - bootlog 使用滚动文件策略,
retainedFileCountLimit为10。 - 支持通过
AG_APP_DATA自定义app_data根目录,从而影响默认引导日志目录。 - Bootstrap Logger 用于 Host/DI 建立前后的启动阶段;运行期日志由 Serilog Provider 和 ASP.NET Core Logging 承接。
Activity 源
AppBootstrapper.AppBootstrapSource:在SafeStartAsync、CreateHostAsync、ConfigureServices、ConfigureWebApplication等阶段打点。- 配合默认
ActivityListener,可以在日志/监控系统中还原整个启动流程。
自定义日志行为
可以在 AppBuildOptions.BootstrapLoggerConfiguration 中追加 Sink,例如推送到 Seq/Elastic:
options.BootstrapLoggerConfiguration = logger =>
{
logger.WriteTo.Console().WriteTo.Seq("http://seq:5341");
};
BootstrapLoggerConfiguration 只影响启动期 Bootstrap Logger。接口请求、后台任务和业务代码中的运行期日志,应通过 Serilog 配置、UseSerilogProvider、ConfigureLoggingBuilder 或 ILogger<T> 处理。
启动失败时怎么查
- 先看控制台是否输出
boot log output dir,确认 bootlog 目录。 - 打开最新
bootlog_*.txt,搜索Host terminated unexpectedly、Critical、Exception。 - 根据日志阶段判断失败位置:
CreateHost、ConfigureServices、ConfigureWebApplication、ConfigureRequestPipeline。 - 如果服务已经启动但请求失败,切到运行期日志和诊断端点排查。
常见问题
- 为什么还没进入 ASP.NET Core 日志就需要 Logger?
- 启动早期(依赖注入容器尚未构建)也可能抛出异常,例如配置文件缺失、连接字符串错误。Bootstrap Logger 能提供第一手信息。
- 如何调整日志级别?
- 设置环境变量
LOG_MINI_LEVEL=Debug或直接操作LoggingLevelControl.LevelSwitch.MinimumLevel。
- 设置环境变量
- 如何定位启动卡顿?
- 结合 Activity 时间线,查看
ConfigureServices、ConfigureWebApplication是否耗时异常。
- 结合 Activity 时间线,查看
下一步:了解 AgileLabApplication、日志策略 与 排查启动、日志与诊断问题。