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

Viewed 304

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, there is no StartUp class anymore.

How can I write code in the 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();
2 Answers

I don't think it is possible with the default logging options. But with the library Serilog, you can achieve what you are looking for

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();
  • Right lick you project and choose Mange NuGet Package.in browse tab, search for "Serilog.Extensions.Logging.File" and install it.
  • in appsetting.json add the below snippet
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    },
    "LogFilePath": "Logs\\log-{Date}.txt"
  },
  • in Program.cs class, after builder.Build() add the below snippet
    var loggerFactory = app.Services.GetService<ILoggerFactory>();
loggerFactory.AddFile(builder.Configuration["Logging:LogFilePath"].ToString());    
  • build your project and run it. you will find the Logs folder in the root directory of your project.
Related