Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ensure log messages are written in order #46

Merged
merged 1 commit into from
Nov 22, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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