3

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

1 Answer 1

5

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" } } } 
Sign up to request clarification or add additional context in comments.

1 Comment

I was banging my head on this for a while. Turns out the default LogLevel was set to Warning and I was logging to Information... Thanks for the push.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.