我使用asp.net core 1.1编写了一个简单的控制台应用程序。 我设置了Kestrel主机,并使用Configure方法注入了IApplicationBuilder和ILoggerFactory。 我在loggerFactory上调用AddConsole扩展。 然后我运行最简单的中间件,输出一条消息。 以下是应用程序代码:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
namespace DemoILoggerFactory
{
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseStartup<Program>()
.Build();
host.Run();
}
public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole();
app.Run( async context => {
await context.Response.WriteAsync("Message ..");
});
}
}
}
当我运行应用程序时,控制台输出以下内容:
Hosting environment: QQ
Content root path: F:\REPOS CORE 1.0.0\LOGGING\DemoILoggerFactory\src\DemoILoggerFactory\bin\Debug\netcoreapp1.0
Now listening on: http://localhost:5000
Application started. Press Ctrl+C to shut down.
当我访问“localhost:5000”时,控制台会显示以下日志信息:
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
Request starting HTTP/1.1 GET http://localhost:5000/
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
Request finished in 125.5854ms 200
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
Request starting HTTP/1.1 GET http://localhost:5000/favicon.ico
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
Request finished in 0.9471ms 200
后来我从Configure参数中移除了ILoggerFactory,并在Configure方法内实例化了一个。唯一的区别是Configure方法的签名和LoggerFactory的实例化。修改后的代码如下所示:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
namespace DemoILoggerFactory
{
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseStartup<Program>()
.Build();
host.Run();
}
public void Configure(IApplicationBuilder app)
{
ILoggerFactory loggerFactory = new LoggerFactory();
loggerFactory.AddConsole();
app.Run( async context => {
await context.Response.WriteAsync("Message ..");
});
}
}
}
现在,在运行应用程序之前,当我访问localhost:5000时,控制台窗口中会显示以下信息:
Hosting environment: QQ
Content root path: F:\REPOS CORE 1.0.0\LOGGING\DemoILoggerFactory\src\DemoILoggerFactory\bin\Debug\netcoreapp1.0
Now listening on: http://localhost:5000
Application started. Press Ctrl+C to shut down.
当我重新访问“localhost:5000”时,控制台中没有显示任何其他请求日志。
无论哪种情况,Project.json文件如下:
{
"version": "1.0.0-*",
"buildOptions": {
"emitEntryPoint": true
},
"dependencies": {
"Microsoft.NETCore.App": {
"type": "platform",
"version": "1.1.0"
},
"Microsoft.AspNetCore.Hosting": "1.1.0",
"Microsoft.AspNetCore.Server.Kestrel": "1.1.0",
"Microsoft.Extensions.Logging": "1.1.0",
"Microsoft.Extensions.Logging.Console": "1.1.0",
"Microsoft.AspNetCore.Http": "1.1.0"
},
"frameworks": {
"netcoreapp1.1": {
"imports": "dnxcore50"
}
}
}
我错过了什么?为什么这两个“LoggerFactory”实例行为不同?