将Serilog与Caliburn Micro .Net Core 3.1一起使用

问题描述 投票:0回答:1

我正在尝试将Serilog注入到.NET Core 3.1 WPF应用程序中的类和项目中。

我正在使用Calibun.Micro框架来处理MVVM方面,已经在Bootstrapper类中配置了Serilog记录器,我不清楚的是如何注册记录器实例,以便它可以在我的应用程序中用于DI。

这是我在Bootstrapper类中所拥有的,我在构造函数中添加了一个简单的try..catch以证明已配置记录器。

public class Bootstrapper : BootstrapperBase
{
    private SimpleContainer _container = new SimpleContainer();
    public Bootstrapper()
    {
        Initialize();

        try
        {
            Log.Information("In Bootstrapper Configure method");
        }
        catch (Exception ex)
        {
            Log.Fatal(ex, "The application failed to start correctly");
        }
        finally
        {
            Log.CloseAndFlush();
        }
    }

    protected override void Configure()
    {
        _container.Instance(_container);

        Log.Logger = new LoggerConfiguration()
            .MinimumLevel.Debug()
            .WriteTo.File("log.txt")
            .CreateLogger();

        _container
            .Singleton<IWindowManager, WindowManager>()
            .Singleton<IEventAggregator, EventAggregator>()


        _container
            .PerRequest<IMyDataHandler, MyDataHandler>();

        GetType().Assembly.GetTypes()
            .Where(type => type.IsClass)
            .Where(type => type.Name.EndsWith("ViewModel"))
            .ToList()
            .ForEach(viewModelType => _container.RegisterPerRequest(
                viewModelType, viewModelType.ToString(), viewModelType));


    }

    protected override void OnStartup(object sender, StartupEventArgs e)
    {
        DisplayRootViewFor<ShellViewModel>();
    }

    protected override object GetInstance(Type service, string key)
    {
        return _container.GetInstance(service, key);
    }

    protected override IEnumerable<object> GetAllInstances(Type service)
    {
        return _container.GetAllInstances(service);
    }

    protected override void BuildUp(object instance)
    {
        _container.BuildUp(instance);
    }


}

任何帮助,或指向文档的指南都很好。

.net-core caliburn.micro serilog
1个回答
0
投票

您可以通过在容器上调用ILogger,以与在应用程序中注册所有其他单例相同的方式注册Serilog的Singleton:>

_container.Singleton<ILogger, Log.Logger>();

在您的应用程序中使用Serilog记录器的另一种方法(我个人更喜欢)是从您的任何类(ViewModels,Services等)访问Log.Logger。使用contextual logger for every class使用Log.ForContext<>也很容易,这在解决问题时很有用。例如:

public class SomeViewModel
{
    private readonly ILogger _log = Log.ForContext<SomeViewModel>();
    // ...
}

public class SomeService
{
    private readonly ILogger _log = Log.ForContext<SomeService>();
    // ...
}
© www.soinside.com 2019 - 2024. All rights reserved.