weikio / PluginFramework

Everything is a Plugin in .NET
MIT License
538 stars 101 forks source link

LoggerFactory #49

Closed satishviswanathan closed 2 years ago

satishviswanathan commented 3 years ago

Is there a way I can set the logger factory so that the internal logs can be viewed in case of any error in loading the plugins or it's dependencies.

I'm trying to understand the different options to integrate in my project. Once again thank you for sharing this project !

mikoskinen commented 3 years ago

Hi @satishviswanathan. One option for configuring LoggerFactory is shown in the following sample: https://github.com/weikio/PluginFramework/tree/master/samples/WebAppWithNuget

In this sample we have the following custom logger:

public class NugetLogger : LoggerBase
{
    private readonly ILogger<NugetLogger> _logger;

    public NugetLogger(IServiceCollection serviceCollection)
    {
        var provider = serviceCollection.BuildServiceProvider();
        _logger = (ILogger<NugetLogger>) provider.GetService(typeof(ILogger<NugetLogger>));
    }

    public override void Log(ILogMessage message)
    {
        switch (message.Level)
        {
            case LogLevel.Debug:
                _logger.LogDebug(message.ToString());
                break;

            case LogLevel.Verbose:
                _logger.LogTrace(message.ToString());
                break;

            case LogLevel.Information:
                _logger.LogInformation(message.ToString());
                break;

            case LogLevel.Minimal:
                _logger.LogTrace(message.ToString());
                break;

            case LogLevel.Warning:
                _logger.LogWarning(message.ToString());
                break;

            case LogLevel.Error:
                _logger.LogError(message.ToString());
                break;
        }
    }

    public override Task LogAsync(ILogMessage message)
    {
        Log(message);

        return Task.CompletedTask;
    }
}

And to use that we configure the LoggerFactory in ConfigureServices:

    public void ConfigureServices(IServiceCollection services)
    {
        NugetPluginCatalogOptions.Defaults.LoggerFactory = () => new NugetLogger(services);
        ....

Hope this helps :)

satishviswanathan commented 2 years ago

That worked !!