Implemented file logging with Serilog

This commit is contained in:
Zafer Balkan
2024-11-20 15:37:15 +02:00
parent 1a9153dd74
commit c7b36a7b84
2 changed files with 7 additions and 49 deletions

View File

@@ -2,7 +2,6 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Net; using System.Net;
using System.Text;
using System.Text.Json; using System.Text.Json;
using System.Text.Json.Serialization; using System.Text.Json.Serialization;
using TechnitiumLibrary.Net.Dns; using TechnitiumLibrary.Net.Dns;

View File

@@ -17,12 +17,9 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
using System; using Serilog;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics; using System.Linq;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace LogExporter.Strategy namespace LogExporter.Strategy
@@ -31,9 +28,7 @@ namespace LogExporter.Strategy
{ {
#region variables #region variables
private static readonly SemaphoreSlim _fileSemaphore = new SemaphoreSlim(1, 1); private readonly Serilog.Core.Logger _sender;
private readonly string _filePath;
private bool disposedValue; private bool disposedValue;
@@ -43,7 +38,7 @@ namespace LogExporter.Strategy
public FileExportStrategy(string filePath) public FileExportStrategy(string filePath)
{ {
_filePath = filePath; _sender = new LoggerConfiguration().WriteTo.File(filePath, outputTemplate:"{Message}{Newline}").CreateLogger();
} }
#endregion constructor #endregion constructor
@@ -52,39 +47,8 @@ namespace LogExporter.Strategy
public Task ExportAsync(List<LogEntry> logs) public Task ExportAsync(List<LogEntry> logs)
{ {
var jsonLogs = new StringBuilder(logs.Count * 250); var tasks = logs.Select(log => Task.Run(() => _sender.Information(log.ToString())));
foreach (var log in logs) return Task.WhenAll(tasks);
{
jsonLogs.AppendLine(log.ToString());
}
return FlushAsync(jsonLogs.ToString());
}
private async Task FlushAsync(string jsonLogs)
{
// Wait to enter the semaphore
await _fileSemaphore.WaitAsync();
try
{
// Use a FileStream with exclusive access
using (var fileStream = new FileStream(_filePath, FileMode.Append, FileAccess.Write, FileShare.None))
using (var writer = new StreamWriter(fileStream))
{
await writer.WriteAsync(jsonLogs);
}
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
finally
{
// Ensure semaphore is released only if it was successfully acquired
if (_fileSemaphore.CurrentCount == 0)
{
_fileSemaphore.Release();
}
}
} }
#endregion public #endregion public
@@ -104,12 +68,7 @@ namespace LogExporter.Strategy
{ {
if (disposing) if (disposing)
{ {
// Ensure semaphore is released only if it was successfully acquired _sender.Dispose();
if (_fileSemaphore.CurrentCount == 0)
{
_fileSemaphore.Release();
}
_fileSemaphore.Dispose();
} }
disposedValue = true; disposedValue = true;