繁体   English   中英

如何使用 .NET Core 6 将日志详细信息写入文件

[英]How to write log details to a file using .NET Core 6

I just want to know, How to save log details in specific file using .NET 6. Here I have created a new ASP.NET Core 6 Web API project using Visual Studio 2022. Previously I used StartUp.cs class to configure logs, but with VS 2022 ,不再有StartUp class。

如何在Program.cs class 中编写代码?

var builder = WebApplication.CreateBuilder(args);
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>();

// Log Details (Using this path I want to save my all log details)
var path = Directory.GetCurrentDirectory();

// 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();

我认为使用默认日志记录选项是不可能的。 但是使用Serilog库,您可以实现您正在寻找的东西

var builder = WebApplication.CreateBuilder(args);

Log.Logger = new LoggerConfiguration()
    .MinimumLevel.Debug()
    .WriteTo.File($"Logs/{Assembly.GetExecutingAssembly().GetName().Name}.log")
    .WriteTo.Console()
    .CreateLogger();
builder.Logging.ClearProviders();
builder.Logging.AddSerilog();
  • 右键单击您的项目并选择 Mange NuGet Package.in 浏览选项卡,搜索“Serilog.Extensions.Logging.File”并安装它。
  • 在 appsetting.json 添加以下代码段
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    },
    "LogFilePath": "Logs\\log-{Date}.txt"
  },
  • 在 Program.cs class 中,在 builder.Build() 之后添加以下代码段
    var loggerFactory = app.Services.GetService<ILoggerFactory>();
loggerFactory.AddFile(builder.Configuration["Logging:LogFilePath"].ToString());    
  • 构建您的项目并运行它。 您将在项目的根目录中找到 Logs 文件夹。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM