Skip to content

.NET console logging uses a blocking collection which is not optimal for cloud-native applications #65264

Closed

Description

@maryamariyan

With the current design of console logging, there is a dedicated thread that writes outputs to console and once message queue is full (with 1024 messages in the queue) the console logger starts blocking the application.

This gist summarizes some trial and error experiments done to evaluate console logger against Console.WriteLine and in different scenarios. We couldn't prove that console logging is slower than console write line. Instead what we want to focus on for this issue is to make sure we don't get a sudden drop in RPS as soon as we hit the max queue size threshold limit.

We could add two configurations improvements to console logger: (1) to allow for both dropping logs and (2) making buffer size configurable.

Configuring buffer size

Given that the queue size today is limited for the blocking collection below:
https://source.dot.net/#Microsoft.Extensions.Logging.Console/ConsoleLoggerProcessor.cs,15

The easiest way is to just expose the queue length to make it configurable.

But instead the main proposal here is to keep track of how many bytes each item in the queue is collectively carrying to decide what the desired maximum buffer size for the blocking collection should be.

Dropping logs

Dropping logs would not be allowed by default. The way dropping of logs would work is "if enabled", then when blocking collection is full, the the console logger would throw the message away.

API Proposal

Since ConsoleLoggerProvider instantiates ConsoleLoggerProcessor, it makes sense to add these configurable options to ConsoleLoggerOptions which is inhected into ConsoleLoggerProvider:

public ConsoleLoggerProvider(IOptionsMonitor<ConsoleLoggerOptions> options, IEnumerable<ConsoleFormatter>? formatters)
{
_options = options;
_loggers = new ConcurrentDictionary<string, ConsoleLogger>();
SetFormatters(formatters);
ReloadLoggerOptions(options.CurrentValue);
_optionsReloadToken = _options.OnChange(ReloadLoggerOptions);
IConsole? console;
IConsole? errorConsole;
if (DoesConsoleSupportAnsi())
{
console = new AnsiLogConsole();
errorConsole = new AnsiLogConsole(stdErr: true);
}
else
{
console = new AnsiParsingLogConsole();
errorConsole = new AnsiParsingLogConsole(stdErr: true);
}
_messageQueue = new ConsoleLoggerProcessor(console, errorConsole);

namespace Microsoft.Extensions.Logging.Console
{
    /// <summary>
    /// Options for a <see cref="ConsoleLogger"/>.
    /// </summary>
    public class ConsoleLoggerOptions
    {
        public bool DisableColors { get; set; }
        public ConsoleLoggerFormat Format { get; set; }
        public string? FormatterName { get; set; }
        public bool IncludeScopes { get; set; }
        public LogLevel LogToStandardErrorThreshold { get; set; } = LogLevel.None;
        public string? TimestampFormat { get; set; }
        public bool UseUtcTimestamp { get; set; }

+        /// <summary>
+        /// Gets or sets the desired console logger behavior when queue becomes full. Defaults to <c>Wait</c>.
+        /// </summary>
+        public ConsoleLoggerBufferFullMode BufferFullMode { get; set; }

+        /// <summary>
+        /// Gets or sets the maximum buffer size before the queue becomes full. Defaults to <c>1MB</c>.
+        /// </summary>
+        public int MaxBufferSizeInBytes { get; set; } = 1048576;
    }

+    /// <summary>
+    /// Determines the console logger behaviour when queue becomes full.
+    /// </summary>
+    public enum ConsoleLoggerBufferFullMode
+    {
+        /// <summary>
+        /// Blocks the console thread once the queue limit is reached
+        /// </summary>
+        Wait,
+        /// <summary>
+        /// Drops new log messages when the queue is full
+        /// </summary>
+        DropNewest,
+    }
}

Alternative Design

Alternatively, MaxQueueBufferSizeInBytes could be nullable and when not specified use an unbounded queue:

-        public int MaxBufferSizeInBytes { get; set; } = 1048576;
+        public int? MaxBufferSizeInBytes { get; set; }

Questions with design

  • Do we want to allow the MaxQueueBufferSizeInBytes to be reconfigurable on reload?

Usage samples

using var loggerFactory = LoggerFactory.Create(builder =>
{
    builder
        .AddConsole(o => o.QueueFullMode = ConsoleLoggerQueueFullMode.DropNewest)
        .AddSimpleConsole(o => o.ColorBehavior = LoggerColorBehavior.Disabled);
});
Original Issue

Console logger not quick enough per request to log for real world production applications. Refer to aspnet/Logging#515 (comment)

With the current design console logging happens on a separate thread and once message queue is full (1000 messages) console logger could start blocking the application.

private const int _maxQueuedMessages = 1024;
private readonly BlockingCollection<LogMessageEntry> _messageQueue = new BlockingCollection<LogMessageEntry>(_maxQueuedMessages);

To improve this design, we could consider using a Channel rather than a blocking collection (refer to https://devblogs.microsoft.com/dotnet/an-introduction-to-system-threading-channels/). This would prevent something that would either block the app due to increased latency or cause out of memory exception.

With upside with the current blocking collection approach is that the order of logs gets respected but since the logging methods can be accompanied with timestamp, the channel approach may still be an improved approach overall to help with the goal of having a console logger that is performant enough for real world applications.

Activity

  1. ghost added
    untriaged
    on Feb 12, 2022
  2. removed
    untriaged
    on Feb 12, 2022
  3. added this to the 7.0.0 milestone on Feb 12, 2022
  4. added
    enhancement
    on Feb 12, 2022
  5. omariom commented on Feb 12, 2022

    @omariom
    Contributor

    BlockingCollection on my machine can accept 12 millions items a sec.

  6. davidfowl commented on Feb 12, 2022

    @davidfowl
    Member

    Right, it's the size of the queue that ends up being the problem for systems that are logging ALOT 😄

  7. danmoseley commented on Feb 12, 2022

    @danmoseley
    Contributor

    How does switching to a Channel help? Is it simply because it can be invoked async? Or because you're imagining it could provide back pressure and the system can drop lower priority events for a while?

  8. zlatanov commented on Feb 12, 2022

    @zlatanov
    Contributor

    Right, it's the size of the queue that ends up being the problem for systems that are logging ALOT

    I don't think the memory is the problem here. The blocking collection is throttling the application because the consumer part isn't able to keep up with the producer if too much is being logged at the at the same time and thus blocking the logging itself.

    BlockingCollection on my machine can accept 12 millions items a sec.

    The collection can accept as many items as your machine is able to consume at the same time. Here the Console related part is slow and thus causing the collection to fill and thus block.

    How does switching to a Channel help? Is it simply because it can be invoked async? Or because you're imagining it could provide back pressure and the system can drop lower priority events for a while?

    No back pressure here, anything that would cause blocking would have the same problem it has right now.

  9. stephentoub commented on Feb 13, 2022

    @stephentoub
    Member

    I'm not clear on the fundamental problem / goal here.

    In any producer/consumer system, if the consumer can't keep up with the producer, you have a few escape valves:

    • make the consumer faster
    • buffer more and more until hopefully the consumer can catch up
    • add more consumers
    • throttle the producer, aka backpressure. That back pressure can be applied via multiple means, e.g. blocking threads, triggering continuation via a callback, etc.
    • skip some data, aka lossy

    If the current system is applying backpressure via BlockingCollection and the goal is just to enable that backpressure to be applied synchronously, yeah, channels is likely a good answer. If the problem is that BlockingCollection has too much overhead and we still want blocking synchronously, channels might help, or we could fix BC, or we could devise a lighterweight handoff mechanism. If the problem is that the current bound is too low, raise the bound.

    But if the problem is that we don't want to slow down the producer and we don't want to buffer as much as we currently are, well, the remaining options are make the consumer faster or drop data (or similarly make the data smaller if the overall size is the concern). Adding more consumers in the case of writing to the console isn't really an option, since there's only one console, unless we fake a console and redirect some output to another storage mechanism.

    So... what's the actual problem and goal here?

  10. davidfowl commented on Feb 13, 2022

    @davidfowl
    Member

    The logging API is synchronous, so we will need to block when the queue limit is reached, that's the constraint. The problem is that systems that log ALOT (probably too much) hit this global 1024 queue limit, it starts blocking threads (probably thread pool threads) and that limit isn't configurable (people seem to have lots of memory and 1024 is hindsight was maybe too low for systems that log alot). I think the simple fix is to allow tweaking the limit. Whether we change to use a channel or something more manual I think is another issue.

    I don't think we want to drop log messages. There's no API to help producers determine which logs are droppable and which ones aren't so blocking I think is the ideal solution.

    We should also speed up the consumer (if there's any room to do so). I'm not sure if there's low hanging fruit.

  11. danmoseley commented on Feb 13, 2022

    @danmoseley
    Contributor

    @maryamariyan what was your reasoning for suggesting channels here?

  12. ShreyasJejurkar commented on Feb 13, 2022

    @ShreyasJejurkar
    Contributor

    As a user, I wish to have control over the maximum queued messages. 1024 limit is applicable to most users I guess but still, users should be able to configure this based on their machine/server. No matter how we solve this problem using Channels or anything else, at some point in the future, this is going to lag because of the hardcoded cap of maxQueuedMessages.
    So I guess we should make that limit configurable first, maybe via Options (if possible) or via env variable!

  13. maryamariyan commented on Feb 13, 2022

    @maryamariyan
    ContributorAuthor

    How does switching to a Channel help? Is it simply because it can be invoked async? Or because you're imagining it could provide back pressure and the system can drop lower priority events for a while?

    I think the current approach as-is should be fine and robust for low load scenarios but could cause latency issues with high load multi threaded requests. Seems like because of this in many cases console logging would be disabled for these high load logging heavy applications.

    @maryamariyan what was your reasoning for suggesting channels here?

    I'd imagine the console logger to behave as-is by default and we could make it configurable for scenarios in which there is high load of logging in cloud workloads, to allow the option to drop logs rather than block. Please correct me if I'm wrong but I assumed using Channel<T> could help with that.

    As a user, I wish to have control over the maximum queued messages. 1024 limit is applicable to most users I guess but still, users should be able to configure this based on their machine/server.

    I guess increasing the queue size would be another option but it could run the risk of running out of memory.

  14. 32 remaining items

  15. added
    api-ready-for-review
    blocking
    on May 19, 2022
  16. bartonjs commented on May 19, 2022

    @bartonjs
    Member

    Video

    • We changed the buffer size limit property to just be a simple queue length property
    • There was a lot of discussion around DropNewest vs DropOldest vs a more complicated policy (such as Drop(Something)UnlessError), so there may be more enum values needed in the near future.
    • We renamed all "Buffer" items to be "Queue"
    namespace Microsoft.Extensions.Logging.Console
    {
        /// <summary>
        /// Options for a <see cref="ConsoleLogger"/>.
        /// </summary>
        public partial class ConsoleLoggerOptions
        {
            /// <summary>
            /// Gets or sets the desired console logger behavior when queue becomes full.
            /// Defaults to <see cref="ConsoleLoggerQueueFullMode.Wait"/>.
            /// </summary>
            public ConsoleLoggerQueueFullMode QueueFullMode { get; set; }
    
            /// <summary>
            /// Gets or sets the maximum number of enqueued messages.
            /// </summary>
            public int MaxQueueLength { get; set; } = SomeDefault;
        }
    
        /// <summary>
        /// Determines the console logger behaviour when queue becomes full.
        /// </summary>
        public enum ConsoleLoggerQueueFullMode
        {
            /// <summary>
            /// Blocks the console thread once the queue limit is reached
            /// </summary>
            Wait,
            /// <summary>
            /// Drops new log messages when the queue is full
            /// </summary>
            DropNewest,
        }
    }
  17. added
    api-approved
    and removed
    blocking
    api-ready-for-review
    on May 19, 2022
  18. halter73 commented on May 19, 2022

    @halter73
    Member

    We should log a message write a line to stdout indicating exactly how many logs were dropped and where so it's obvious to anyone reviewing the logs why something fishy might be going on. We've already done this kind of thing in Microsoft.Extensions.Logging.AzureAppServices which you can see here: https://github.com/dotnet/aspnetcore/blob/bf50999cd8e60d4c683b772dffa9898794a8433a/src/Logging.AzureAppServices/src/BatchingLoggerProvider.cs#L96-L100

    Edit: Clarified that I meant writing a line to stdout instead of sending yet another message through the logging system. It's better if this message doesn't look like a normal log so it stands out more.

  19. eerhardt commented on May 19, 2022

    @eerhardt
    Member

    DropNewest

    Should this be renamed to DropWrite (or similar) to not confuse it with the same named option in Channels?

    /// <summary>Remove and ignore the newest item in the channel in order to make room for the item being written.</summary>
    DropNewest,
    /// <summary>Remove and ignore the oldest item in the channel in order to make room for the item being written.</summary>
    DropOldest,
    /// <summary>Drop the item being written.</summary>
    DropWrite

    I think it would be confusing for Channels' DropNewest to mean "drop the most recent item in the channel", and ConsoleLoggerQueueFullMode.DropNewest to mean "drop the item being written".

  20. bartonjs commented on May 19, 2022

    @bartonjs
    Member

    I think it would be confusing for Channels' DropNewest to mean "drop the most recent item in the channel", and ConsoleLoggerQueueFullMode.DropNewest to mean "drop the item being written".

    Yeah, I thought about suggesting that. Then wondered how pervasive Channels are, and if they're the odd one out there.

    I'd support changing it to DropAdd/DropWrite/whatever.

  21. noahfalk commented on May 20, 2022

    @noahfalk
    Member

    Should this be renamed to DropWrite (or similar) to not confuse it with the same named option in Channels?

    +1 for using DropWrite 👍

  22. ghost added
    in-pr
    on Jun 3, 2022
  23. ghost removed
    in-pr
    on Jun 21, 2022
  24. maryamariyan commented on Jun 21, 2022

    @maryamariyan
    ContributorAuthor

    @timmydo this went in for the next preview. hopefully you could get to test it out and help with feedback.

  25. ghost locked as resolved and limited conversation to collaborators on Jul 21, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-approvedarea-Extensions-Loggingenhancement

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions