Log to Console with .Net Core 2.0 web application

4.5k Views Asked by At

I'm giving my first steps with .Net Core

Just created a web Hello world with

dotnet new web

I can see there's some kind of logging enabled. I just want to log something to the Console.

But I don't know how to access the logger from

app.Run(async (context) =>
{
    await context.Response.WriteAsync("Hello World!!!");
});

I tried with Console.WriteLine but it obviously didn't work.

Also tried with NLog following this guide https://github.com/NLog/NLog.Web/wiki/Getting-started-with-ASP.NET-Core-(csproj---vs2017) but I don't know how to inject the logger.

I'm just trying to look around for educational purposes, not looking for a real logger, so perhaps there's a better/easier option.

1

There are 1 best solutions below

1
On

I could achieve it with this:

[...]
using Microsoft.Extensions.Logging;
[...]
namespace web
{
    public class Startup
    {
        ILogger log;
        public Startup(ILoggerFactory loggerFactory)
        {
            log = loggerFactory.CreateLogger("Logger");
        }
        [...]

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

            [...]

            app.Run(async (context) =>
            {
                log.LogInformation("logging!");
                await context.Response.WriteAsync("Hello World!");
            });
        }
    }
}

also had to add an appsettings.json file to the root of the project

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
     }
  }
}