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

2

10

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();
National answered 16/7, 2022 at 12:55 Comment(2)
The documentation states what must be done to accomplish this. Always check the documentation before asking! Read through it, pick an approach, try it out. If it doesn't work, you can tell us what you've tried and clearly explain how it's not working.Gorgerin
The documentation says ASP.NET Core doesn't include a logging provider for writing logs to files. Consider using a third-party logging provider to write logs to files from an ASP.NET Core app.Consumerism
L
16

You can log to file by using "Serilog.Extensions.Logging.File" NuGet:

  • Right lick your project and choose Mange NuGet Package.in browse tab, search for "Serilog.Extensions.Logging.File" and install it.
  • in appsettings.json add the below snippet
"Logging": {
    "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.

You can log any thing you need in your controller or service, just inject ILogger interface in your constructor as below.

 private readonly ILogger<HomeController> _logger;
 public HomeController(ILogger<HomeController> logger)
        {
            _logger = logger;
        }

Here are examples to log any thing like your process steps, information, warning in any place or exception in catch block. Example of information logging:

_logger.LogInformation("API started at:"+DateTime.Now); 

Example of exception logging in catch block:

_logger.LogError(ex, ex.Message);
Lobectomy answered 1/9, 2022 at 11:8 Comment(7)
Can you please explain it after configuring as you said what code i use to log in file ? ex. log.warning() / log.error()Gapeworm
You can log any thing you need, like steps, information and exception in catch block. Example of information logging: _logger.LogInformation($"API started at:{DateTime.Now}"); Example of exception logging in catch block: _logger.LogError(ex, $"{ex.Message} - {ex.InnerException?.Message}");Lobectomy
Please fix the JSON. Doesn't seem to jive with what's in the appSettings.json alreadyCatkin
appsettings.jsonLobectomy
where did _logger comes from?Ganef
Don't use string interpolation for log messages, take advantage of the built-in structured logging, especially with Serilog that was intended to accept structured messagingDrescher
@AlexS. just inject ILogger interface in your constructor. I had updated the answerLobectomy
P
1

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();
Paulapauldron answered 16/7, 2022 at 13:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.