[英]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();
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
},
"LogFilePath": "Logs\\log-{Date}.txt"
},
var loggerFactory = app.Services.GetService<ILoggerFactory>();
loggerFactory.AddFile(builder.Configuration["Logging:LogFilePath"].ToString());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.