Changed Console.WriteLine to event

This commit is contained in:
2026-07-22 06:34:06 +02:00
committed by Jeroen Saey
parent f2fa009200
commit b37a7119bf
4 changed files with 29 additions and 91 deletions
+3 -3
View File
@@ -14,7 +14,7 @@ It features a rich fluent API for routing log events to dozens of destinations f
<Copyright>EonaCat (Jeroen Saey)</Copyright>
<PackageTags>EonaCat;Logger;EonaCatLogStack;Log;Writer;Flows;LogStack;Memory;Speed;Jeroen;Saey</PackageTags>
<PackageIconUrl />
<FileVersion>0.1.6</FileVersion>
<FileVersion>0.1.7</FileVersion>
<PackageReadmeFile>README.md</PackageReadmeFile>
<GenerateDocumentationFile>True</GenerateDocumentationFile>
<PackageLicenseFile>LICENSE</PackageLicenseFile>
@@ -25,7 +25,7 @@ It features a rich fluent API for routing log events to dozens of destinations f
</PropertyGroup>
<PropertyGroup>
<EVRevisionFormat>0.1.6+{chash:10}.{c:ymd}</EVRevisionFormat>
<EVRevisionFormat>0.1.7+{chash:10}.{c:ymd}</EVRevisionFormat>
<EVDefault>true</EVDefault>
<EVInfo>true</EVInfo>
<EVTagMatch>v[0-9]*</EVTagMatch>
@@ -36,7 +36,7 @@ It features a rich fluent API for routing log events to dozens of destinations f
</PropertyGroup>
<PropertyGroup>
<Version>0.1.6</Version>
<Version>0.1.7</Version>
<PackageId>EonaCat.LogStack</PackageId>
<Product>EonaCat.LogStack</Product>
<RepositoryUrl>https://git.saey.me/EonaCat/EonaCat.LogStack</RepositoryUrl>
@@ -48,6 +48,7 @@ namespace EonaCat.LogStack.Flows
private readonly Thread _flushThread;
private readonly Thread _retentionThread;
private readonly Stopwatch _uptime = Stopwatch.StartNew();
public static event EventHandler<string> OnException;
private struct QueueEntry
{
@@ -84,8 +85,6 @@ namespace EonaCat.LogStack.Flows
private long _totalBytesWritten;
private long _currentMemoryBytes;
public bool IgnoreConsoleErrors { get; set; }
private volatile SamplingPolicy _samplingPolicy;
private volatile Action<LogEvent> _onDrop;
private volatile Action<string> _onRotate;
@@ -623,7 +622,7 @@ namespace EonaCat.LogStack.Flows
}
catch (Exception e)
{
Console.WriteLine($"Exception during decryption => {e.Message}");
OnException?.Invoke(null, "[EncryptedFileFlow] Exception during decryption: " + e.Message);
}
return false;
}
@@ -793,7 +792,7 @@ namespace EonaCat.LogStack.Flows
}
catch (Exception ex)
{
WriteToConsoleError("[EncryptedFileFlow] Writer error: " + ex.Message);
OnException?.Invoke(null, "[EncryptedFileFlow] Writer error: " + ex.Message);
}
finally
{
@@ -878,7 +877,7 @@ namespace EonaCat.LogStack.Flows
_lastError = ex;
Interlocked.Increment(ref _totalErrors);
Interlocked.Exchange(ref _lastErrorTimestamp, DateTime.UtcNow.Ticks);
WriteToConsoleError("[EncryptedFileFlow] Write error: " + ex.Message);
OnException?.Invoke(null, "[EncryptedFileFlow] Write error: " + ex.Message);
}
}
}
@@ -1083,16 +1082,6 @@ namespace EonaCat.LogStack.Flows
}
}
private void WriteToConsoleError(string text)
{
if (IgnoreConsoleErrors)
{
return;
}
Console.Error.WriteLine(text);
}
private string Format(LogEvent log)
{
var sb = new StringBuilder(256);
@@ -1292,7 +1281,7 @@ namespace EonaCat.LogStack.Flows
}
catch (Exception ex)
{
WriteToConsoleError("[EncryptedFileFlow] Retention error: " + ex.Message);
OnException?.Invoke(null, "[EncryptedFileFlow] Retention error: " + ex.Message);
}
}
}
@@ -1336,7 +1325,7 @@ namespace EonaCat.LogStack.Flows
}
catch (Exception ex)
{
WriteToConsoleError("[EncryptedFileFlow] Retention error: " + ex.Message);
OnException?.Invoke(null, "[EncryptedFileFlow] Retention error: " + ex.Message);
}
}
@@ -26,11 +26,11 @@ namespace EonaCat.LogStack.Flows
public sealed class FileFlow : FlowBase
{
public event EventHandler<string> OnDirectoryException;
public event EventHandler<string> OnException;
private const int FileBufferSize = 131072; // 128 KB
private const int WriterBufferSize = 131072; // 128 KB
private readonly int _batchSize;
private const int QueueCapacity = 8192;
public bool IgnoreConsoleErrors { get; set; }
private static readonly Dictionary<LogLevel, string> LevelStrings =
new Dictionary<LogLevel, string>
@@ -208,7 +208,6 @@ namespace EonaCat.LogStack.Flows
}
catch (Exception ex)
{
WriteToConsoleError($"[FileFlow] Critical error in directory resolution: {ex.Message}");
_directory = Path.GetTempPath();
OnDirectoryException?.Invoke(this, $"FileFlow: Critical failure in directory resolution: {ex.Message}. Falling back to temp: '{_directory}'");
}
@@ -849,7 +848,6 @@ namespace EonaCat.LogStack.Flows
}
private void WriterThreadBody()
{
WriteToConsoleError("[FileFlow] Writer thread started");
try
{
while (!_queue.IsCompleted)
@@ -886,7 +884,7 @@ namespace EonaCat.LogStack.Flows
}
catch (Exception ex)
{
WriteToConsoleError("[FileFlow] Writer thread error: " + ex.Message);
OnException?.Invoke(this, $"[FileFlow] Writer thread encountered an error: {ex.Message}");
}
finally
{
@@ -907,26 +905,6 @@ namespace EonaCat.LogStack.Flows
}
}
}
private void WriteToConsoleError(string text)
{
if (IgnoreConsoleErrors)
{
return;
}
try
{
// Write to both stdout and stderr to ensure visibility
Console.WriteLine(text);
Console.Error.WriteLine(text);
}
catch
{
// Logging must never bring down the application.
}
}
private void WriteLogEvent(LogEvent log)
{
long size =0;
@@ -1034,11 +1012,6 @@ namespace EonaCat.LogStack.Flows
of.Writer.WriteLine(line);
of.Size += line.Length + Environment.NewLine.Length;
}
else
{
// File handle disappeared between EnsureFileOpen and write attempt
WriteToConsoleError("[FileFlow] File handle for '" + path + "' missing after EnsureFileOpen");
}
}
}
}
@@ -1058,7 +1031,7 @@ namespace EonaCat.LogStack.Flows
diagnosis = " | " + Helpers.DirectoryPermissionHelper.GetAccessIssueDiagnosis(dir);
}
}
WriteToConsoleError("[FileFlow] Write error for '" + path + "': " + ex.Message + diagnosis);
OnException?.Invoke(this, "[FileFlow] Write error for '" + path + "': " + ex.Message + diagnosis);
}
catch { /* Do nothing */ }
}
@@ -1083,7 +1056,7 @@ namespace EonaCat.LogStack.Flows
{
try
{
WriteToConsoleError("[FileFlow] WriteLogEvent error: " + ex.Message);
OnException?.Invoke(this, "[FileFlow] WriteLogEvent error: " + ex.Message);
}
catch { /* Do nothing */ }
}
@@ -1592,7 +1565,7 @@ namespace EonaCat.LogStack.Flows
}
catch (Exception ex)
{
WriteToConsoleError("[FileFlow] CSV header write error for '" + path + "': " + ex.Message);
OnException?.Invoke(this, "[FileFlow] CSV header write error for '" + path + "': " + ex.Message);
}
}
@@ -1616,7 +1589,7 @@ namespace EonaCat.LogStack.Flows
}
catch (Exception ex)
{
WriteToConsoleError("[FileFlow] XML header write error for '" + path + "': " + ex.Message);
OnException?.Invoke(this, "[FileFlow] XML header write error for '" + path + "': " + ex.Message);
}
}
@@ -1646,7 +1619,7 @@ namespace EonaCat.LogStack.Flows
diagnosis = " Diagnosis: " + Helpers.DirectoryPermissionHelper.GetAccessIssueDiagnosis(dir);
}
}
WriteToConsoleError("[FileFlow] Failed to open '" + path + "': " + ex.Message + diagnosis);
OnException?.Invoke(this, "[FileFlow] Failed to open '" + path + "': " + ex.Message + diagnosis);
return false;
}
}
@@ -1655,7 +1628,7 @@ namespace EonaCat.LogStack.Flows
// Outermost safety net never let this method take down the process
try
{
WriteToConsoleError("[FileFlow] EnsureFileOpen unhandled error: " + ex.Message);
OnException?.Invoke(this, "[FileFlow] EnsureFileOpen unhandled error: " + ex.Message);
}
catch { /* ignore */ }
return false;
@@ -1763,7 +1736,7 @@ namespace EonaCat.LogStack.Flows
}
catch (Exception ex)
{
WriteToConsoleError("[FileFlow] Archive error '" + filePath + "': " + ex.Message);
OnException?.Invoke(this, "[FileFlow] Archive error '" + filePath + "': " + ex.Message);
return null;
}
}
@@ -1807,7 +1780,7 @@ namespace EonaCat.LogStack.Flows
try { CompressFile(path); }
catch (Exception ex)
{
WriteToConsoleError("[FileFlow] Compress error '" + path + "': " + ex.Message);
OnException?.Invoke(this, "[FileFlow] Compress error '" + path + "': " + ex.Message);
}
}
}
@@ -1873,13 +1846,12 @@ namespace EonaCat.LogStack.Flows
}
catch (Exception ex)
{
WriteToConsoleError("[FileFlow] Compressed retention error: " + ex.Message);
OnException?.Invoke(this, "[FileFlow] Compressed retention error: " + ex.Message);
}
}
private void PeriodicFlushLoop()
{
WriteToConsoleError("[FileFlow] Periodic flush loop started");
try
{
while (!_isDisposing && !_cts.Token.IsCancellationRequested)
@@ -1918,13 +1890,13 @@ namespace EonaCat.LogStack.Flows
catch (ThreadInterruptedException) { break; }
catch (Exception ex)
{
WriteToConsoleError("[FileFlow] Flush error: " + ex.Message);
OnException?.Invoke(this, "[FileFlow] Flush error: " + ex.Message);
}
}
}
catch (Exception ex)
{
WriteToConsoleError("[FileFlow] PeriodicFlushLoop error: " + ex.Message);
OnException?.Invoke(this, "[FileFlow] PeriodicFlushLoop error: " + ex.Message);
}
}
@@ -1958,7 +1930,7 @@ namespace EonaCat.LogStack.Flows
}
catch (Exception ex)
{
WriteToConsoleError("[FileFlow] RetentionLoop error: " + ex.Message);
OnException?.Invoke(this, "[FileFlow] RetentionLoop error: " + ex.Message);
}
}
@@ -2011,7 +1983,7 @@ namespace EonaCat.LogStack.Flows
}
catch (Exception ex)
{
WriteToConsoleError("[FileFlow] Retention error: " + ex.Message);
OnException?.Invoke(this, "[FileFlow] Retention error: " + ex.Message);
}
}
@@ -2058,50 +2030,30 @@ namespace EonaCat.LogStack.Flows
workingDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, workingDirectory.Substring(2));
}
// Attempt 1: Use the requested directory
WriteToConsoleError($"[FileFlow] Attempting to use log directory: {workingDirectory}");
if (Helpers.DirectoryPermissionHelper.EnsureDirectoryHierarchy(workingDirectory))
{
WriteToConsoleError($"[FileFlow] Successfully using log directory: {workingDirectory}");
return workingDirectory;
}
WriteToConsoleError($"[FileFlow] Failed to use log directory: {workingDirectory}. Diagnosis: {Helpers.DirectoryPermissionHelper.GetAccessIssueDiagnosis(workingDirectory)}");
// Attempt 2: Try to fix permissions on the requested directory
WriteToConsoleError($"[FileFlow] Attempting to fix permissions on: {workingDirectory}");
if (TryFixDirectoryPermissions(workingDirectory) && Helpers.DirectoryPermissionHelper.EnsureDirectoryHierarchy(workingDirectory))
{
WriteToConsoleError($"[FileFlow] Successfully fixed permissions and using log directory: {workingDirectory}");
return workingDirectory;
}
WriteToConsoleError($"[FileFlow] Failed to fix permissions on: {workingDirectory}");
string appDataDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "EonaCat.LogStack");
// Attempt 3: Fall back to AppData directory
string appDataDirectory = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"EonaCat.LogStack");
WriteToConsoleError($"[FileFlow] Attempting to use AppData log directory: {appDataDirectory}");
if (Helpers.DirectoryPermissionHelper.EnsureDirectoryHierarchy(appDataDirectory))
{
WriteToConsoleError($"[FileFlow] Successfully using AppData log directory: {appDataDirectory}");
OnDirectoryException?.Invoke(this, $"FileFlow: Could not use requested directory '{requestedDirectory}', fell back to '{appDataDirectory}'");
return appDataDirectory;
}
WriteToConsoleError($"[FileFlow] Failed to use AppData log directory: {appDataDirectory}. Diagnosis: {Helpers.DirectoryPermissionHelper.GetAccessIssueDiagnosis(appDataDirectory)}");
// Attempt 4: Fall back to TEMP directory
string tempDirectory = Path.GetTempPath();
WriteToConsoleError($"[FileFlow] Attempting to use TEMP log directory: {tempDirectory}");
try
{
if (Helpers.DirectoryPermissionHelper.CanWrite(tempDirectory))
{
WriteToConsoleError($"[FileFlow] Successfully using TEMP log directory: {tempDirectory}");
OnDirectoryException?.Invoke(this, $"FileFlow: Could not use requested directory '{requestedDirectory}' or AppData, fell back to TEMP directory '{tempDirectory}'");
return tempDirectory;
}
@@ -2111,8 +2063,6 @@ namespace EonaCat.LogStack.Flows
// Temp directory check failed
}
WriteToConsoleError($"[FileFlow] Failed to use TEMP log directory: {tempDirectory}. This is a critical error - logging may not work.");
// Final fallback: return the temp path anyway, even if it might not work
OnDirectoryException?.Invoke(this, $"FileFlow: Critical - could not find any writable directory. Attempting to use TEMP: '{tempDirectory}'");
return tempDirectory;
@@ -2144,7 +2094,6 @@ namespace EonaCat.LogStack.Flows
// Attempt to set everyone permissions (handles all platforms)
if (Helpers.DirectoryPermissionHelper.TrySetEveryonePermissions(dirPath))
{
WriteToConsoleError($"[FileFlow] Set permissions on: {dirPath}");
return true;
}
@@ -2157,13 +2106,12 @@ namespace EonaCat.LogStack.Flows
if ((dirInfo.Attributes & FileAttributes.ReadOnly) != 0)
{
dirInfo.Attributes &= ~FileAttributes.ReadOnly;
WriteToConsoleError($"[FileFlow] Cleared read-only attribute on: {dirPath}");
}
return true;
}
catch (Exception ex)
{
WriteToConsoleError($"[FileFlow] Failed to fix permissions: {ex.Message}");
OnException?.Invoke(this, $"[FileFlow] Failed to fix permissions: {ex.Message}");
return false;
}
}
@@ -43,6 +43,7 @@ namespace ServiceMonitoring
private readonly string _statusDirectory;
private readonly CancellationTokenSource _cts;
private readonly Action<ServiceStatus> _statusChangeTrigger;
public event EventHandler<string> OnException;
/// <summary>
/// Log fileSize (default: 10 MB)
@@ -300,7 +301,7 @@ namespace ServiceMonitoring
}
catch (Exception ex)
{
Console.WriteLine($"StatusFlow: Error writing to file: {ex.Message}");
OnException?.Invoke(null, $"StatusFlow: Error writing to file: {ex.Message}");
}
}
@@ -326,7 +327,7 @@ namespace ServiceMonitoring
}
catch (Exception ex)
{
Console.WriteLine($"StatusFlow: Error handling log file rollover: {ex.Message}");
OnException?.Invoke(null, $"StatusFlow: Error handling log file rollover: {ex.Message}");
}
}