Removed some blocking if the logger cannot log to http, tcp or udp

This commit is contained in:
2025-07-25 21:14:23 +02:00
parent d981397b02
commit 182129d9fa
29 changed files with 550 additions and 282 deletions

View File

@@ -7,7 +7,7 @@ namespace EonaCat.Logger;
public static class DllInfo
{
public const string NAME = "EonaCatLogger";
public const string VERSION = "1.1.0";
public const string VERSION = "1.4.8";
static DllInfo()
{

View File

@@ -1,9 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>.netstandard2.1; net6.0; net7.0; net8.0; net4.8;</TargetFrameworks>
<TargetFrameworks>.netstandard2.1; net8.0; net4.8;</TargetFrameworks>
<ApplicationIcon>icon.ico</ApplicationIcon>
<Version>1.4.8</Version>
<LangVersion>latest</LangVersion>
<FileVersion>1.4.7</FileVersion>
<FileVersion>1.4.8</FileVersion>
<Authors>EonaCat (Jeroen Saey)</Authors>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<Company>EonaCat (Jeroen Saey)</Company>
@@ -24,7 +25,7 @@
</PropertyGroup>
<PropertyGroup>
<EVRevisionFormat>1.4.7+{chash:10}.{c:ymd}</EVRevisionFormat>
<EVRevisionFormat>1.4.8+{chash:10}.{c:ymd}</EVRevisionFormat>
<EVDefault>true</EVDefault>
<EVInfo>true</EVInfo>
<EVTagMatch>v[0-9]*</EVTagMatch>
@@ -58,10 +59,11 @@
</PackageReference>
<PackageReference Include="EonaCat.Versioning.Helpers" Version="1.0.2" />
<PackageReference Include="Microsoft.CSharp" Version="4.7.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="9.0.4" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="9.0.4" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="9.0.4" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="9.0.6" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="9.0.6" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="9.0.6" />
<PackageReference Include="System.Net.Http" Version="4.3.4" />
<PackageReference Include="System.Threading.Channels" Version="9.0.7" />
</ItemGroup>
<ItemGroup>
<None Update="LICENSE.md">

View File

@@ -9,6 +9,8 @@ using System.Threading.Tasks;
namespace EonaCat.Logger.EonaCatCoreLogger
{
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
public class BatchingDatabaseLogger : ILogger, IDisposable
{
private readonly string _categoryName;

View File

@@ -3,6 +3,8 @@ using System.Data.Common;
namespace EonaCat.Logger.EonaCatCoreLogger
{
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
public class BatchingDatabaseLoggerOptions
{
public DbProviderFactory DbProviderFactory { get; set; }
@@ -12,7 +14,7 @@ namespace EonaCat.Logger.EonaCatCoreLogger
VALUES (@Timestamp, @LogLevel, @Category, @Message, @Exception, @CorrelationId)";
public bool IsEnabled { get; set; } = true;
public bool IncludeCorrelationId { get; set; } = true;
public bool IncludeCorrelationId { get; set; }
public TimeSpan BatchInterval { get; set; } = TimeSpan.FromSeconds(5); // 5 sec batch
public TimeSpan ShutdownTimeout { get; set; } = TimeSpan.FromSeconds(10); // wait on shutdown

View File

@@ -2,6 +2,8 @@
namespace EonaCat.Logger.EonaCatCoreLogger
{
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
public class BatchingDatabaseLoggerProvider : ILoggerProvider
{
private readonly BatchingDatabaseLoggerOptions _options;

View File

@@ -1,17 +1,25 @@
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Data.Common;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace EonaCat.Logger.EonaCatCoreLogger
{
public class DatabaseLogger : ILogger
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
public class DatabaseLogger : ILogger, IDisposable
{
private readonly string _categoryName;
private readonly DatabaseLoggerOptions _options;
private readonly LoggerScopedContext _context = new();
private static readonly ConcurrentQueue<LogEntry> _queue = new();
private static readonly SemaphoreSlim _flushLock = new(1, 1);
private static bool _flushLoopStarted = false;
private static CancellationTokenSource _cts;
public bool IncludeCorrelationId { get; set; }
public event EventHandler<Exception> OnException;
@@ -20,6 +28,13 @@ namespace EonaCat.Logger.EonaCatCoreLogger
_categoryName = categoryName;
_options = options;
IncludeCorrelationId = options.IncludeCorrelationId;
if (!_flushLoopStarted)
{
_flushLoopStarted = true;
_cts = new CancellationTokenSource();
Task.Run(() => FlushLoopAsync(_cts.Token));
}
}
public IDisposable BeginScope<TState>(TState state) => null;
@@ -33,11 +48,7 @@ namespace EonaCat.Logger.EonaCatCoreLogger
Exception exception, Func<TState, Exception, string> formatter)
{
if (!IsEnabled(logLevel) || formatter == null)
{
return;
}
var message = formatter(state, exception);
if (IncludeCorrelationId)
{
@@ -45,33 +56,75 @@ namespace EonaCat.Logger.EonaCatCoreLogger
_context.Set("CorrelationId", correlationId);
}
var message = formatter(state, exception);
var entry = new LogEntry
{
Timestamp = DateTime.UtcNow,
LogLevel = logLevel.ToString(),
Category = _categoryName,
Message = message,
Exception = exception?.ToString(),
CorrelationId = _context.Get("CorrelationId")
};
_queue.Enqueue(entry);
if (_queue.Count >= _options.FlushBatchSize)
{
_ = FlushBufferAsync();
}
}
private async Task FlushLoopAsync(CancellationToken token)
{
while (!token.IsCancellationRequested)
{
await Task.Delay(TimeSpan.FromSeconds(_options.FlushIntervalSeconds), token);
await FlushBufferAsync();
}
}
private async Task FlushBufferAsync()
{
if (!await _flushLock.WaitAsync(0))
return; // Another flush is in progress
try
{
while (_queue.TryDequeue(out var entry))
{
try
{
using var connection = _options.DbProviderFactory.CreateConnection();
if (connection == null)
{
throw new InvalidOperationException("Failed to create database connection.");
}
connection.ConnectionString = _options.ConnectionString;
connection.Open();
await connection.OpenAsync();
using var command = connection.CreateCommand();
command.CommandText = _options.InsertCommand;
command.Parameters.Clear();
command.Parameters.Add(CreateParameter(command, "Timestamp", DateTime.UtcNow));
command.Parameters.Add(CreateParameter(command, "LogLevel", logLevel.ToString()));
command.Parameters.Add(CreateParameter(command, "Category", _categoryName));
command.Parameters.Add(CreateParameter(command, "Message", message));
command.Parameters.Add(CreateParameter(command, "Exception", exception?.ToString()));
command.Parameters.Add(CreateParameter(command, "CorrelationId", _context.Get("CorrelationId")));
command.Parameters.Add(CreateParameter(command, "Timestamp", entry.Timestamp));
command.Parameters.Add(CreateParameter(command, "LogLevel", entry.LogLevel));
command.Parameters.Add(CreateParameter(command, "Category", entry.Category));
command.Parameters.Add(CreateParameter(command, "Message", entry.Message));
command.Parameters.Add(CreateParameter(command, "Exception", entry.Exception));
command.Parameters.Add(CreateParameter(command, "CorrelationId", entry.CorrelationId));
command.ExecuteNonQuery();
await command.ExecuteNonQueryAsync();
}
catch (Exception e)
catch (Exception ex)
{
OnException?.Invoke(this, e);
OnException?.Invoke(this, ex);
}
}
}
finally
{
_flushLock.Release();
}
}
@@ -82,5 +135,22 @@ namespace EonaCat.Logger.EonaCatCoreLogger
param.Value = value ?? DBNull.Value;
return param;
}
public void Dispose()
{
_cts?.Cancel();
_flushLock.Dispose();
_cts?.Dispose();
}
private class LogEntry
{
public DateTime Timestamp { get; set; }
public string LogLevel { get; set; }
public string Category { get; set; }
public string Message { get; set; }
public string Exception { get; set; }
public string CorrelationId { get; set; }
}
}
}

View File

@@ -2,6 +2,8 @@
namespace EonaCat.Logger.EonaCatCoreLogger
{
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
public class DatabaseLoggerOptions
{
public DbProviderFactory DbProviderFactory { get; set; }
@@ -12,6 +14,8 @@ namespace EonaCat.Logger.EonaCatCoreLogger
VALUES (@Timestamp, @LogLevel, @Category, @Message, @Exception, @CorrelationId)";
public bool IsEnabled { get; set; } = true;
public bool IncludeCorrelationId { get; set; } = true;
public bool IncludeCorrelationId { get; set; }
public int FlushIntervalSeconds { get; set; } = 5;
public int FlushBatchSize { get; set; } = 100;
}
}

View File

@@ -2,6 +2,8 @@
namespace EonaCat.Logger.EonaCatCoreLogger
{
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
public class DatabaseLoggerProvider : ILoggerProvider
{
private readonly DatabaseLoggerOptions _options;

View File

@@ -1,18 +1,29 @@
using Microsoft.Extensions.Logging;
using EonaCat.Json;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
namespace EonaCat.Logger.EonaCatCoreLogger
{
public class DiscordLogger : ILogger
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
public class DiscordLogger : ILogger, IDisposable
{
private readonly string _categoryName;
private readonly DiscordLoggerOptions _options;
private readonly LoggerScopedContext _context = new();
private static readonly ConcurrentQueue<string> _messageQueue = new();
private static readonly HttpClient _httpClient = new();
private static readonly SemaphoreSlim _flushLock = new(1, 1);
private static bool _flushLoopStarted = false;
private static CancellationTokenSource _cts;
public bool IncludeCorrelationId { get; set; }
public event EventHandler<Exception> OnException;
@@ -21,6 +32,13 @@ namespace EonaCat.Logger.EonaCatCoreLogger
_categoryName = categoryName;
_options = options;
IncludeCorrelationId = options.IncludeCorrelationId;
if (!_flushLoopStarted)
{
_flushLoopStarted = true;
_cts = new CancellationTokenSource();
_ = Task.Run(() => FlushLoopAsync(_cts.Token));
}
}
public IDisposable BeginScope<TState>(TState state) => null;
@@ -34,11 +52,7 @@ namespace EonaCat.Logger.EonaCatCoreLogger
Exception exception, Func<TState, Exception, string> formatter)
{
if (!IsEnabled(logLevel) || formatter == null)
{
return;
}
var message = formatter(state, exception);
if (IncludeCorrelationId)
{
@@ -46,6 +60,8 @@ namespace EonaCat.Logger.EonaCatCoreLogger
_context.Set("CorrelationId", correlationId);
}
var message = formatter(state, exception);
var logParts = new List<string>
{
$"**[{DateTime.UtcNow:u}]**",
@@ -66,18 +82,56 @@ namespace EonaCat.Logger.EonaCatCoreLogger
string fullMessage = string.Join("\n", logParts);
// Enqueue and return immediately - non-blocking
_messageQueue.Enqueue(fullMessage);
}
private async Task FlushLoopAsync(CancellationToken token)
{
while (!token.IsCancellationRequested)
{
await Task.Delay(TimeSpan.FromSeconds(_options.FlushIntervalSeconds), token);
await FlushBufferAsync();
}
}
private async Task FlushBufferAsync()
{
if (!await _flushLock.WaitAsync(0))
return; // Already flushing
try
{
using var client = new HttpClient();
var payload = new { content = fullMessage };
var content = new StringContent(JsonSerializer.Serialize(payload), Encoding.UTF8, "application/json");
client.PostAsync(_options.WebhookUrl, content).Wait();
}
catch (Exception e)
while (_messageQueue.TryDequeue(out var message))
{
OnException?.Invoke(this, e);
try
{
var payload = new { content = message };
var content = new StringContent(JsonHelper.ToJson(payload), Encoding.UTF8, "application/json");
var response = await _httpClient.PostAsync(_options.WebhookUrl, content);
if (!response.IsSuccessStatusCode)
{
var error = await response.Content.ReadAsStringAsync();
OnException?.Invoke(this, new Exception($"Discord webhook failed: {response.StatusCode} {error}"));
}
}
catch (Exception ex)
{
OnException?.Invoke(this, ex);
}
}
}
finally
{
_flushLock.Release();
}
}
public void Dispose()
{
_cts?.Cancel();
_flushLock.Dispose();
_cts?.Dispose();
}
}
}

View File

@@ -1,9 +1,12 @@
namespace EonaCat.Logger.EonaCatCoreLogger
{
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
public class DiscordLoggerOptions
{
public string WebhookUrl { get; set; }
public bool IsEnabled { get; set; } = true;
public bool IncludeCorrelationId { get; set; } = true;
public bool IncludeCorrelationId { get; set; }
public int FlushIntervalSeconds { get; set; } = 5;
}
}

View File

@@ -2,6 +2,8 @@
namespace EonaCat.Logger.EonaCatCoreLogger
{
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
public class DiscordLoggerProvider : ILoggerProvider
{
private readonly DiscordLoggerOptions _options;

View File

@@ -5,6 +5,7 @@
namespace EonaCat.Logger.EonaCatCoreLogger
{
using EonaCat.Json;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
@@ -15,6 +16,7 @@ namespace EonaCat.Logger.EonaCatCoreLogger
public class ElasticSearchLogger : ILogger
{
private readonly string _categoryName;
private readonly ElasticSearchLoggerOptions _options;
private static readonly HttpClient _httpClient = new HttpClient();
@@ -74,7 +76,7 @@ namespace EonaCat.Logger.EonaCatCoreLogger
};
// Serialize log to JSON
string json = JsonSerializer.Serialize(logDoc);
string json = JsonHelper.ToJson(logDoc);
// Add to the buffer
lock (_lock)

View File

@@ -19,6 +19,6 @@ namespace EonaCat.Logger.EonaCatCoreLogger
public int RetryBufferSize { get; set; } = 100;
public int FlushIntervalSeconds { get; set; } = 5;
public bool UseBulkInsert { get; set; } = true;
public bool IncludeCorrelationId { get; set; } = true;
public bool IncludeCorrelationId { get; set; }
}
}

View File

@@ -141,7 +141,7 @@ public class FileLoggerOptions : BatchingLoggerOptions
public bool UseDefaultMasking { get; set; } = true;
/// <summary>
/// Determines if we need to include the correlation ID in the log
/// Determines if we need to include the correlation ID in the log (default: false)
/// </summary>
public bool IncludeCorrelationId { get; set; } = true;
public bool IncludeCorrelationId { get; set; }
}

View File

@@ -4,21 +4,21 @@ using System;
using System.Net.Http;
using System.Text;
using System.Collections.Generic;
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
using System.Threading.Tasks;
namespace EonaCat.Logger.EonaCatCoreLogger
{
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
public class HttpLogger : ILogger
{
private readonly string _categoryName;
private readonly HttpLoggerOptions _options;
private readonly LoggerScopedContext _context = new();
private static readonly HttpClient _client = new();
public bool IncludeCorrelationId { get; set; }
private static readonly HttpClient _client = new();
public event EventHandler<Exception> OnException;
public event EventHandler<string> OnInvalidStatusCode;
@@ -39,7 +39,7 @@ namespace EonaCat.Logger.EonaCatCoreLogger
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state,
Exception exception, Func<TState, Exception, string> formatter)
{
if (!IsEnabled(logLevel))
if (!IsEnabled(logLevel) || formatter == null)
{
return;
}
@@ -61,27 +61,25 @@ namespace EonaCat.Logger.EonaCatCoreLogger
{ "eventId", eventId.Id }
};
// Add full log context as a nested dictionary
var contextData = _context.GetAll();
if (contextData.Count > 0)
{
payload["context"] = contextData;
}
Task.Run(async () =>
{
try
{
var content = _options.SendAsJson
? new StringContent(JsonHelper.ToJson(payload), Encoding.UTF8, "application/json")
: new StringContent(message);
: new StringContent(message, Encoding.UTF8, "text/plain");
var result = _client.PostAsync(_options.Endpoint, content);
if (result.Result.IsSuccessStatusCode)
var response = await _client.PostAsync(_options.Endpoint, content);
if (!response.IsSuccessStatusCode)
{
return;
}
// Handle non-success status codes
var statusCode = result.Result.StatusCode;
var statusCode = response.StatusCode;
var statusCodeMessage = statusCode switch
{
System.Net.HttpStatusCode.BadRequest => "400 Bad Request",
@@ -123,10 +121,12 @@ namespace EonaCat.Logger.EonaCatCoreLogger
OnInvalidStatusCode?.Invoke(this, statusCodeMessage);
}
catch (Exception e)
}
catch (Exception ex)
{
OnException?.Invoke(this, e);
}
OnException?.Invoke(this, ex);
}
});
}
}
}

View File

@@ -12,7 +12,7 @@ namespace EonaCat.Logger.EonaCatCoreLogger
public string Endpoint { get; set; } = "http://localhost:5000/logs";
public bool IsEnabled { get; set; } = true;
public bool SendAsJson { get; set; } = true;
public bool IncludeCorrelationId { get; set; } = true;
public bool IncludeCorrelationId { get; set; }
}
}

View File

@@ -4,18 +4,20 @@ using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
using System.Threading;
namespace EonaCat.Logger.EonaCatCoreLogger
{
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
public class JsonFileLogger : ILogger
{
private readonly string _categoryName;
private readonly JsonFileLoggerOptions _options;
private readonly string _filePath;
private readonly LoggerScopedContext _context = new();
private static readonly SemaphoreSlim _fileLock = new(1, 1);
public bool IncludeCorrelationId { get; set; }
public event EventHandler<Exception> OnException;
@@ -24,8 +26,16 @@ namespace EonaCat.Logger.EonaCatCoreLogger
_categoryName = categoryName;
_options = options;
_filePath = Path.Combine(_options.LogDirectory, _options.FileName);
Directory.CreateDirectory(_options.LogDirectory);
IncludeCorrelationId = options.IncludeCorrelationId;
try
{
Directory.CreateDirectory(_options.LogDirectory);
}
catch (Exception ex)
{
OnException?.Invoke(this, ex);
}
}
public void SetContext(string key, string value) => _context.Set(key, value);
@@ -38,12 +48,15 @@ namespace EonaCat.Logger.EonaCatCoreLogger
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state,
Exception exception, Func<TState, Exception, string> formatter)
{
if (!IsEnabled(logLevel))
if (!IsEnabled(logLevel) || formatter == null)
{
return;
}
try
{
string message = formatter(state, exception);
if (IncludeCorrelationId)
{
var correlationId = _context.Get("CorrelationId") ?? Guid.NewGuid().ToString();
@@ -66,14 +79,21 @@ namespace EonaCat.Logger.EonaCatCoreLogger
logObject["context"] = contextData;
}
string json = JsonHelper.ToJson(logObject);
_fileLock.Wait();
try
{
string json = JsonHelper.ToJson(logObject);
File.AppendAllText(_filePath, json + Environment.NewLine, Encoding.UTF8);
}
catch (Exception e)
finally
{
OnException?.Invoke(this, e);
_fileLock.Release();
}
}
catch (Exception ex)
{
OnException?.Invoke(this, ex);
}
}
}

