无法查看 Azure 日志流中的日志

Dar*_*ius 2 azure

在我的 Web Api 应用程序中,我有控制器:

[Route("api/[controller]")]
public class ValuesController : Controller
{
    // GET api/values
    [HttpGet]
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }

    // GET api/values/5
    [HttpGet("{id}")]
    public string Get(int id)
    {
        System.Diagnostics.Trace.TraceInformation("in get...");
        return "value";
    }
}
Run Code Online (Sandbox Code Playgroud)

我希望在发布日志时能够在 Azure 上看到“in get...”日志。在 Azure 上,在App Service LogsI 打开Application Logging (Filesystem)并将级别设置为Information。在 中Log Stream,当我转到该方法的 url 时,我在日志中看到:

正在连接... 2020-02-09T06:07:38 欢迎,您现在已连接到日志流服务。默认超时为 2 小时。使用应用程序设置 SCM_LOGSTREAM_TIMEOUT 更改超时(以秒为单位)。2020-02-09 06:08:07.158 +00:00 [信息] Microsoft.AspNetCore.Hosting.Internal.WebHost:请求启动 HTTP/1.1 GET http://testapi20200208104448.azurewebsites.net/api/values/5 2020- 02-09 06:08:07.159 +00:00 [信息] Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:使用参数执行操作方法 TestApi.Controllers.ValuesController.Get (TestApi) (5) - ModelState 有效 2020-02 -09 06:08:07.160 +00:00 [信息] Microsoft.AspNetCore.Mvc.Internal.ObjectResultExecutor:执行ObjectResult,写入值Microsoft.AspNetCore.Mvc.ControllerContext。

但我没有看到我的日志“in get...”

Iva*_*ang 5

这是 .NET core 的一个已知问题(但对于 .NET Framework,它可以很好地工作)。

作为 .NET Core Web 应用程序的解决方法,我建议您可以使用ILogger,它可以将消息写入应用程序日志。在Startup.cs->Configure方法中,重写Configure方法,如下所示:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
   //your other code

   //add the following 2 lines of code.
   loggerFactory.AddConsole();
   loggerFactory.AddDebug();

   app.UseStaticFiles();

   //your other code
}
Run Code Online (Sandbox Code Playgroud)

然后在ValuesController

public class ValuesController : Controller
{
   private readonly ILogger _logger; 

   public ValuesController(ILoggerFactory loggerFactory)
   {
      _logger = loggerFactory.CreateLogger<ValuesController>();
   }

   // GET api/values
   [HttpGet]
   public IEnumerable<string> Get()
   {
      return new string[] { "value1", "value2" };
   }

   // GET api/values/5
   [HttpGet("{id}")]
   public string Get(int id)
   {
      //System.Diagnostics.Trace.TraceInformation("in get...");

      //use ILogger here.
      _logger.LogInformation("in get...");
      return "value";
   }
}
Run Code Online (Sandbox Code Playgroud)