Skip to content
This repository has been archived by the owner on Oct 30, 2024. It is now read-only.

Commit

Permalink
2.0.1 - Made more memory efficient
Browse files Browse the repository at this point in the history
  • Loading branch information
atomsk-0 committed Feb 27, 2024
1 parent f8acf8c commit 91be5bb
Show file tree
Hide file tree
Showing 5 changed files with 54 additions and 26 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
Simple and easy to use logging system.
</p>

<img src="https://i.imgur.com/NKhyA4h.png" align="middle">
<img src="https://i.imgur.com/fmZhWRU.png" align="middle">

## How to use?
- Install Easy-Log to your project from nuget
Expand Down
8 changes: 4 additions & 4 deletions examples/Sample/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,10 @@
//var log = new Logger(options);

Log.SetOptions(options);
Log.WriteLine<Debug>("Hello World ARG 0: {} ARG 2: {}", 419, 500);
Log.WriteLine<Info>("Hello World ARG 0: {}", 613);
Log.WriteLine<Warning>("Hello World ARG 0: {}", 74);
Log.WriteLine<Error>("Hello World ARG 0: {}", 42);
Log.WriteLine<Debug>("Processing data - ID: {} Status: {}", 419, "In Progress");
Log.WriteLine<Info>("Task completed successfully - ID: {}", 613);
Log.WriteLine<Warning>("Unexpected input detected - Code: {}", "ABC123");
Log.WriteLine<Error>("Critical error occurred - Code: {}", "X987");

try
{
Expand Down
3 changes: 2 additions & 1 deletion src/EasyLog/Log.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,15 @@ namespace EasyLog;
public static class Log
{
private static Logger _logger = new(new LoggerOptions());

public static void SetOptions(LoggerOptions loggerOptions)
=> _logger = new Logger(loggerOptions);

public static void WriteLine<T>(string str, params object[] args) where T : ILogType, new()
=> _logger.WriteLine<T>(str, args);

public static void Write<T>(string str, params object[] args) where T : ILogType, new()
=> _logger.WriteLine<T>(str, args);
=> _logger.Write<T>(str, args);

public static void LogException(Exception ex)
=> _logger.LogException(ex);
Expand Down
43 changes: 30 additions & 13 deletions src/EasyLog/Logger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ public class Logger
{
private readonly StreamWriter? _fileStream;
private readonly LoggerOptions _loggerOptions;
private readonly Dictionary<Type, ILogType> _logTypeCache = new();

public Logger(LoggerOptions loggerOptions)
{
Expand All @@ -21,34 +22,50 @@ public Logger(LoggerOptions loggerOptions)
_fileStream = File.CreateText(loggerOptions.FileOutputPath);
_fileStream.AutoFlush = true;
}

public void WriteLine<T>(string str, params object[] args) where T : ILogType, new()
{
Write<T>($"{str}\n", args);
}

public void Write<T>(string str, params object[] args) where T : ILogType, new()
{
var formatted = Utils.Format(str, args);
var logType = new T();
var dat = "";
var logType = GetLogType<T>();
var sb = new StringBuilder();
if (_loggerOptions.ShowDateAndTime)
{
dat = $"[{DateTime.Now.ToLongTimeString()}] ";
sb.Append($"[{DateTime.Now.ToLongTimeString()}] ");
}

sb.Append($"{logType.Prefix}: ".Pastel(logType.PrefixColor));
sb.Append(Utils.Format(str, args));

if (_loggerOptions.ConsoleLogging)
{
var colorized = Utils.ColorizeMessageArgs(formatted, logType.ArgColor, args);
Console.Write(dat.Pastel(ConsoleColor.DarkGray) + $"{logType.Prefix}: ".Pastel(logType.PrefixColor) + colorized);
var colorized = Utils.ColorizeMessageArgs(sb.ToString(), logType.ArgColor, args);
Console.Write(colorized);
}


_fileStream?.Write($"{dat}{logType.Prefix}: {formatted}");

_fileStream?.Write(sb.ToString());
}

public void LogException(Exception ex)
{
WriteLine<Error>("Exception: {}\nMessage: {}\nStackTrace: {}", ex.GetType().FullName ?? "Unknown Source", ex.Message, ex.StackTrace ?? "No stacktrace");
var sb = new StringBuilder();
sb.AppendLine("An exception has occurred:".Pastel(GetLogType<Error>().PrefixColor));
sb.AppendLine(ex.GetType().FullName.Pastel(GetLogType<Error>().PrefixColor) ?? "Unknown Source".Pastel(GetLogType<Error>().PrefixColor));
sb.AppendLine(ex.Message.Pastel(GetLogType<Error>().PrefixColor));
sb.AppendLine(ex.StackTrace.Pastel(GetLogType<Error>().PrefixColor) ?? "No stacktrace".Pastel(GetLogType<Error>().PrefixColor));
WriteLine<Error>(sb.ToString());
}

private T GetLogType<T>() where T : ILogType, new()
{
var type = typeof(T);
if (!_logTypeCache.TryGetValue(type, out var logType))
{
logType = new T();
_logTypeCache[type] = logType;
}
return (T)logType;
}
}
24 changes: 17 additions & 7 deletions src/EasyLog/Utils.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Drawing;
using System.Text;
using Pastel;

namespace EasyLog;
Expand All @@ -7,22 +8,31 @@ internal static class Utils
{
internal static string ColorizeMessageArgs(string str, Color color, params object[] args)
{
return args.Select(arg => arg.ToString()!).Aggregate(str, (current, sArg) => current.Replace(sArg, sArg.Pastel(color)));
var sb = new StringBuilder(str);
foreach (var arg in args)
{
var sArg = arg.ToString()!;
sb.Replace(sArg, sArg.Pastel(color));
}
return sb.ToString();
}

/* This makes possible to just have {} instead like this {0}, {1}... */
internal static string Format(string str, params object[] args)
{
var sb = new StringBuilder(str);
for (var i = 0; i < args.Length; i++)
{
str = str.ReplaceFirst("{}", "{" + i + "}");
sb.ReplaceFirst("{}", "{" + i + "}");
}
return string.Format(str, args);
return string.Format(sb.ToString(), args);
}
internal static string ReplaceFirst(this string text, string search, string replace)

private static void ReplaceFirst(this StringBuilder sb, string search, string replace)
{
var pos = text.IndexOf(search, StringComparison.Ordinal);
return pos < 0 ? text : string.Concat(text.AsSpan(0, pos), replace, text.AsSpan(pos + search.Length));
var pos = sb.ToString().IndexOf(search, StringComparison.Ordinal);
if (pos < 0) return;
sb.Remove(pos, search.Length);
sb.Insert(pos, replace);
}
}

0 comments on commit 91be5bb

Please sign in to comment.