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

Allow replacing Console.Out #130

Open
matkoch opened this issue Jul 10, 2022 · 2 comments
Open

Allow replacing Console.Out #130

matkoch opened this issue Jul 10, 2022 · 2 comments

Comments

@matkoch
Copy link
Contributor

matkoch commented Jul 10, 2022

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

@nblumhardt
Copy link
Member

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

@matkoch
Copy link
Contributor Author

matkoch commented Jul 18, 2022

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants