Console.SetOut does not work with ConsoleLogger

In my asp.net application, I’m using ConsoleLogger when debug.

services.AddLogging(builder => builder.AddConsole());

In integration tests, I’m trying to obtain console output like this

var strWriter = new StringWriter();
Console.SetOut(strWriter);

// some code that has a lot of logging

var consoleOutput = strWriter.ToString();

and consoleOutput is an empty string.

Is that issue with ConsoleLogger? How can I obtain console output?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Not sure why you want to do this and even more – I would say you should not do this, at least this way, but if you still want – you will need Console.SetOut before writing first messages to log, i.e. in case of ASP.NET Core it should look something like this:

public static StringWriter GlobalStringWriter = new StringWriter(); // use this "singleton"
    
public static void Main(string[] args)
{
    Console.SetOut(GlobalStringWriter);
    CreateHostBuilder(args).Build().Run();
}

Note that it will capture all concurrent requests (as it should do anyway).

If you take a look at source code for ConsoleLoggerProvider (which is actually setup with AddConsole call), you will see that in internally uses AnsiLogConsole/AnsiParsingLogConsole both of which internally capture current value of System.Console.Error/System.Console.Out in theirs constructors:

public AnsiParsingLogConsole(bool stdErr = false)
{
    _textWriter = stdErr ? System.Console.Error : System.Console.Out;
    _parser = new AnsiParser(WriteToConsole);
}

public AnsiLogConsole(bool stdErr = false)
{
    _textWriter = stdErr ? System.Console.Error : System.Console.Out;
}

So setting the string writer after this capture happened does not actually change where logs are written.

I would say that this is not very good approach and possibly you better think about implementing some kind of your own logger provider which will allow you to handle this usecase, or use an existing one and set it up for debug mode to write to file.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x