You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET6中Program.cs内Serilog数据库连接日志无法显示的问题

Program.cs中Serilog日志无法输出的问题

我在所有需要添加日志的类顶部都引入了using Serilog,Controller和Service类中的日志均正常输出,但在Program.cs中记录数据库连接相关的日志时,日志既不显示在控制台也不写入本地文件。

以下是我的appsettings.json中的Serilog配置:

"Serilog": {
    "MinimumLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    },
    "Enrich": [
      "FromLogContext"
    ],
    "WriteTo": [
      {
        "Name": "File",
        "Args": {
          "path": "../logs/dev/dev.log",
          "rollingInterval": "Day",
          "outputTemplate": "{Level:w5} [{Timestamp:yyyy-MM-dd HH:mm:ss,fff}] [{UserId}] [{ResourceId}] >> {Message}{NewLine}{Exception}"
        }
      },
      {
        "Name": "Console",
        "Args": {
          "outputTemplate": "{Level:w5} [{Timestamp:yyyy-MM-dd HH:mm:ss,fff}] [{UserId}] [{ResourceId}] >> {Message}{NewLine}{Exception}"
        }
      }
    ]
  }

以及Program.cs代码:

using MyProject.Repositories;
using MyProject.Services;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using Serilog;

namespace MyProject
{
    public class Program
    {
        private static string? env = String.Empty;
        private static string connect = String.Empty;
        public static void Main(string[] args)
        {
            // 从部署环境获取环境变量
            env = Environment.GetEnvironmentVariable("SERVER_ENVIRONMENT");

            if (string.IsNullOrEmpty(env))
            {
                env = "dev";
            }

            var builder = WebApplication.CreateBuilder(args);
            builder.Configuration.AddJsonFile("appsettings.json");
            builder.Configuration.AddJsonFile($"appsettings.{env}.json", true, true);

            builder.Host.UseSerilog((hostContext, services, configuration) =>
            {
                configuration.ReadFrom.Configuration(hostContext.Configuration);
            });

            // 添加服务到容器
            builder.Services.AddControllers();
            builder.Services.AddControllersWithViews();
            builder.Services.AddEndpointsApiExplorer();
            builder.Services.AddSwaggerGen();
            builder.Services.AddScoped<ILikeService, LikeService>();
            builder.Services.AddScoped<LdapService>();
            

            // 使用SQL Server
            if (env.Equals("dev"))
            {
                connect = builder.Configuration.GetConnectionString("Connection");
            }
            else if (env.Equals("pre") || env.Equals("prod"))
            {
                // 其他环境处理逻辑
            }



            /// 以下代码块的日志无法输出!-----------------------------------
            using (var connection = new SqlConnection(connect))
            {
                try
                {
                    // 无输出
                    Log.Debug("this is a debug msg");

                    // 无输出
                    Log.Information("Before testing connect...");
                    connection.Open();

                    // 无输出
                    Log.Information("Connection successful!");
                    Console.WriteLine("Success");
                }
                catch (Exception ex)
                {
                    // 无输出                    
                    Log.Error("Connection failed: {ErrorMessage}", ex.Message);
                    
                }
            }

//////-----------------------------------
            builder.Services.AddDbContext<LikeDbContext>(options =>
                options.UseSqlServer(connect));
            builder.Services.AddDatabaseDeveloperPageExceptionFilter();

            


            var app = builder.Build();

            // 配置HTTP请求管道
            if (!app.Environment.IsDevelopment())
            {
                app.UseHsts();
                app.UseSwagger();
                app.UseSwaggerUI();
            }

            app.UsePathBase("/my-app");
            app.UseWhen(context => context.Request.Path.StartsWithSegments("/api"), appBuilder =>
            {
                appBuilder.UseMiddleware<ApiHeaderMiddleware>();
            });

            app.UseStaticFiles();
            app.UseRouting();


            app.MapControllerRoute(
                name: "default",
                pattern: "{controller}/{action=Index}/{id?}");

            app.MapFallbackToFile("index.html");

            using (var scope = app.Services.CreateScope())
            {
                var services = scope.ServiceProvider;
                try
                {
                    var context = services.GetRequiredService<LikeDbContext>();
                }
                catch (Exception ex)
                {
                    var logger = services.GetRequiredService<ILogger<Program>>();
                    logger.LogError(ex, "An error occurred creating the DB.");
                }
            }

            app.Run();
        }
    }
}

我考虑是否要将该数据库连接代码块提取到类中并注入DI容器来解决问题。

内容的提问来源于stack exchange,提问作者Michael Chen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 19:27:41