操作時一直會有綠蚯蚓的提示訊息,說明只能用 Windows 系統上而已
改寫 Worker
抓取各 EventLog 的最新錯誤訊息來顯示,該 ExecuteAsync 執行後,只會 run 一次而已
using System.Diagnostics;
namespace EventWorkerSample
{
public class Worker : BackgroundService
{
private readonly ILogger<Worker> _logger;
public Worker(ILogger<Worker> logger)
{
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
foreach (EventLog el in EventLog.GetEventLogs())
{
EventLogEntry ele = el.Entries
.OfType<EventLogEntry>()
.Where(entry => entry.EntryType == EventLogEntryType.Error)
.OrderByDescending(o => o.TimeWritten)
.Take(1)
.SingleOrDefault();
if (ele == null)
continue;
string errorMessage = $@"
Log 名稱:{el.Log} - {el.LogDisplayName}
錯誤訊息:{ele.Message.Substring(0, 50)}
";
_logger.LogError(errorMessage);
}
await Task.CompletedTask;
}
}
}
沒有留言:
張貼留言