Nikolai Samteladze Nikolai Samteladze - 10 days ago 6
C# Question

System.Diagnostic.Debug.WriteLine doesn't work in ASP.NET 5 Web API

Environment



I am writing a Web API using ASP.NET 5 1.0.0-rc1-update1 and Visual Studio Code on Mac. I scaffolded the default Web API app using Yeoman
generator-aspnet
. I am using DNX Mono to run the app via the default
web
command.

Missing output from
System.Diagnostics.Debug



I want to log debug output to Terminal or to Visual Studio Code Output. I tried to do so using
System.Diagnostics.Debug
class, but the code above produces zero output.

System.Disagnostics.Debug.WriteLine("This is your message");


What am I missing? Do I need to declare
DEBUG
symbol somewhere to see debug output?

Missing from
Microsoft.Extensions.Logging.Debug.DebugLogger



I also tried DebugLogger provided by
Microsoft.Extensions.Logging.Debug
package, but with no luck. Which I guess makes sense since it's a wrapper on top of
System.Diagnostics.Debug
. My
Startup.cs
configuration looked like:

public void Configure(IApplicationBuilder app,
IHostingEnvironment env,
ILoggerFactory loggerFactory)
{
loggerFactory.AddDebug(LogLevel.Debug);

// Configuring other middleware
}


I created
ILogger
in my controller as follows:

public ProductsController(ILoggerFactory logFactory)
{
_logger = logFactory.CreateLogger(nameof(ProductsController));
}


And used
ILogger
as follows:

public IActionResult Ping()
{
_logger.LogDebug("Debug message");
}

Answer

You have to add a TraceListener,

TextWriterTraceListener writer = new TextWriterTraceListener(System.Console.Out);
Debug.Listeners.Add(writer);

Also, set the DEBUG flag in the Visual Studio project properties