Reputation: 329
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.
Upvotes: 2
Views: 570
Reputation: 121
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.
Upvotes: 1
Reputation: 878
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.
Upvotes: 3