View File

@@ -12,7 +12,7 @@ namespace EonaCat.Logger.EonaCatCoreLogger
public string LogDirectory { get; set; } = "Logs";
public string FileName { get; set; } = "log.json";
public bool IsEnabled { get; set; } = true;
public bool IncludeCorrelationId { get; set; } = true;
public bool IncludeCorrelationId { get; set; }
}
}

View File

@@ -1,20 +1,23 @@
using Microsoft.Extensions.Logging;
using EonaCat.Json;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Text.Json;
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
using System.Threading.Channels;
using System.Threading.Tasks;
namespace EonaCat.Logger.EonaCatCoreLogger
{
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
public class SlackLogger : ILogger
{
private readonly string _categoryName;
private readonly SlackLoggerOptions _options;
private readonly LoggerScopedContext _context = new();
private readonly Channel<string> _logChannel = Channel.CreateUnbounded<string>();
private readonly HttpClient _httpClient;
public bool IncludeCorrelationId { get; set; }
public event EventHandler<Exception> OnException;
@@ -24,6 +27,9 @@ namespace EonaCat.Logger.EonaCatCoreLogger
_categoryName = categoryName;
_options = options;
IncludeCorrelationId = options.IncludeCorrelationId;
_httpClient = new HttpClient();
Task.Run(ProcessLogQueueAsync);
}
public IDisposable BeginScope<TState>(TState state) => null;
@@ -41,6 +47,8 @@ namespace EonaCat.Logger.EonaCatCoreLogger
return;
}
try
{
var message = formatter(state, exception);
if (IncludeCorrelationId)
@@ -68,19 +76,29 @@ namespace EonaCat.Logger.EonaCatCoreLogger
}
string fullMessage = string.Join("\n", logParts);
try
{
using var client = new HttpClient();
var payload = new { text = fullMessage };
var content = new StringContent(JsonSerializer.Serialize(payload), Encoding.UTF8, "application/json");
client.PostAsync(_options.WebhookUrl, content).Wait();
_logChannel.Writer.TryWrite(fullMessage); // non-blocking
}
catch (Exception e)
{
OnException?.Invoke(this, e);
}
}
private async Task ProcessLogQueueAsync()
{
await foreach (var message in _logChannel.Reader.ReadAllAsync())
{
try
{
var payload = new { text = message };
var content = new StringContent(JsonHelper.ToJson(payload), Encoding.UTF8, "application/json");
await _httpClient.PostAsync(_options.WebhookUrl, content);
}
catch (Exception ex)
{
OnException?.Invoke(this, ex);
}
}
}
}
}

