【发布时间】:2017-05-28 11:04:07
【问题描述】:
我无法在我的应用程序中获得基本的LogTrace(...) 输出。这是一个再现:
- 使用 Visual Studio 2017 创建一个新的 ASP.NET Core 应用程序。
- (可选)注释掉
.UseApplicationInsights()以便重现更清晰 -
将
ValuesController.cs中的代码替换为:using System.Collections.Generic; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; namespace WebApplication1.Controllers { [Route("api/[controller]")] public class ValuesController : Controller { private readonly ILogger<ValuesController> logger; public ValuesController(ILogger<ValuesController> logger) { this.logger = logger; } [HttpGet] public IEnumerable<string> Get() { logger.LogError("ERROR!"); logger.LogWarning("WARN!"); logger.LogInformation("INFO!"); logger.LogTrace("TRACE!"); return new string[] { "value1", "value2" }; } } } -
将
appsettings.Development.json更改为:{ "Logging": { "IncludeScopes": false, "LogLevel": { "Default": "Trace", "System": "Information", "Microsoft": "Information" } } } 运行并查看调试输出
这导致:
我也尝试过调整 appsettings.json 文件中的值,但这也没有效果。
奇怪的是,将任一文件中的值更改为 "Error" 也没有任何作用。
底线/问题
我需要做什么才能使注入的ILogger<ValuesController> 尊重日志记录设置,包括Trace 级别?
脚注
下面是一些相关代码,这些代码将通过上述重现自动生成:
Startup.cs
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseMvc();
}
}
Program.cs
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.UseApplicationInsights()
.Build();
host.Run();
}
}
appsettings.json 默认:
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Warning"
}
}
}
【问题讨论】:
-
请注意...从 2.0 开始,此问题将发生重大变化(感谢 @Tseng )。我相应地更新了我的答案。
标签: c# asp.net-core .net-core .net-core-logging .net-core-configuration