Logging in ASP.NET Core

πŸ’‘ Concept Name

Logging in ASP.NET Core

πŸ“˜ Quick Intro

Logging in ASP.NET Core allows you to track application behavior and errors using built-in or third-party providers. It's fully integrated and supports structured logging, configuration via appsettings.json, and scopes.

🧠 Analogy / Short Story

Imagine flying an airplane without any dashboard indicators. That’s a system without logging. Logs are like your dashboardβ€”showing you the altitude, fuel, and alerts so you can act quickly. In web apps, logs tell you what’s happening under the hood.

πŸ”§ Technical Explanation

ASP.NET Core uses ILogger interface from Microsoft.Extensions.Logging. The system supports multiple logging providers like Console, Debug, EventSource, Application Insights, and more. You can configure log levels in appsettings.json or programmatically.

Structured logging (like Serilog) enhances this further with output formatting, sinks, and JSON logging for observability tools.

🎯 Purpose & Use Case

  • βœ… Debug issues and exceptions
  • βœ… Monitor application health
  • βœ… Track user actions or system events
  • βœ… Integrate with third-party tools like Seq, Kibana, or Splunk
  • βœ… Set up custom logging per environment

πŸ’» Real Code Example

Example: Logging setup in Program.cs


var builder = WebApplication.CreateBuilder(args);
builder.Logging.ClearProviders();
builder.Logging.AddConsole();
builder.Logging.AddDebug();

var app = builder.Build();

app.MapGet("/", (ILogger<Program> logger) => {
    logger.LogInformation("Hello logged at {time}", DateTime.UtcNow);
    return "Hello Logging!";
});

app.Run();
            

Configuration in appsettings.json:


"Logging": {
  "LogLevel": {
    "Default": "Information",
    "Microsoft": "Warning",
    "Microsoft.Hosting.Lifetime": "Information"
  }
}
            

❓ Interview Q&A

Q1: What is the use of ILogger in ASP.NET Core?
A: It’s used for logging messages to different providers like Console, Debug, etc.

Q2: How do you add a logging provider?
A: Using methods like AddConsole(), AddDebug() in Program.cs.

Q3: Where is logging configuration done?
A: In appsettings.json or Program.cs.

Q4: What is the purpose of ClearProviders()?

A: It removes the default logging providers to let you add only the ones you need.

Q5: Name some popular third-party logging libraries?

A: Serilog, NLog, Log4Net.

Q6: Can logs be filtered based on levels?

A: Yes. Levels like Information, Warning, Error, etc., can be configured per namespace.

Q7: Is logging asynchronous?

A: By default, most built-in providers are synchronous. Third-party providers may offer async logging.

Q8: How to log exception stack trace?

A: Use logger.LogError(ex, "message").

Q9: What are scopes in logging?

A: Used to group logs for a single operation or request.

Q10: Can logs be written to a database?

A: Yes, using providers like Serilog with SQL sinks.

πŸ“ MCQs

πŸ“ MCQs

Q1. Which interface is used for logging in ASP.NET Core?

  • ILogger
  • ILog
  • LoggerService
  • ILoggerFactory

Q2. Which provider logs to the command line?

  • Debug
  • Console
  • Trace
  • ApplicationInsights

Q3. Where do you configure log levels?

  • Startup.cs
  • Program.cs
  • appsettings.json
  • launchSettings.json

Q4. Which logging library supports sinks and structured logging?

  • Log4Net
  • NLog
  • Serilog
  • Console

Q5. What does ClearProviders() do?

  • Adds all providers
  • Resets logging
  • Removes all default logging providers
  • Flushes logs

Q6. Can you filter logs by category?

  • No
  • Yes
  • Only in Debug mode
  • Only in Release mode

Q7. What is the purpose of scopes in logging?

  • Change logging level
  • Enable async logging
  • Send to DB
  • Group logs by request or operation

Q8. Which method logs an error with stack trace?

  • WriteLog()
  • LogInfo()
  • LogError(ex, message)
  • Debug.Write()

Q9. Which package is required for Serilog?

  • Serilog.Base
  • Serilog.Core
  • Serilog.AspNetCore
  • Microsoft.Extensions.Logging

Q10. Which log level represents detailed debug info?

  • Error
  • Warning
  • Trace
  • Info

πŸ“„ PDF Download

Need a handy summary for your notes? Download this topic as a PDF!

Learn More About ASP.NET Core πŸš€

What is ASP.NET Core? πŸ‘‰ Explained
ASP.NET Core vs .NET Framework πŸ‘‰ Explained
Role of Kestrel Server in ASP.NET Core πŸ‘‰ Explained
Middleware & Request Pipeline πŸ‘‰ Explained
Dependency Injection in ASP.NET Core πŸ‘‰ Explained
Program.cs vs Startup.cs πŸ‘‰ Explained
Configuration & appsettings.json πŸ‘‰ Explained
Environment-specific settings πŸ‘‰ Explained
Writing Custom Middleware πŸ‘‰ Explained
Logging in ASP.NET Core πŸ‘‰ Explained
Static File Middleware πŸ‘‰ Explained
Routing fundamentals πŸ‘‰ Explained
Model Binding & Validation πŸ‘‰ Explained
Razor Pages vs MVC πŸ‘‰ Explained
Tag Helpers overview πŸ‘‰ Explained
Filters in MVC (Action, Authorization, Exception) πŸ‘‰ Explained
Web API controllers & content negotiation πŸ‘‰ Explained
Versioning ASP.NET Core Web API πŸ‘‰ Explained
Entity Framework Core introduction πŸ‘‰ Explained
Code-First vs Database-First in EF Core πŸ‘‰ Explained
Migrations in EF Core πŸ‘‰ Explained
LINQ fundamentals πŸ‘‰ Explained
Async/Await and async controllers πŸ‘‰ Explained
Error & Exception Handling Middleware πŸ‘‰ Explained
CORS configuration & usage πŸ‘‰ Explained
Authentication vs Authorization πŸ‘‰ Explained
ASP.NET Core Identity basics πŸ‘‰ Explained
JWT Authentication integration πŸ‘‰ Explained
Caching strategies πŸ‘‰ Explained
Session & State Management πŸ‘‰ Explained
File Upload handling πŸ‘‰ Explained
Health Checks & monitoring πŸ‘‰ Explained
Hosted Services & Background Tasks πŸ‘‰ Explained
Working with IWebHostEnvironment πŸ‘‰ Explained
IWebHostBuilder and WebHost vs Generic Host πŸ‘‰ Explained
Deployment to IIS, Kestrel, Nginx, Docker πŸ‘‰ Explained
Use of HTTP.sys Server πŸ‘‰ Explained
Configuration providers (JSON, env, CLI) πŸ‘‰ Explained
Handling Concurrency in EF Core πŸ‘‰ Explained
Model validation & custom validation πŸ‘‰ Explained
Dependency Injection service lifetimes πŸ‘‰ Explained
Security best practices (HTTPS, HSTS, CSP) πŸ‘‰ Explained
Authorization policies & claims πŸ‘‰ Explained
Rate limiting & request throttling πŸ‘‰ Explained
Health & metrics integration πŸ‘‰ Explained
Swagger/OpenAPI documentation πŸ‘‰ Explained
Blazor fundamentals πŸ‘‰ Explained
Razor Class Libraries (RCL) πŸ‘‰ Explained
SignalR real-time communication πŸ‘‰ Explained
Performance optimization & profiling πŸ‘‰ Explained
Share:

Tags:


Feedback Modal Popup