Skip to content

Commit

Permalink
Add toggle for console logging
Browse files Browse the repository at this point in the history
  • Loading branch information
Banane9 committed Aug 26, 2024
1 parent da7f219 commit 1c27d4c
Show file tree
Hide file tree
Showing 5 changed files with 101 additions and 22 deletions.
3 changes: 1 addition & 2 deletions MonkeyLoader.ConsoleTest/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,7 @@ private static void Main(string[] args)
//}

var loader = new MonkeyLoader();
loader.LoggingController.Level = LoggingLevel.Trace;
loader.LoggingController.Handler = ConsoleLoggingHandler.Instance;
loader.Logging.Controller.Handler = ConsoleLoggingHandler.Instance;

loader.FullLoad();

Expand Down
9 changes: 9 additions & 0 deletions MonkeyLoader/Entrypoint.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using MonkeyLoader;
using MonkeyLoader.Logging;
using System;
using System.Diagnostics;
using System.IO;
Expand All @@ -15,6 +16,14 @@ public static void Start()
var loader = new MonkeyLoader.MonkeyLoader();
var log = loader.Logger;

if (ConsoleLoggingHandler.Instance.Connected)
{
Console.Title = $"{loader.GameName} - MonkeyLoader Console";
Console.BackgroundColor = ConsoleColor.Black;
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("Welcome to MonkeyLoader!");
}

try
{
foreach (var file in Directory.EnumerateFiles("./"))
Expand Down
83 changes: 74 additions & 9 deletions MonkeyLoader/Logging/ConsoleLoggingHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
Expand All @@ -13,43 +14,107 @@ namespace MonkeyLoader.Logging
/// </summary>
public sealed class ConsoleLoggingHandler : LoggingHandler
{
private static bool _hasConsole = false;

/// <summary>
/// Gets the instance of the <see cref="ConsoleLoggingHandler"/>.
/// </summary>
public static ConsoleLoggingHandler Instance { get; } = new ConsoleLoggingHandler();

/// <remarks>
/// For this logger, that means that a <see cref="Console"/> is available.
/// </remarks>
/// <inheritdoc/>
public override bool Connected => true;
public override bool Connected => _hasConsole;

private ConsoleLoggingHandler()
{ }
{
try
{
// Probably doesn't work on Linux Native, should work on Wine/Proton?
if (GetConsoleWindow() != IntPtr.Zero)
{
_hasConsole = true;
return;
}

if (!AllocConsole())
return;

_hasConsole = true;

var output = Console.OpenStandardOutput();
var writer = new StreamWriter(output) { AutoFlush = true };

Console.SetOut(writer);
}
catch
{
_hasConsole = false;
return;
}
}

/// <inheritdoc/>
public override void Debug(Func<object> messageProducer) => Log(messageProducer().ToString());
public override void Debug(Func<object> messageProducer)
{
Console.ForegroundColor = ConsoleColor.Cyan;
Log(messageProducer().ToString());
}

/// <inheritdoc/>
public override void Error(Func<object> messageProducer) => Log(messageProducer().ToString());
public override void Error(Func<object> messageProducer)
{
Console.ForegroundColor = ConsoleColor.Red;
Log(messageProducer().ToString());
}

/// <inheritdoc/>
public override void Fatal(Func<object> messageProducer) => Log(messageProducer().ToString());
public override void Fatal(Func<object> messageProducer)
{
Console.ForegroundColor = ConsoleColor.Red;
Log(messageProducer().ToString());
}

/// <inheritdoc/>
public override void Flush()
{ }

/// <inheritdoc/>
public override void Info(Func<object> messageProducer) => Log(messageProducer().ToString());
public override void Info(Func<object> messageProducer)
{
Console.ForegroundColor = ConsoleColor.White;
Log(messageProducer().ToString());
}

/// <summary>
/// Writes a message prefixed with a timestamp to the <see cref="Console"/>.
/// </summary>
/// <param name="message">The message to write.</param>
public void Log(string message) => Console.WriteLine($"[{DateTime.Now:HH:mm:ss:ffff}] {message}");
public void Log(string message)
{
Console.WriteLine($"[{DateTime.UtcNow:HH:mm:ss:ffff}] {message}");
Console.ForegroundColor = ConsoleColor.Gray;
}

/// <inheritdoc/>
public override void Trace(Func<object> messageProducer) => Log(messageProducer().ToString());
public override void Trace(Func<object> messageProducer)
{
Console.ForegroundColor = ConsoleColor.Cyan;
Log(messageProducer().ToString());
}

/// <inheritdoc/>
public override void Warn(Func<object> messageProducer) => Log(messageProducer().ToString());
public override void Warn(Func<object> messageProducer)
{
Console.ForegroundColor = ConsoleColor.Yellow;
Log(messageProducer().ToString());
}

[DllImport("kernel32.dll")]
private static extern bool AllocConsole();

[DllImport("kernel32.dll")]
private static extern IntPtr GetConsoleWindow();
}
}
2 changes: 1 addition & 1 deletion MonkeyLoader/Logging/FileLoggingHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ public override void Flush()
public void Log(string message)
{
lock (_streamWriter)
_streamWriter.WriteLine($"[{DateTime.Now:HH:mm:ss.ffff}] {message}");
_streamWriter.WriteLine($"[{DateTime.UtcNow:HH:mm:ss.ffff}] {message}");
}

/// <summary>
Expand Down
26 changes: 16 additions & 10 deletions MonkeyLoader/Logging/LoggingConfig.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,10 @@ public sealed class LoggingConfig : ConfigSection
public const string FileSearchPattern = "*" + FileExtension;
public const string TimestampFormat = "yyyy-MM-ddTHH-mm-ss";

public readonly DefiningConfigKey<string?> DirectoryPathKey = new("DirectoryPath", "The directory to write log files to. Changes will only take effect on restart.", () => "./MonkeyLoader/Logs");
public readonly DefiningConfigKey<int> FilesToPreserveKey = new("FilesToPreserve", "The number of recent log files to keep around. Set <1 to disable. Changes take effect on restart.", () => 16);
public readonly DefiningConfigKey<LoggingLevel> LevelKey = new("Level", "The logging level used to filter logging requests. May be ignored in the initial startup phase. Changes take effect immediately.", () => LoggingLevel.Info);
public readonly DefiningConfigKey<string?> DirectoryPathKey = new("DirectoryPath", "The directory to write log files to.\nChanges will only take effect on restart.", () => "./MonkeyLoader/Logs");
public readonly DefiningConfigKey<int> FilesToPreserveKey = new("FilesToPreserve", "The number of recent log files to keep around. Set <1 to disable.\nChanges take effect on restart.", () => 16);
public readonly DefiningConfigKey<LoggingLevel> LevelKey = new("Level", "The logging level used to filter logging requests. May be ignored in the initial startup phase.\nChanges take effect immediately.", () => LoggingLevel.Info);
public readonly DefiningConfigKey<bool> TryLoggingToConsoleKey = new("TryLoggingToConsole", "Whether to try logging to a console window.\nIf one isn't already present, it may be spawned. Spawning a console may only work on Windows and Wine or Proton.\nIf you close the console, Resonite will close too.\nThis may have some performance impact with high log levels.\nChanges take effect on restart.", () => false);

private readonly Lazy<string?> _currentLogFilePath;
private LoggingController _loggingController;
Expand All @@ -39,7 +40,7 @@ internal set

EnsureDirectory();
CleanLogDirectory();
SetupFileLogger();
SetupLoggers();
}
}

Expand All @@ -49,7 +50,6 @@ internal set
public override string Description => "Contains the options for where and what to log.";

public string? DirectoryPath => DirectoryPathKey;

public int FilesToPreserve => FilesToPreserveKey;

/// <inheritdoc/>
Expand All @@ -65,6 +65,8 @@ internal set
[MemberNotNullWhen(true, nameof(DirectoryPath), nameof(CurrentLogFilePath))]
public bool ShouldWriteLogFile => !string.IsNullOrWhiteSpace(DirectoryPathKey.GetValue());

public bool TryLoggingToConsole => TryLoggingToConsoleKey;

/// <inheritdoc/>
public override Version Version { get; } = new Version(1, 0, 0);

Expand Down Expand Up @@ -141,13 +143,17 @@ private void EnsureDirectory()
}
}

private void SetupFileLogger()
private void SetupLoggers()
{
if (!ShouldWriteLogFile)
return;
LoggingHandler loggingHandlers = MissingLoggingHandler.Instance;

if (TryLoggingToConsole && ConsoleLoggingHandler.Instance.Connected)
loggingHandlers += ConsoleLoggingHandler.Instance;

if (ShouldWriteLogFile)
loggingHandlers += new FileLoggingHandler(CurrentLogFilePath);

var fileLogger = new FileLoggingHandler(CurrentLogFilePath);
Controller.Handler += fileLogger;
Controller.Handler += loggingHandlers;
}
}
}

0 comments on commit 1c27d4c

Please sign in to comment.