在以下控制台应用程序(.Net core 2.0)中,_logger.LogInformation()
中的_logger.LogError()
,Run()
的输出将不会显示。
static void Main(string[] args)
{
var services = new ServiceCollection();
ConfigureServices(services);
var serviceProvider = services.BuildServiceProvider();
var app = serviceProvider.GetService<Application>();
Task.Run(() => app.Run()).Wait();
// Console.WriteLine("Test"); // _logger.Information() will not output unless uncommented
// Console.ReadKey(); works too
}
private static void ConfigureServices(IServiceCollection services)
{
ILoggerFactory loggerFactory = new LoggerFactory().AddConsole().AddDebug();
services.AddSingleton(loggerFactory);
services.AddLogging();
IConfigurationRoot configuration = GetConfiguration();
services.AddSingleton(configuration);
var myOptions = new MyOptions();
configuration.GetSection("Settings").Bind(myOptions);
services.AddSingleton(myOptions);
services.AddTransient<Application>();
}
public class Application
{
ILogger _logger;
MyOptions _settings;
public Application(ILogger<Application> logger, MyOptions settings)
{
_logger = logger;
_settings = settings;
}
public async Task Run()
{
_logger.LogInformation($"Application start...");
_logger.LogError(ex.ToString());
}
}