我正在关注本教程:https://andrewlock.net/using-dependency-injection-in-a-net-core-console-application/
并相应地安装了软件包,但日志未在任何地方打印。
这是我的代码:
var serviceProvider = new ServiceCollection()
.AddLogging()
.AddTransient<IFoo, Foo>(s =>
{
return new Foo()})
.BuildServiceProvider();
//configure console logging
serviceProvider
.GetService<ILoggerFactory>()
.AddConsole(LogLevel.Debug);
var logger = serviceProvider.GetService<ILoggerFactory>().CreateLogger<Program>();
logger.LogError("Starting application");
答案 0 :(得分:9)
结果是,控制台日志记录提供程序没有像net-core-1.x版本那样立即将消息刷新到控制台。它似乎在其他线程上运行。有关信息,请参见此网页:https://github.com/aspnet/Logging/issues/631
您可以在 Main 功能的末尾添加。
serviceProvider.Dispose();
,或者您可以添加 .AddDebug()
serviceProvider
.GetService<ILoggerFactory>()
.AddConsole(LogLevel.Debug)
.AddDebug();
答案 1 :(得分:0)
我进入了这个线程,试图解决为什么控制台日志记录不起作用的问题,这个答案记录了我发现的内容。 使用的软件包: Microsoft.Extensions.Logging Microsoft.Extensions.Logging.Console Microsoft.Extensions.Logging.Debug
应用程序: .NET Core 2.2控制台(Microsoft.NET.Sdk,netcoreapp2.2) 使用Microsoft.Extensions.Hosting.IHost,这就是我添加控制台日志记录的方式:
var hostBuilder = new HostBuilder()
// Other Configuration omitted for brevity
.ConfigureLogging((hostBuilderContext, loggingBuilder) =>
{
loggingBuilder.AddConfiguration(hostBuilderContext.Configuration.GetSection("Logging"));
loggingBuilder.AddConsole(options =>
{
options.IncludeScopes = true;
});
loggingBuilder.AddDebug();
});
// Start the application
await hostBuilder.RunConsoleAsync();
有趣的是,如果我在对AddConsole的调用中删除了options参数,则看不到任何日志记录。我相信是这样,因为我在发出日志语句的代码中使用了ILogger:
public class ClassThatLogs
{
private readonly ILogger<ClassThatLogs> _logger;
public ClassThatLogs(ILogger<ClassThatLogs> logger)
{
_logger = logger;
}
public void DoWork()
{
_logger.LogInformation("Working");
}
}
答案 2 :(得分:0)
如果我们只想登录控制台应用程序,那么创建一个新的ServiceProvider和HostBuilder可能不值得,因为清理或处置它时要格外谨慎。 相反,我建议只让Logging Factory使用logger,如果仅是我们想要的话,它将解决日志记录。
public static class ApplicationLogging
{
public static ILoggerFactory LogFactory { get; } = LoggerFactory.Create(builder =>
builder.ClearProviders();
// Clear Microsoft's default providers (like eventlogs and others)
builder.AddSimpleConsole(options =>
{
options.IncludeScopes = true;
options.SingleLine = true;
options.TimestampFormat = "hh:mm:ss ";
});
builder.AddApplicationInsights("instrument-key");
});
public static ILogger<T> CreateLogger<T>() => LogFactory.CreateLogger<T>();
}
static void Main(string[] args)
{
var logger = ApplicationLogging.CreateLogger<Program>();
logger.LogInformation("Let's do some work");
logger.LogWarning("I am going Crazy now!!!");
logger.LogInformation("Seems like we are finished our work!");
Console.ReadLine();
}