.NET Core 2.1日志注册失败问题求助
Hey there! Let's walk through the common pitfalls that might be causing your logging setup to fail. I'll break this down into actionable steps to get your logs working properly.
1. Verify Your appsettings.json Logging Configuration
First, double-check that your appsettings.json has a valid Logging section—this is what your AddConfiguration call uses to set log levels. If this is missing or misconfigured, your logs might not show up at all. Here's a standard working example:
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" } }, // Other app settings... }
Make sure the log level for your target category (like your controllers) isn't set higher than the logs you're trying to write. For example, if Default is set to Error, LogInformation calls won't output anything.
2. Ensure You're Properly Injecting ILogger
Logging in .NET Core relies on dependency injection—don't try to instantiate a logger manually. In your controller (or service), inject a typed logger like this:
public class HomeController : Controller { private readonly ILogger<HomeController> _logger; // Inject the logger via constructor public HomeController(ILogger<HomeController> logger) { _logger = logger; } public IActionResult Index() { // Test with a simple info log _logger.LogInformation("Index action executed successfully"); return View(); } }
Using a typed logger (ILogger<T>) ensures your logs are categorized correctly and ties into your configuration settings.
3. Refine Your Program.cs Logging Setup
Your current ConfigureLogging code is on the right track, but let's tweak it to cover common gaps:
public static IWebHost BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args) .ConfigureLogging((hostContext, logging) => { // Uncomment below if you want to replace default providers entirely (optional) // logging.ClearProviders(); // Load configuration from the Logging section logging.AddConfiguration(hostContext.Configuration.GetSection("Logging")); // Add console logging with default formatting logging.AddConsole(); // Add debug logging to see logs in your IDE's debug output logging.AddDebug(); }) .UseStartup<Startup>() .Build();
A couple key notes:
WebHost.CreateDefaultBuilderalready adds default providers (Console, Debug, EventSource). Uselogging.ClearProviders()only if you want full control over which providers are active.- Adding
AddDebug()will make logs visible in your IDE's debug output pane (like Visual Studio's Output tab), which is super helpful for debugging.
4. Rule Out Interference from Startup.cs
Check if you've made any changes in Startup.cs that might override or remove logging services. Avoid code like this, which would break logging entirely:
// ❌ Avoid this—it removes core logging services services.RemoveAll(typeof(ILoggerFactory));
If you're configuring other services in ConfigureServices, make sure they aren't accidentally disrupting the logging setup.
5. Test and Verify Log Output
Run your application and check two places for logs:
- The console window where you launched the app (if using
dotnet run) - Your IDE's debug output pane (if running in debug mode)
If logs still don't appear, temporarily set the Default log level to Trace in appsettings.json—this will show all logs, helping you identify if your logs are being filtered out.
内容的提问来源于stack exchange,提问作者opensas

