如何在 ASP.NET Core 5.0 中 Startup.cs 的 ConfigureServices 方法中执行日志记录
How to perform logging in ConfigureServices method of Startup.cs in ASP.NET Core 5.0
将记录器的构造函数注入 Startup
在 ASP.NET Core 的早期版本中有效,因为为 Web 主机创建了一个单独的 DI 容器。到目前为止,只为通用主机创建了一个容器,请参阅 breaking change announcement。
Startup.cs
public class Startup
{
/// <summary> The configuration. </summary>
public IConfiguration Configuration { get; }
/// <summary> The web host environment. </summary>
public IWebHostEnvironment WebHostEnvironment { get; }
public Startup(IConfiguration configuration, IWebHostEnvironment webHostEnvironment)
{
Configuration = configuration;
WebHostEnvironment = webHostEnvironment;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddServices(Configuration); // This is a custom method, that adds multiple services to the container.
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILogger<Startup> logger) =>
app.UseComponents(env, Configuration, logger);
}
现在根据 MSDN,我已将我的 Startup.cs 修改如下:
public class Startup
{
/// <summary> The configuration. </summary>
public IConfiguration Configuration { get; }
public ILogger<Startup> Logger { get; set; }
/// <summary> The web host environment. </summary>
public IWebHostEnvironment WebHostEnvironment { get; }
public Startup(IConfiguration configuration, IWebHostEnvironment webHostEnvironment)
{
Configuration = configuration;
WebHostEnvironment = webHostEnvironment;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton((container) =>
{
var logger = container.GetRequiredService<ILogger<MyService>>();
return new Startup(Configuration, WebHostEnvironment) { Logger = logger };
}); // I know this is incorrect, but that my question- how do I correctly access logger in here?
services.AddServices(Configuration, Logger); // Logger => null
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILogger<Startup> logger) =>
app.UseComponents(env, Configuration, logger);
}
StartupExtension.ConfigureServices.cs
public static partial class StartupExtension
{
#region Internal Method
/// <summary> Adds all the services required by the DemoUsageApp. </summary>
/// <param name="services">The services, <see cref="IServiceCollection"/>.</param>
/// <param name="configuration">The configuration, <see cref="IConfiguration"/>.</param>
/// <param name="logger">The logger, <see cref="ILogger{Startup}"/>.</param>
/// <returns></returns>
internal static IServiceCollection AddServices(this IServiceCollection services, IConfiguration configuration, ILogger logger)
{
services.AddDotNetCoreServices(configuration, logger);
services.AddCrossCuttingServices(configuration, logger);
return services;
}
#endregion Internal Method
#region Private Methods
/// <summary> Adds .NET Core services. </summary>
/// <param name="services">The services, <see cref="IServiceCollection"/>.</param>
/// <param name="configuration">The configuration, <see cref="IConfiguration"/>.</param>
/// <param name="logger">The logger, <see cref="ILogger{Startup}"/>.</param>
/// <returns></returns>
private static IServiceCollection AddDotNetCoreServices(this IServiceCollection services, IConfiguration configuration, ILogger logger)
{
logger.LogInformation("---- Adding .NET Core components ----");
services.AddMvc();
services.AddControllers();
logger.LogInformation("---- Successfully added .NET Core components ----");
return services;
}
/// <summary> Adds Cross-Cutting services. </summary>
/// <param name="services">The services, <see cref="IServiceCollection"/>.</param>
/// <param name="configuration">The configuration, <see cref="IConfiguration"/>.</param>
/// <param name="logger">The logger, <see cref="ILogger{Startup}"/>.</param>
/// <returns></returns>
private static IServiceCollection AddCrossCuttingServices(this IServiceCollection services, IConfiguration configuration, ILogger logger)
{
logger.LogInformation("---- Adding Cross-Cutting components ----");
services.AddSql(configuration, logger); //This is a extension methods, that adds Sql services (which are also completely custom) to the application.
logger.LogInformation("---- Successfully added Cross-Cutting components ----");
return services;
}
#endregion Private Methods
}
问题-如何在Startup.cs的ConfigureServices方法中访问Logger,以便我可以将其传递给其他向容器添加自定义服务的自定义扩展方法?
注意: 为 Microsoft 和 Serilog Logger(可选)请求的解决方案。
更新 1: 正如@MathewBeck 在他的第二条评论中指出的那样,我已经有了 Program.cs
:
的以下结构
public class Program
{
#region Public Methods
/// <summary> Main method, the entry-point of the application. </summary>
/// <param name="args">The args <see cref="string[]"/></param>
public static void Main(string[] args)
{
var host = CreateHostBuilder(args).Build();
var logger = host.Services.GetRequiredService<ILogger<Program>>();
logger.LogInformation("Host created.");
host.Run();
}
/// <summary> Creates the host builder. </summary>
/// <param name="args">The args <see cref="string[]"/></param>
/// <returns></returns>
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
//.ConfigureLogging(loggingBuilder =>
//{
// loggingBuilder.ClearProviders();
// loggingBuilder.AddConsole();
// loggingBuilder.AddDebug();
// loggingBuilder.AddEventLog();
// loggingBuilder.AddEventSourceLogger();
//})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
webBuilder.UseConfiguration(GetConfiguration());
});
#endregion Public Methods
#region Private Methods
/// <summary> Gets the configuration. </summary>
/// <returns></returns>
private static IConfiguration GetConfiguration()
{
var env = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Development";
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", true, true)
.AddJsonFile($"appsettings.{env}.json", true, true);
return builder.Build();
}
#endregion Private Methods
}
如果您使用 NLog,最简单的登录方式 startup.cs 是添加私有 属性.
private readonly NLog.ILogger _log;
然后在你的构造函数中使用
_log = NLog.LogManager.GetCurrentClassLogger();
ASP.NET 5.0
我使用了 .NET 5.0 中引入的 Control Startup class activation 功能 -
引用MSDN文档-
An additional UseStartup overload has been added that lets an app provide a factory method for controlling Startup class activation. Controlling Startup class activation is useful to pass additional parameters to Startup that are initialized along with the host
public class Program
{
public static async Task Main(String[] args)
{
var loggerFactory = LoggerFactory
.Create(builder =>
{
builder.ClearProviders();
builder.AddConsole();
});
var logger = loggerFactory.CreateLogger<Program>();
var host = Host.CreateDefaultBuilder()
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup(context => new Startup(ILogger<Program> logger, /*based on the ctor of startup one can pass the required arguments here*/)
})
.Build();
await host.RunAsync();
}
}
将记录器的构造函数注入 Startup
在 ASP.NET Core 的早期版本中有效,因为为 Web 主机创建了一个单独的 DI 容器。到目前为止,只为通用主机创建了一个容器,请参阅 breaking change announcement。
Startup.cs
public class Startup
{
/// <summary> The configuration. </summary>
public IConfiguration Configuration { get; }
/// <summary> The web host environment. </summary>
public IWebHostEnvironment WebHostEnvironment { get; }
public Startup(IConfiguration configuration, IWebHostEnvironment webHostEnvironment)
{
Configuration = configuration;
WebHostEnvironment = webHostEnvironment;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddServices(Configuration); // This is a custom method, that adds multiple services to the container.
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILogger<Startup> logger) =>
app.UseComponents(env, Configuration, logger);
}
现在根据 MSDN,我已将我的 Startup.cs 修改如下:
public class Startup
{
/// <summary> The configuration. </summary>
public IConfiguration Configuration { get; }
public ILogger<Startup> Logger { get; set; }
/// <summary> The web host environment. </summary>
public IWebHostEnvironment WebHostEnvironment { get; }
public Startup(IConfiguration configuration, IWebHostEnvironment webHostEnvironment)
{
Configuration = configuration;
WebHostEnvironment = webHostEnvironment;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton((container) =>
{
var logger = container.GetRequiredService<ILogger<MyService>>();
return new Startup(Configuration, WebHostEnvironment) { Logger = logger };
}); // I know this is incorrect, but that my question- how do I correctly access logger in here?
services.AddServices(Configuration, Logger); // Logger => null
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILogger<Startup> logger) =>
app.UseComponents(env, Configuration, logger);
}
StartupExtension.ConfigureServices.cs
public static partial class StartupExtension
{
#region Internal Method
/// <summary> Adds all the services required by the DemoUsageApp. </summary>
/// <param name="services">The services, <see cref="IServiceCollection"/>.</param>
/// <param name="configuration">The configuration, <see cref="IConfiguration"/>.</param>
/// <param name="logger">The logger, <see cref="ILogger{Startup}"/>.</param>
/// <returns></returns>
internal static IServiceCollection AddServices(this IServiceCollection services, IConfiguration configuration, ILogger logger)
{
services.AddDotNetCoreServices(configuration, logger);
services.AddCrossCuttingServices(configuration, logger);
return services;
}
#endregion Internal Method
#region Private Methods
/// <summary> Adds .NET Core services. </summary>
/// <param name="services">The services, <see cref="IServiceCollection"/>.</param>
/// <param name="configuration">The configuration, <see cref="IConfiguration"/>.</param>
/// <param name="logger">The logger, <see cref="ILogger{Startup}"/>.</param>
/// <returns></returns>
private static IServiceCollection AddDotNetCoreServices(this IServiceCollection services, IConfiguration configuration, ILogger logger)
{
logger.LogInformation("---- Adding .NET Core components ----");
services.AddMvc();
services.AddControllers();
logger.LogInformation("---- Successfully added .NET Core components ----");
return services;
}
/// <summary> Adds Cross-Cutting services. </summary>
/// <param name="services">The services, <see cref="IServiceCollection"/>.</param>
/// <param name="configuration">The configuration, <see cref="IConfiguration"/>.</param>
/// <param name="logger">The logger, <see cref="ILogger{Startup}"/>.</param>
/// <returns></returns>
private static IServiceCollection AddCrossCuttingServices(this IServiceCollection services, IConfiguration configuration, ILogger logger)
{
logger.LogInformation("---- Adding Cross-Cutting components ----");
services.AddSql(configuration, logger); //This is a extension methods, that adds Sql services (which are also completely custom) to the application.
logger.LogInformation("---- Successfully added Cross-Cutting components ----");
return services;
}
#endregion Private Methods
}
问题-如何在Startup.cs的ConfigureServices方法中访问Logger,以便我可以将其传递给其他向容器添加自定义服务的自定义扩展方法?
注意: 为 Microsoft 和 Serilog Logger(可选)请求的解决方案。
更新 1: 正如@MathewBeck 在他的第二条评论中指出的那样,我已经有了 Program.cs
:
public class Program
{
#region Public Methods
/// <summary> Main method, the entry-point of the application. </summary>
/// <param name="args">The args <see cref="string[]"/></param>
public static void Main(string[] args)
{
var host = CreateHostBuilder(args).Build();
var logger = host.Services.GetRequiredService<ILogger<Program>>();
logger.LogInformation("Host created.");
host.Run();
}
/// <summary> Creates the host builder. </summary>
/// <param name="args">The args <see cref="string[]"/></param>
/// <returns></returns>
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
//.ConfigureLogging(loggingBuilder =>
//{
// loggingBuilder.ClearProviders();
// loggingBuilder.AddConsole();
// loggingBuilder.AddDebug();
// loggingBuilder.AddEventLog();
// loggingBuilder.AddEventSourceLogger();
//})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
webBuilder.UseConfiguration(GetConfiguration());
});
#endregion Public Methods
#region Private Methods
/// <summary> Gets the configuration. </summary>
/// <returns></returns>
private static IConfiguration GetConfiguration()
{
var env = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Development";
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", true, true)
.AddJsonFile($"appsettings.{env}.json", true, true);
return builder.Build();
}
#endregion Private Methods
}
如果您使用 NLog,最简单的登录方式 startup.cs 是添加私有 属性.
private readonly NLog.ILogger _log;
然后在你的构造函数中使用
_log = NLog.LogManager.GetCurrentClassLogger();
ASP.NET 5.0
我使用了 .NET 5.0 中引入的 Control Startup class activation 功能 -
引用MSDN文档-
An additional UseStartup overload has been added that lets an app provide a factory method for controlling Startup class activation. Controlling Startup class activation is useful to pass additional parameters to Startup that are initialized along with the host
public class Program
{
public static async Task Main(String[] args)
{
var loggerFactory = LoggerFactory
.Create(builder =>
{
builder.ClearProviders();
builder.AddConsole();
});
var logger = loggerFactory.CreateLogger<Program>();
var host = Host.CreateDefaultBuilder()
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup(context => new Startup(ILogger<Program> logger, /*based on the ctor of startup one can pass the required arguments here*/)
})
.Build();
await host.RunAsync();
}
}