2

I have a basic WebAPI .NET Core 2.2 project and I'm trying to log something:

// GET api/values
    [HttpGet]
    public ActionResult<IEnumerable<string>> Get()
    {
        System.Diagnostics.Trace.WriteLine("THIS IS A TEST");
        System.Diagnostics.Debug.WriteLine("THIS IS A TEST");
        return new string[] { "value1", "value2" };
    }

Unfortunately, nothing shows up in my output or console. I'm using Visual Studio Code. This is my first .NET project so don't hesitate to ask any questions, I'm super responsive.

Update I just downloaded DebugView and I'm able to see things that I log. Still looking for an alternative solution that doesn't rely on downloading a tool as logging is pretty basic.

sbattou
  • 319
  • 3
  • 18
  • 1
    You can take a look [here](https://stackoverflow.com/questions/1159755/where-does-system-diagnostics-debug-write-output-appear) – OlegI Dec 13 '18 at 15:05
  • 1
    @OlegI I can't seem to figure out how to add a listener. I tried adding the following: TextWriterTraceListener writer = new TextWriterTraceListener(System.Console.Out); Debug.Listeners.Add(writer); but it complains about 'Debug' does not contain a definition for 'Listeners' any idea? – sbattou Dec 13 '18 at 15:18
  • 1
    but you are not outputting into `Console`. you are outputting to `Trace` and `Debug`. those are different. that's why you see it in DebugView. Try `Console.WriteLine` or something if you need it quick – Andrey Borisko Dec 13 '18 at 15:55
  • @AndreyBorisko I tried `Console.WriteLine("Test");` and I still couldn't see it in the console – sbattou Dec 13 '18 at 16:15
  • @sbattoh I feel that [logger](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/logging/?view=aspnetcore-2.2) is what you are looking for – OlegI Dec 14 '18 at 08:52

2 Answers2

3

For logging, you can use NLog.Web.AspNetCore package. For more details refer the link given below:

https://github.com/NLog/NLog.Web/wiki/Getting-started-with-ASP.NET-Core-2

Thanks.

Jayoti Parkash
  • 868
  • 11
  • 26
1

ASP.NET Core has built in support for logging and allows developers to easily leverage their preferred logging framework as well. The logging service works with logging providers that store or display logs to a particular medium such as console, debug, trace listeners. For eg : The console provider displays the logs on the console and azure application insightt provider stores them in azure application insights, similarly we have many more providers like Nlog etc.

Now to simply log into your console.

Step 1 : Add a provider, i.e. console in your case. In your program.cs after the main method paste this

public static void Main(string[] args)
{
    var host = CreateWebHostBuilder(args).Build();

    var todoRepository = host.Services.GetRequiredService<ITodoRepository>();
    todoRepository.Add(new Core.Model.TodoItem() { Name = "Feed the dog" });
    todoRepository.Add(new Core.Model.TodoItem() { Name = "Walk the dog" });

    var logger = host.Services.GetRequiredService<ILogger<Program>>();
    logger.LogInformation("Seeded the database.");

    host.Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>()
        .ConfigureLogging(logging =>
        {
            logging.ClearProviders();
            logging.AddConsole(); \\adding to console
        });

Step 2 :Then inject the ILogger in your class through constructor

public class AboutModel
{
    private readonly ILogger _logger;

    public AboutModel(ILogger<AboutModel> logger)
    {
        _logger = logger;
    }
}

Step 3 : And then just mention the type of log you want to save and give its message.

public void OnGet()
    {
    Message = $"About page visited at {DateTime.UtcNow.ToLongTimeString()}";
    _logger.LogInformation("Message displayed: {Message}", Message);
    }

In the above method we are using information level log which specifies that program ends correctly.

Hope this helps.

abcbc
  • 123
  • 2
  • 12