v 1.0.1 - Add Cancellation Token to service

This commit is contained in:
Claudio Boggian
2025-02-24 14:56:41 +01:00
parent 2e1c003808
commit 8e097e90c1
4 changed files with 35 additions and 31 deletions
@@ -37,6 +37,14 @@
"PrivateKeyFile" = "8:"
"TimeStampServer" = "8:"
"InstallerBootstrapper" = "3:2"
"BootstrapperCfg:{63ACBE69-63AA-4F98-B2B6-99F9E24495F2}"
{
"Enabled" = "11:TRUE"
"PromptEnabled" = "11:TRUE"
"PrerequisitesLocation" = "2:1"
"Url" = "8:"
"ComponentsUrl" = "8:"
}
}
"Release"
{
@@ -156,15 +164,15 @@
{
"Name" = "8:Microsoft Visual Studio"
"ProductName" = "8:Log 4 Graylog"
"ProductCode" = "8:{AE9265EA-F205-4212-9A4A-C0AFD73A2067}"
"PackageCode" = "8:{688D543B-C948-42B2-9DBB-282E9C06868B}"
"ProductCode" = "8:{20B40DF7-DE7D-4525-8A5A-70A7553AD142}"
"PackageCode" = "8:{8B5226CE-438C-4CA5-AA45-6B913E396AD8}"
"UpgradeCode" = "8:{7CE09C91-3C26-4C8E-BC66-003536E12481}"
"AspNetVersion" = "8:4.0.30319.0"
"RestartWWWService" = "11:FALSE"
"RemovePreviousVersions" = "11:FALSE"
"DetectNewerInstalledVersion" = "11:TRUE"
"InstallAllUsers" = "11:TRUE"
"ProductVersion" = "8:1.0.0"
"ProductVersion" = "8:1.0.1"
"Manufacturer" = "8:PAL s.r.l."
"ARPHELPTELEPHONE" = "8:"
"ARPHELPLINK" = "8:"
+3 -12
View File
@@ -1,13 +1,11 @@
using System.ServiceProcess;
using console_log4graylog.Model;
using console_log4graylog.Model;
using console_log4graylog.Workers;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Serilog;
using Serilog.Core;
using Serilog.Events;
using Serilog.Sinks.Graylog;
using System.ServiceProcess;
namespace console_log4graylog
{
@@ -15,8 +13,6 @@ namespace console_log4graylog
{
public static void Main(string[] args)
{
ServiceBase[] servicesToRun;
IConfigurationRoot config = new ConfigurationBuilder()
.AddJsonFile("appsettings.json",
optional: true,
@@ -24,11 +20,6 @@ namespace console_log4graylog
.AddEnvironmentVariables()
.Build();
servicesToRun = new []
{
new MainWorker(config)
};
var graylogSettings = config.GetSection("GraylogSettings").Get<GraylogSettings>();
Log.Logger = new LoggerConfiguration()
@@ -41,7 +32,7 @@ namespace console_log4graylog
Facility = graylogSettings.Facility
}).CreateLogger();
ServiceBase.Run(servicesToRun);
ServiceBase.Run(new MainWorker(config));
}
}
+20 -15
View File
@@ -1,9 +1,6 @@
using console_log4graylog.Model;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.FileSystemGlobbing;
using Microsoft.Extensions.Hosting;
using Serilog;
using System.IO;
using System.Net;
using System.ServiceProcess;
@@ -13,8 +10,8 @@ namespace console_log4graylog.Workers
{
private SettingsModel Settings { get; set; }
private FileSystemWatcher watcher;
private Thread monitorThread;
private bool running = true;
private Task monitorTask;
private CancellationTokenSource cancellationTokenSource;
public MainWorker(IConfiguration _configuration)
{
@@ -29,9 +26,9 @@ namespace console_log4graylog.Workers
Log2File("Start Log 4 Graylog");
Log.Logger.Warning("▶️ Start Log 4 Graylog on " + Dns.GetHostName());
cancellationTokenSource = new CancellationTokenSource();
monitorTask = Task.Run(() => MonitorFolder(cancellationTokenSource.Token), cancellationTokenSource.Token);
monitorThread = new Thread(MonitorFolder);
monitorThread.Start();
}
protected override void OnStop()
@@ -39,23 +36,28 @@ namespace console_log4graylog.Workers
Log2File("End Log 4 Graylog");
Log.Logger.Error("⏹️ End Log 4 Graylog on " + Dns.GetHostName());
running = false;
cancellationTokenSource.Cancel();
watcher?.Dispose();
monitorTask?.Wait();
}
private void MonitorFolder()
private async Task MonitorFolder(CancellationToken cancellationToken)
{
while (running)
while (!cancellationToken.IsCancellationRequested)
{
try
{
var latestFile = GetLatestLogFile();
if (latestFile != null)
{
MonitorLogFile(latestFile);
await MonitorLogFile(latestFile, cancellationToken);
}
Thread.Sleep(1000);
else
{
await Task.Delay(50, cancellationToken);
}
}
catch (TaskCanceledException) { return; }
catch (Exception ex)
{
LogError("Service encountered an error: " + ex.Message);
@@ -71,7 +73,7 @@ namespace console_log4graylog.Workers
.FirstOrDefault();
}
private void MonitorLogFile(FileInfo file)
private async Task MonitorLogFile(FileInfo file, CancellationToken cancellationToken)
{
try
{
@@ -81,8 +83,10 @@ namespace console_log4graylog.Workers
using (var reader = new StreamReader(fs))
{
reader.BaseStream.Seek(0, SeekOrigin.End);
while (running)
while (!cancellationToken.IsCancellationRequested)
{
cancellationToken.ThrowIfCancellationRequested();
string line = reader.ReadLine();
while (line != null)
{
@@ -93,10 +97,11 @@ namespace console_log4graylog.Workers
{
break;
}
Thread.Sleep(500);
await Task.Delay(1, cancellationToken);
}
}
}
catch (TaskCanceledException) { return; }
catch (Exception ex)
{
LogError("Error monitoring file: " + ex.Message);
+1 -1
View File
@@ -7,6 +7,6 @@
"GeneralSettings" : {
"DirPath" : "C:\\Logs",
"FileNamePattern": "*.log",
"LogPath": "C:\\Logs\\l4g_debug.log"
"LogPath": "C:\\Logs\\debug.l4g"
}
}