adams85 / filelogger

A lightweight yet feature-rich file logger implementation for the Microsoft.Extensions.Logging framework.
MIT License
147 stars 22 forks source link

I follow your instrcution in program.cs and everything works fine however #24

Closed sandycs-protoss closed 1 year ago

sandycs-protoss commented 1 year ago

I'm running a WEBAPI in ASP.NET CORE 7.0 however I need to code them again in every controller. The logging service provide by ASP.NET Core can be setting in program.cs and nothing is need to be done in the controller.

public apiController(ILogger logger) { var configuration = new ConfigurationBuilder() .AddJsonFile("appsettings.json") .Build();

        var services = new ServiceCollection();

        services.AddLogging(builder =>
        {
            builder.AddConfiguration(configuration.GetSection("Logging"));
            // the "standard" provider which logs all messages with severity warning or above to 'warn+err.log' (see appsettings.json for configuration settings)
            builder.AddFile(o => o.RootPath = AppContext.BaseDirectory);
            // a custom one which only logs messages with level information or below to 'info.log'
            builder.AddFile<InfoFileLoggerProvider>(configure: o => o.RootPath = AppContext.BaseDirectory);
        });

        using (ServiceProvider sp = services.BuildServiceProvider())
        {
            // create logger factory
            _logger = sp.GetRequiredService<ILoggerFactory>().CreateLogger<apiController>();
        }
    }

The apicontroller is one of the controller. In the logging service provice by ASP.NET Core, I just need to use the logger in the parameter. Am I do anything wrong?

adams85 commented 1 year ago

Based on your code sample, you register the file logger provider in your controllers into separate DI containers than the ASP.NET Core controller. Instead of this, you need to register the logger provider only once in your Program.cs.

Please refer to the ASP.NET Core 6+ application (minimal hosting model) section of the configuration guide for .NET 5+.