如何从Microsoft.Extensions.Logging订阅日志

时间:2019-06-24 11:45:06

标签: c# logging mvvm

如何将日志返回到UI?

我创建了一个自定义Logger AudittrailLogger,以登录到mssqlserver数据库。 到目前为止成功,...日志将插入到数据库中。现在,我希望在用户控件中的某个日志级别上方显示所有即将出现的日志。

我是否必须在configureLoggerFactory方法中传递委托/动作?

public void ConfigureLoggerFactory(string dbConnectionString)
{
    if (LoggerFactory == null)
    {
        LoggerFactory = new LoggerFactory()
            .AddAudittrailLogger(c =>
        {
            c.LogLevel = LogLevel.Trace;
            c.DbConnectionString = dbConnectionString;
        });
        CaliburnLog = LoggerFactory.CreateLogger("CaliburnMicro");
    }
}

在我看来,当前情况如下:

private ILogger Log { get; set; }

public MainViewModel(IEventAggregator eventAggregator)
{
    ....
    Log = _LogManager.LoggerFactory.CreateLogger<MainViewModel>();

    // now I like to subscribe to the logs to show them in the UI
    _LogManager.OnLogReceived += OnLogReceived;

或者,我编写第二个自定义LoggingProvider。但是我仍然迷失了如何将日志消息发送回UI。

public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
{
    // *** this single line is not working yet *** How to inform the subscribers?
    OnLogReceived?.Invoke(this, new LogReceivedEventArgs(formatter(state, exception), logLevel));

    // save to database via EntityFramework - this could be skipped/deleted in a second LoggingProvider 
    using (var dbContext = new MyDbContext(_Config.DbConnectionString))
    {
        dbContext.LogEntries.Add(new Models.LogEntry()
        {
            TimeStampUtc = DateTime.UtcNow,
            Level = logLevel,
            Source = _Name, 
            EventId = eventId.Id, 
            EventIdName = eventId.Name,
            MachineName = Environment.MachineName,
            UserName = Environment.UserName,
            LogMessage = formatter(state, exception),
            Exception = exception?.Message, 
            StackTrace = exception?.StackTrace
        });
        dbContext.SaveChanges();
    }
}

1 个答案:

答案 0 :(得分:0)

通过静态函数和静态事件解决了它...

const {b : {c , d}} = a

{value: 'john'}
{value: 'doe'};

然后在Log方法中只需调用静态函数即可启动静态事件。

public delegate void LogReceived(Object sender, LogReceivedEventArgs args);

public class MyLogManager : Caliburn.Micro.ILog
{
    public static event LogReceived OnLogReceived;

    public static void ShowLog(string msg, LogLevel logLevel)
    {
        OnLogReceived?.Invoke(_Instance, new LogReceivedEventArgs(msg, logLevel));
    }

在我的MainViewModel中,我只需要订阅此事件:

public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
{
    if (logLevel > LogLevel.Debug)
        MyLogManager.ShowLog(formatter(state, exception), logLevel);