avechuche
avechuche

Reputation: 1560

Serilog from ASP.net Core API Controller

I am trying to add serilog to my api (asp net core) and I can not do it as I want. I have 2 examples: 1) This example works as I want, I only write in the ".txt" file what I need but I can not get it to work from a Controller

//Program.cs
public static void Main(string[] args)
{
    var logger = new LoggerConfiguration()
        .ReadFrom.Configuration(new ConfigurationBuilder()
            .AddJsonFile("appsettings.json")
            .Build())
        .CreateLogger();

    logger.Information("Hello, world!");

    CreateWebHostBuilder(args).Build().Run();
}

//Output

2018-07-02 18:17:18.210 -03:00 [INF] Hello, world!

2) This example works from a controller, but every time I want to write in the ".txt", it writes all the output of the VisualStudio console.

//Program.cs
public static void Main(string[] args)
{
    Log.Logger = new LoggerConfiguration()
    .ReadFrom.Configuration(new ConfigurationBuilder()
        .AddJsonFile("appsettings.json")
        .Build())
    .CreateLogger();

    CreateWebHostBuilder(args).Build().Run();
}

//Startup.cs
loggerFactory.AddSerilog();

//Controller
private readonly ILogger<ValuesController> _logger;

public ValuesController(ILogger<ValuesController> logger)
{
    _logger = logger;
}

[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
    _logger.LogInformation("Test");
    return new[] { "value1", "value2" };
}

Upvotes: 0

Views: 3718

Answers (1)

Edward
Edward

Reputation: 29986

If you check the output .txt, will there be any log? I suggest you follow steps below to modify your project.

  1. Comment out loggerFactory.AddSerilog(); which is pointed at Serilog
  2. Run install-package Serilog.Sinks.File which is used to write log to file.

Upvotes: 1

Related Questions