Skip to content

Instantly share code, notes, and snippets.

@SamKr
Last active June 27, 2019 09:23
Show Gist options
  • Save SamKr/d7635d27b767c0ce3e46790277e43f56 to your computer and use it in GitHub Desktop.
Save SamKr/d7635d27b767c0ce3e46790277e43f56 to your computer and use it in GitHub Desktop.
Extensive console (+ file) logger, using a queue and color-coding
using System;
using System.Collections.Concurrent;
using System.ComponentModel;
using System.IO;
using System.Runtime.CompilerServices;
using System.Text.RegularExpressions;
using System.Threading;
using Coderr.Client;
namespace HDSupportIdentifier.Functions
{
public class ConsoleLogItem
{
public ConsoleLogItem()
{
//
}
public ConsoleLogItem(string msg, LogType type)
{
Message = msg;
Type = type;
}
public string Message { get; set; } = "";
public LogType Type { get; set; } = LogType.Info;
}
public enum LogType
{
Info = 0,
Warning = 1,
Error = 2,
Exception = 3,
Debug = 4
}
internal static class Log
{
private static ConcurrentQueue<ConsoleLogItem> LogQueue { get; } = new ConcurrentQueue<ConsoleLogItem>();
private static readonly BackgroundWorker BgQueueProcessor = new BackgroundWorker();
internal static void Initialise()
{
BgQueueProcessor.DoWork += BgQueueProcessorOnDoWork;
BgQueueProcessor.RunWorkerCompleted += BgQueueProcessorOnRunWorkerCompleted;
BgQueueProcessor.WorkerSupportsCancellation = true;
BgQueueProcessor.RunWorkerAsync();
}
internal static void Stop()
{
BgQueueProcessor?.CancelAsync();
}
private static void BgQueueProcessorOnRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs runWorkerCompletedEventArgs)
{
Console.ForegroundColor = ConsoleColor.White;
var msg = $"[{DateTime.Now:MM:dd HH:mm:ss}] [LOG] Logging afgebroken";
Console.WriteLine(msg);
WriteToLog(msg, LogType.Info);
}
private static void BgQueueProcessorOnDoWork(object sender, DoWorkEventArgs doWorkEventArgs)
{
while (!BgQueueProcessor.CancellationPending)
{
var ok = LogQueue.TryDequeue(out var logItem);
if (!ok) Thread.Sleep(TimeSpan.FromMilliseconds(25));
else PrintLog(logItem.Message, logItem.Type);
}
}
internal static void LogDebug(string debug)
{
AddToLog(debug, LogType.Debug);
}
internal static void LogInfo(string info)
{
AddToLog(info, LogType.Info);
}
internal static void LogWarning(string warning)
{
AddToLog(warning, LogType.Warning);
}
internal static void LogError(string error, [CallerMemberName] string callerName = "")
{
Err.Report(new Exception(error), callerName);
AddToLog($"[{callerName}] {error}", LogType.Error);
}
internal static void LogException(Exception stacktrace, object data, [CallerMemberName] string callerName = "")
{
Err.Report(stacktrace, data);
AddToLog($"[{callerName}] {stacktrace.Message}", LogType.Exception);
}
internal static void LogException(Exception stacktrace, [CallerMemberName] string callerName = "")
{
Err.Report(stacktrace, callerName);
AddToLog($"[{callerName}] {stacktrace.Message}", LogType.Exception);
}
internal static void AddToLog(string msg, LogType type)
{
var logItem = new ConsoleLogItem(msg, type);
LogQueue.Enqueue(logItem);
}
/// <summary>
/// Logt een bericht naar de console en eventueel logbestand
/// </summary>
/// <param name="msg"></param>
/// <param name="type"></param>
private static void PrintLog(string msg, LogType type)
{
try
{
// data klaarzetten
var datetime = $"{DateTime.Now:MM-dd HH:mm:ss}";
// hebben we een [*] datablok?
var regex = new Regex(@"\[.+\]");
var match = regex.Matches(msg);
var showMarkedNote = false;
var markedNote = "";
if (match.Count > 0)
{
markedNote = match[0].ToString();
showMarkedNote = true;
msg = msg.Replace($"{markedNote} ", "");
}
ConsoleColor msgColor;
switch (type)
{
case LogType.Info:
msgColor = ConsoleColor.White;
break;
case LogType.Warning:
msgColor = ConsoleColor.Yellow;
break;
case LogType.Error:
msgColor = ConsoleColor.Red;
break;
case LogType.Debug:
msgColor = ConsoleColor.Green;
break;
default:
msgColor = ConsoleColor.Gray;
break;
}
// printen naar console
Console.ForegroundColor = ConsoleColor.Gray;
Console.Write($"[{datetime}] ");
if (showMarkedNote)
{
Console.ForegroundColor = ConsoleColor.Cyan;
Console.Write($"{markedNote} ");
}
Console.ForegroundColor = msgColor;
Console.WriteLine(msg);
Console.ForegroundColor = ConsoleColor.Gray;
// wegschrijven
WriteToLog(msg, type);
}
catch (Exception ex)
{
Err.Report(ex, msg);
}
}
/// <summary>
/// Bericht wegschrijven naar logbestand
/// </summary>
/// <param name="msg"></param>
/// <param name="type"></param>
private static void WriteToLog(string msg, LogType type)
{
try
{
var fileTypeName = "";
switch (type)
{
case LogType.Info:
fileTypeName = "Log";
break;
case LogType.Warning:
fileTypeName = "WarningLog";
break;
case LogType.Error:
fileTypeName = "ErrorLog";
break;
case LogType.Exception:
fileTypeName = "ExceptionLog";
break;
case LogType.Debug:
fileTypeName = "DebugLog";
break;
}
if (!Directory.Exists(Variables.LogDirectory)) Directory.CreateDirectory(Variables.LogDirectory);
var curFile = Path.Combine(Variables.LogDirectory, $"[{DateTime.Now:yyyy-MM-dd}] {fileTypeName}.ini");
if (!File.Exists(curFile))
{
File.WriteAllText(curFile, "");
Thread.Sleep(10);
}
using (var stream = new FileStream(curFile, FileMode.Append, FileAccess.Write))
using (var writer = new StreamWriter(stream))
{
writer.WriteLine($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff}] {msg}");
writer.Close();
stream.Close();
}
}
catch (Exception ex)
{
Err.Report(ex, msg);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment