Repository navigation
Description
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:
runtime/src/libraries/Microsoft.Extensions.Logging.Console/src/ConsoleLoggerProvider.cs
Lines 41 to 62 in 42d1644
| 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
MaxQueueBufferSizeInBytesto 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.
runtime/src/libraries/Microsoft.Extensions.Logging.Console/src/ConsoleLoggerProcessor.cs
Lines 14 to 16 in 78c6505
| 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
omariom commentedon Feb 12, 2022
BlockingCollection on my machine can accept 12 millions items a sec.
davidfowl commentedon Feb 12, 2022
Right, it's the size of the queue that ends up being the problem for systems that are logging ALOT 😄
danmoseley commentedon Feb 12, 2022
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?
zlatanov commentedon Feb 12, 2022
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.
The collection can accept as many items as your machine is able to consume at the same time. Here the
Consolerelated part is slow and thus causing the collection to fill and thus block.No back pressure here, anything that would cause blocking would have the same problem it has right now.
stephentoub commentedon Feb 13, 2022
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:
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?
davidfowl commentedon Feb 13, 2022
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.
danmoseley commentedon Feb 13, 2022
@maryamariyan what was your reasoning for suggesting channels here?
ShreyasJejurkar commentedon Feb 13, 2022
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!
maryamariyan commentedon Feb 13, 2022
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.
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.I guess increasing the queue size would be another option but it could run the risk of running out of memory.
32 remaining items
bartonjs commentedon May 19, 2022
Video
halter73 commentedon May 19, 2022
We should
log a messagewrite 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-L100Edit: 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.
eerhardt commentedon May 19, 2022
Should this be renamed to
DropWrite(or similar) to not confuse it with the same named option in Channels?runtime/src/libraries/System.Threading.Channels/src/System/Threading/Channels/BoundedChannelFullMode.cs
Lines 11 to 16 in 6ca8c9b
I think it would be confusing for Channels'
DropNewestto mean "drop the most recent item in the channel", andConsoleLoggerQueueFullMode.DropNewestto mean "drop the item being written".bartonjs commentedon May 19, 2022
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.
noahfalk commentedon May 20, 2022
+1 for using DropWrite 👍
maryamariyan commentedon Jun 21, 2022
@timmydo this went in for the next preview. hopefully you could get to test it out and help with feedback.