View File

@@ -8,6 +8,6 @@
{
public string WebhookUrl { get; set; }
public bool IsEnabled { get; set; } = true;
public bool IncludeCorrelationId { get; set; } = true;
public bool IncludeCorrelationId { get; set; }
}
}

View File

@@ -3,17 +3,21 @@ using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Sockets;
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
using System.Text;
using System.Threading.Channels;
using System.Threading.Tasks;
namespace EonaCat.Logger.EonaCatCoreLogger
{
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
public class TcpLogger : ILogger
{
private readonly string _categoryName;
private readonly TcpLoggerOptions _options;
private readonly LoggerScopedContext _context = new();
private readonly Channel<string> _logChannel = Channel.CreateUnbounded<string>();
public bool IncludeCorrelationId { get; set; }
public event EventHandler<Exception> OnException;
@@ -22,6 +26,9 @@ namespace EonaCat.Logger.EonaCatCoreLogger
_categoryName = categoryName;
_options = options;
IncludeCorrelationId = options.IncludeCorrelationId;
// Start background log writer
Task.Run(ProcessLogQueueAsync);
}
public void SetContext(string key, string value) => _context.Set(key, value);
@@ -34,14 +41,12 @@ namespace EonaCat.Logger.EonaCatCoreLogger
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state,
Exception exception, Func<TState, Exception, string> formatter)
{
if (!IsEnabled(logLevel))
{
return;
}
if (!IsEnabled(logLevel)) return;
try
{
string message = formatter(state, exception);
if (IncludeCorrelationId)
{
var correlationId = _context.Get("CorrelationId") ?? Guid.NewGuid().ToString();
@@ -73,14 +78,30 @@ namespace EonaCat.Logger.EonaCatCoreLogger
string fullLog = string.Join(" | ", logParts);
_logChannel.Writer.TryWrite(fullLog);
}
catch (Exception e)
{
OnException?.Invoke(this, e);
}
}
private async Task ProcessLogQueueAsync()
{
await foreach (var log in _logChannel.Reader.ReadAllAsync())
{
try
{
using var client = new TcpClient();
client.Connect(_options.Host, _options.Port);
await client.ConnectAsync(_options.Host, _options.Port);
using var stream = client.GetStream();
using var writer = new StreamWriter(stream, System.Text.Encoding.UTF8)
using var writer = new StreamWriter(stream, Encoding.UTF8)
{
AutoFlush = true
};
writer.WriteLine(fullLog);
await writer.WriteLineAsync(log);
}
catch (Exception e)
{
@@ -89,3 +110,4 @@ namespace EonaCat.Logger.EonaCatCoreLogger
}
}
}
}

View File

@@ -12,6 +12,6 @@ namespace EonaCat.Logger.EonaCatCoreLogger
public string Host { get; set; }
public int Port { get; set; }
public bool IsEnabled { get; set; } = true;
public bool IncludeCorrelationId { get; set; } = true;
public bool IncludeCorrelationId { get; set; }
}
}

View File

@@ -1,43 +1,65 @@
using Microsoft.Extensions.Logging;
using EonaCat.Json;
using Microsoft.Extensions.Logging;
using System;
using System.Net.Http;
using System.Text;
using System.Text.Json;
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
using System.Threading.Channels;
using System.Threading.Tasks;
namespace EonaCat.Logger.EonaCatCoreLogger
{
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
public class TelegramLogger : ILogger
{
private readonly string _categoryName;
private readonly TelegramLoggerOptions _options;
private readonly HttpClient _httpClient = new HttpClient();
private readonly HttpClient _httpClient = new();
private readonly Channel<string> _logChannel = Channel.CreateUnbounded<string>();
public event EventHandler<Exception> OnException;
public TelegramLogger(string categoryName, TelegramLoggerOptions options)
{
_categoryName = categoryName;
_options = options;
// Start background task
Task.Run(ProcessLogQueueAsync);
}
public IDisposable BeginScope<TState>(TState state) => null;
public bool IsEnabled(LogLevel logLevel) => _options.IsEnabled;
public async void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
{
if (!IsEnabled(logLevel))
if (!IsEnabled(logLevel) || formatter == null)
{
return;
}
try
{
var message = $"[{DateTime.UtcNow:u}] [{logLevel}] {_categoryName}: {formatter(state, exception)}";
if (exception != null)
{
message += $"\nException: {exception}";
}
_logChannel.Writer.TryWrite(message);
}
catch (Exception ex)
{
OnException?.Invoke(this, ex);
}
}
private async Task ProcessLogQueueAsync()
{
await foreach (var message in _logChannel.Reader.ReadAllAsync())
{
try
{
var url = $"https://api.telegram.org/bot{_options.BotToken}/sendMessage";
var payload = new
{
@@ -45,10 +67,7 @@ namespace EonaCat.Logger.EonaCatCoreLogger
text = message
};
var content = new StringContent(JsonSerializer.Serialize(payload), Encoding.UTF8, "application/json");
try
{
var content = new StringContent(JsonHelper.ToJson(payload), Encoding.UTF8, "application/json");
await _httpClient.PostAsync(url, content);
}
catch (Exception ex)
@@ -58,3 +77,4 @@ namespace EonaCat.Logger.EonaCatCoreLogger
}
}
}
}

View File

@@ -3,17 +3,21 @@ using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Text;
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
using System.Threading.Channels;
using System.Threading.Tasks;
namespace EonaCat.Logger.EonaCatCoreLogger
{
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
public class UdpLogger : ILogger
{
private readonly string _categoryName;
private readonly UdpLoggerOptions _options;
private readonly LoggerScopedContext _context = new();
private readonly Channel<string> _logChannel = Channel.CreateUnbounded<string>();
private readonly UdpClient _udpClient = new();
public bool IncludeCorrelationId { get; set; }
public event EventHandler<Exception> OnException;
@@ -22,6 +26,8 @@ namespace EonaCat.Logger.EonaCatCoreLogger
_categoryName = categoryName;
_options = options;
IncludeCorrelationId = options.IncludeCorrelationId;
Task.Run(ProcessLogQueueAsync);
}
public void SetContext(string key, string value) => _context.Set(key, value);
@@ -40,9 +46,10 @@ namespace EonaCat.Logger.EonaCatCoreLogger
return;
}
try
{
string message = formatter(state, exception);
// Get correlation ID from context or generate new one
if (IncludeCorrelationId)
{
var correlationId = _context.Get("CorrelationId") ?? Guid.NewGuid().ToString();
@@ -73,16 +80,27 @@ namespace EonaCat.Logger.EonaCatCoreLogger
}
string fullMessage = string.Join(" | ", logParts);
_logChannel.Writer.TryWrite(fullMessage);
}
catch (Exception ex)
{
OnException?.Invoke(this, ex);
}
}
private async Task ProcessLogQueueAsync()
{
await foreach (var message in _logChannel.Reader.ReadAllAsync())
{
try
{
using var client = new UdpClient();
byte[] bytes = Encoding.UTF8.GetBytes(fullMessage);
client.Send(bytes, bytes.Length, _options.Host, _options.Port);
byte[] bytes = Encoding.UTF8.GetBytes(message);
await _udpClient.SendAsync(bytes, bytes.Length, _options.Host, _options.Port);
}
catch (Exception e)
catch (Exception ex)
{
OnException?.Invoke(this, e);
OnException?.Invoke(this, ex);
}
}
}
}

View File

@@ -14,7 +14,7 @@ namespace EonaCat.Logger.EonaCatCoreLogger
public int Port { get; set; } = 514;
public bool IsEnabled { get; set; } = true;
public bool IncludeCorrelationId { get; set; } = true;
public bool IncludeCorrelationId { get; set; }
}
}

View File

@@ -1,32 +1,39 @@
using Microsoft.Extensions.Logging;
using System;
using System.IO;
using System.Threading;
using System.Xml.Linq;
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
namespace EonaCat.Logger.EonaCatCoreLogger
{
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
public class XmlFileLogger : ILogger
{
private readonly string _categoryName;
private readonly XmlFileLoggerOptions _options;
private readonly string _filePath;
private readonly LoggerScopedContext _context = new();
private static readonly SemaphoreSlim _fileLock = new(1, 1);
public bool IncludeCorrelationId { get; set; }
public event EventHandler<Exception> OnException;
public XmlFileLogger(string categoryName, XmlFileLoggerOptions options)
{
_categoryName = categoryName;
_options = options;
_filePath = Path.Combine(_options.LogDirectory, _options.FileName);
Directory.CreateDirectory(_options.LogDirectory);
IncludeCorrelationId = options.IncludeCorrelationId;
try
{
Directory.CreateDirectory(_options.LogDirectory);
}
catch (Exception e)
{
OnException?.Invoke(this, e);
}
}
public void SetContext(string key, string value) => _context.Set(key, value);
@@ -41,9 +48,7 @@ namespace EonaCat.Logger.EonaCatCoreLogger
Exception exception, Func<TState, Exception, string> formatter)
{
if (!IsEnabled(logLevel) || formatter == null)
{
return;
}
try
{
@@ -76,7 +81,15 @@ namespace EonaCat.Logger.EonaCatCoreLogger
logElement.Add(new XElement("exception", exception.ToString()));
}
File.AppendAllText(_filePath, logElement.ToString() + Environment.NewLine);
_fileLock.Wait();
try
{
File.AppendAllText(_filePath, logElement + Environment.NewLine);
}
finally
{
_fileLock.Release();
}
}
catch (Exception e)
{

View File

@@ -12,7 +12,7 @@ namespace EonaCat.Logger.EonaCatCoreLogger
public string LogDirectory { get; set; } = "Logs";
public string FileName { get; set; } = "log.xml";
public bool IsEnabled { get; set; } = true;
public bool IncludeCorrelationId { get; set; } = true;
public bool IncludeCorrelationId { get; set; }
}
}

View File

@@ -8,7 +8,7 @@
<ItemGroup>
<PackageReference Include="EonaCat.Web.RateLimiter" Version="1.0.3" />
<PackageReference Include="EonaCat.Web.Tracer" Version="1.1.9" />
<PackageReference Include="EonaCat.Web.Tracer" Version="2.0.2" />
</ItemGroup>
<ItemGroup>

View File

@@ -53,6 +53,18 @@ options.UseMask = true;
builder.Logging.AddEonaCatFileLogger(fileLoggerOptions: options, filenamePrefix: "web");
builder.Logging.AddEonaCatConsoleLogger();
TcpLoggerOptions tcpLoggerOptions = new TcpLoggerOptions
{
Host = "192.168.1.1",
Port = 12345,
};
builder.Logging.AddEonaCatTcpLogger((tcpLoggerOptions) =>
{
tcpLoggerOptions.Port = 12345;
tcpLoggerOptions.Host = "192.168.1.1";
});
builder.Services.AddRazorPages();
//var rateLimitOptions = new RateLimitOptions