简体   繁体   English

Serilog日志文件写入时如何触发事件?

[英]How to Trigger Event When Serilog Logs File is Written to?

I am trying to display the contents of the Serilog "logs.txt" file in my UWP app. 我正在尝试在我的UWP应用中显示Serilog“ logs.txt”文件的内容。 I have it successfully displayed, but now I want it to auto refresh as new log events are created. 我已成功显示它,但是现在我希望它在创建新的日志事件时自动刷新。

So far I tried making a ContentsChanged event listener that subscribes to changes in .txt files in the local files drive. 到目前为止,我尝试制作一个ContentsChanged事件侦听器,该侦听器订阅本地文件驱动器中.txt文件中的更改。

private async void CreateFileUpdater()
{
    List<string> fileTypeFilter = new List<string>();
    fileTypeFilter.Add(".txt");
    var options = new Windows.Storage.Search.QueryOptions(Windows.Storage.Search.CommonFileQuery.OrderByName, fileTypeFilter);
    var query = ApplicationData.Current.LocalFolder.CreateFileQueryWithOptions(options);
            //subscribe on query's ContentsChanged event
    query.ContentsChanged += Query_ContentsChanged;
    var files = await query.GetFilesAsync();
}

private void Query_ContentsChanged(Windows.Storage.Search.IStorageQueryResultBase sender, object args)
{
    ReadFileAsync(); //This updates the bound variable to display in UI
}

However, It doesn't seem to trigger properly when new log events are added to the logs file. 但是,将新的日志事件添加到日志文件后,似乎无法正确触发。 So I was wondering if Serilog itself has an event I am just not seeing in the documentation or if there is a better way to detect changes in files or when things are added to files. 因此,我想知道Serilog本身是否发生了某个事件,而我只是在文档中没有看到它,或者是否有更好的方法来检测文件中的更改或何时向文件中添加内容。 I just want some sort of event to be called so that I can trigger my ReadFilesAsync() function to update the variable that is bound to my UI. 我只希望调用某种事件,以便可以触发ReadFilesAsync()函数来更新绑定到UI的变量。

Thanks for any help! 谢谢你的帮助!

The best way I think to do this, is to create your own custom Sink for Serilog. 我认为最好的方法是为Serilog创建自己的自定义接收器。 It will catch any log generated, and then you can filter and output these logs anywhere you want. 它会捕获生成的所有日志,然后您可以在任何需要的地方过滤并输出这些日志。 In my case, I output them to my UI. 就我而言,我将它们输出到我的UI。

Create a sinks class: 创建一个接收器类:

    public class LogsSink : ILogEventSink
    {
        /// <summary>
        /// Format of the output log
        /// </summary>
        readonly string Format = "{0} {1} {2}";

        /// <summary>
        /// Emit the provided log event to the sink.
        /// </summary>
        /// <param name="logEvent">The log event to write</param>
        public void Emit(LogEvent logEvent)
        {
            var t = logEvent.Timestamp;
            LogMsg msg = new LogMsg()
            {
                Text = logEvent.RenderMessage(),
                Lvl = LevelToSeverity(logEvent),
                TimeStamp = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss.fff") + " -" + t.Offset.ToString(@"hh\:mm"),
            };
            if (LogsViewModel.logFile != null)
                LogsViewModel.logFile.AllText.Add(string.Format(Format, msg.TimeStamp, msg.Lvl, msg.Text));
            LogsViewModel.logFile.AppendText();
        }

        static string LevelToSeverity(LogEvent logEvent)
        {
            switch (logEvent.Level)
            {
                case LogEventLevel.Debug:
                    return "[DBG]";
                case LogEventLevel.Error:
                    MainPageViewModel.statusBar.AddError();
                    return "[ERR]";
                case LogEventLevel.Fatal:
                    return "[FTL]";
                case LogEventLevel.Verbose:
                    return "VERBOSE";
                case LogEventLevel.Warning:
                    MainPageViewModel.statusBar.AddWarning();
                    return "WARNING";
                default:
                    return "[INF]";
            }
        }
    }

    struct LogMsg
    {
        public string Lvl;
        public string Text;
        public string TimeStamp;
    }

Register your sink when you instantiate the logger 实例化记录器时注册接收器

public LogsSink sink;
sink = new LogsSink();
Log.Logger = new LoggerConfiguration().MinimumLevel.Debug()
                .WriteTo.Sink(sink)
                .CreateLogger();

Let me know if you have any questions! 如果您有任何疑问,请告诉我!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM