Skip to content

Commit

Permalink
Ensure log messages are written in order
Browse files Browse the repository at this point in the history
  • Loading branch information
Banane9 committed Nov 22, 2024
1 parent 66b6b2b commit 4ab3717
Showing 1 changed file with 13 additions and 4 deletions.
17 changes: 13 additions & 4 deletions MonkeyLoader/Logging/LoggingController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ public sealed class LoggingController

private readonly Timer _flushTimer;
private bool _autoFlush = true;

private LoggingHandler _handler = MissingLoggingHandler.Instance;
private Task _lastLogTask = Task.CompletedTask;

/// <summary>
/// Gets or sets whether this logger will automatically trigger <see cref="Flush()">flushing</see> of messages.
Expand Down Expand Up @@ -122,7 +122,7 @@ internal void LogInternal(LoggingLevel level, string identifier, Func<object> me
if (!ShouldLog(level))
return;

Task.Run(() =>
QueueLogging(() =>
{
LogLevelToLogger(level)(MakeMessageProducer(level, identifier, messageProducer));

Expand All @@ -135,7 +135,7 @@ internal void LogInternal(LoggingLevel level, string identifier, IEnumerable<Fun
if (!ShouldLog(level))
return;

Task.Run(() =>
QueueLogging(() =>
{
var logger = LogLevelToLogger(level);

Expand All @@ -151,7 +151,7 @@ internal void LogInternal(LoggingLevel level, string identifier, IEnumerable<obj
if (!ShouldLog(level))
return;

Task.Run(() =>
QueueLogging(() =>
{
var logger = LogLevelToLogger(level);

Expand Down Expand Up @@ -236,6 +236,15 @@ private Func<object> MakeMessageProducer(LoggingLevel level, string identifier,
private Func<object> MakeMessageProducer(LoggingLevel level, string identifier, object message)
=> () => $"{LogLevelToString(level)} [{identifier}] {message}";

private void QueueLogging(Action handleLogging)
{
lock (this)
{
_lastLogTask = _lastLogTask.ContinueWith(_ => handleLogging(),
TaskContinuationOptions.RunContinuationsAsynchronously);
}
}

private sealed class DeferredMessage
{
public readonly LoggingLevel LoggingLevel;
Expand Down

0 comments on commit 4ab3717

Please sign in to comment.