serilog-sinks-console icon indicating copy to clipboard operation
serilog-sinks-console copied to clipboard

Allow replacing Console.Out

Open matkoch opened this issue 3 years ago • 2 comments

Hi 👋

I was playing around to see if I could redirect all Console.Write calls to Serilog. The problem is that ConsoleSink itself will use Console.Out and Console.Error to write the formatted output. My suggestion is to allow capturing the initial values of these two properties. That would allow replacing the original text writers once the sink was created, and the sink would still use the old writer (hence, we don't run into meaningless StackOverflow).

https://github.com/serilog/serilog-sinks-console/blob/dev/src/Serilog.Sinks.Console/Sinks/SystemConsole/ConsoleSink.cs#L85

matkoch avatar Jul 10 '22 03:07 matkoch

Thanks for the suggestion @matkoch!

I think doing this might open up the possibility of causing the inverse issue, for people who expect to be able to change Console.Out and Console.Error at runtime, and have Serilog respect those new values.

Given that it's a bit of an edge case, I don't think we'd tackle this change right now, but you might find that you can do what you're after using Serilog.Sinks.TextWriter and ExpressionTemplate from Serilog.Expressions:

Log.Logger = new LoggerConfiguration()
    .WriteTo.TextWriter(Console.Out, new ExpressionTemplate("...", TemplateTheme.Literate))
    .CreateLogger();

// Now switch Console.Out...

Just checking in on Serilog.Sinks.TextWriter, I can't believe we haven't updated it in 6 years, it's still an XPROJ! Pretty sure it will work for this case, though :-)

Let me know if this helps, Nick

nblumhardt avatar Jul 14 '22 23:07 nblumhardt

Correct me if I'm wrong, but this only seems to work with ANSI colors, and not with system-colors as in SystemConsoleTheme. This is essential for my scenario since not all terminals are supporting ANSI.

By the way, I didn't mention it before, but what I envisioned was to introduce a parameter like captureInitialConsoleOut with default false, so that existing behavior won't be changed.

matkoch avatar Jul 18 '22 18:07 matkoch