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

.NET Core 6如何将日志详情写入指定文件(Program.cs配置)

在ASP.NET Core 6的Program.cs中配置文件日志

ASP.NET Core 6采用顶级语句模式,不再需要Startup.cs,日志配置直接在WebApplication.CreateBuilder阶段完成。要将日志详情保存到指定路径的文件中,最简便且常用的方案是使用Serilog日志框架,以下是具体步骤:

步骤1:安装NuGet包

打开项目的NuGet包管理器,安装以下两个包:

  • Serilog.AspNetCore:Serilog与ASP.NET Core的集成包
  • Serilog.Sinks.File:Serilog的文件输出接收器

步骤2:修改Program.cs配置日志

在你现有代码的基础上,添加Serilog的配置逻辑,指定日志文件的存储路径。修改后的完整代码如下:

using Serilog;

var builder = WebApplication.CreateBuilder(args);

// 配置日志文件路径:当前目录下的Logs文件夹,按日期生成滚动日志文件
var logDirectory = Path.Combine(Directory.GetCurrentDirectory(), "Logs");
if (!Directory.Exists(logDirectory))
{
    Directory.CreateDirectory(logDirectory);
}
var logFilePath = Path.Combine(logDirectory, "app-.log");

// 配置Serilog,将日志写入文件并按日期滚动
builder.Host.UseSerilog((context, config) =>
{
    config
        .MinimumLevel.Information() // 设置最低日志级别
        .WriteTo.File(
            path: logFilePath,
            rollingInterval: RollingInterval.Day, // 按天生成新日志文件
            retainedFileCountLimit: 30, // 保留最近30天的日志
            outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}" // 日志格式,包含时间、级别、消息和异常详情
        );
});

builder.Services.AddDbContext<StudentDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("StudentDbContext")
    ?? throw new InvalidOperationException("Connection string 'StudentDbContext' not found.")));

// Add services to the container.

builder.Services.AddControllers();
builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());

builder.Services.AddScoped<IStudentRepository, StudentService>();

// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();

app.Run();

关键配置说明

  • 日志路径:代码中会自动创建当前目录下的Logs文件夹,避免路径不存在导致的报错
  • 滚动日志:通过rollingInterval: RollingInterval.Day设置按天生成新的日志文件,避免单个文件体积过大
  • 日志格式:outputTemplate定义了日志的输出内容,包含时间戳、日志级别、消息和异常堆栈信息,方便排查问题
  • 日志级别:MinimumLevel.Information表示只记录Information级别及以上的日志,可根据需求调整为Debug(开发环境)或Warning(生产环境)

验证日志

运行项目后,你会在项目根目录的Logs文件夹下看到以app-yyyyMMdd.log命名的日志文件,所有符合级别的日志都会被写入其中。

内容的提问来源于stack exchange,提问作者Sandanuwan Dharmarathna

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 21:33:23