agilelabs-fx-docs main topics/details/fundamentals/bootstraper/overview.md

AppBootstrapper 引导流程

AppBootstrapper 负责创建 Bootstrap Logger、Activity、捕获异常,并在宿主启动早期提供诊断能力。

SafeStartAsync

核心入口 AppBootstrapper.SafeStartAsync(Func<ILogger, CancellationToken, Task<int>> run, ...) 会:

  1. 创建 BootstrapLogger(Serilog),输出启动阶段日志。
  2. 生成启动 Activity:ActivitySource "AgileLabs.AppBootstrapTracing"
  3. 捕获未处理异常,写入引导日志目录。
  4. 在 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 使用滚动文件策略,retainedFileCountLimit10
  • 支持通过 AG_APP_DATA 自定义 app_data 根目录,从而影响默认引导日志目录。
  • Bootstrap Logger 用于 Host/DI 建立前后的启动阶段;运行期日志由 Serilog Provider 和 ASP.NET Core Logging 承接。

Activity 源

  • AppBootstrapper.AppBootstrapSource:在 SafeStartAsyncCreateHostAsyncConfigureServicesConfigureWebApplication 等阶段打点。
  • 配合默认 ActivityListener,可以在日志/监控系统中还原整个启动流程。

自定义日志行为

可以在 AppBuildOptions.BootstrapLoggerConfiguration 中追加 Sink,例如推送到 Seq/Elastic:

options.BootstrapLoggerConfiguration = logger =>
{
    logger.WriteTo.Console().WriteTo.Seq("http://seq:5341");
};

BootstrapLoggerConfiguration 只影响启动期 Bootstrap Logger。接口请求、后台任务和业务代码中的运行期日志,应通过 Serilog 配置、UseSerilogProviderConfigureLoggingBuilderILogger<T> 处理。

启动失败时怎么查

  1. 先看控制台是否输出 boot log output dir,确认 bootlog 目录。
  2. 打开最新 bootlog_*.txt,搜索 Host terminated unexpectedlyCriticalException
  3. 根据日志阶段判断失败位置:CreateHostConfigureServicesConfigureWebApplicationConfigureRequestPipeline
  4. 如果服务已经启动但请求失败,切到运行期日志和诊断端点排查。

常见问题

  1. 为什么还没进入 ASP.NET Core 日志就需要 Logger?
    • 启动早期(依赖注入容器尚未构建)也可能抛出异常,例如配置文件缺失、连接字符串错误。Bootstrap Logger 能提供第一手信息。
  2. 如何调整日志级别?
    • 设置环境变量 LOG_MINI_LEVEL=Debug 或直接操作 LoggingLevelControl.LevelSwitch.MinimumLevel
  3. 如何定位启动卡顿?
    • 结合 Activity 时间线,查看 ConfigureServicesConfigureWebApplication 是否耗时异常。

下一步:了解 AgileLabApplication日志策略排查启动、日志与诊断问题