所以我最近开始创建和编写ASP.NET Core 2.0应用程序。我一直在使用Serilog进行日志记录工作,我可以在本地计算机上写入.txt日志文件。这个文件的路径写在我的appsettings.json文件中,该文件从我的Startup.ConfigureServices方法读取就好了。
但是,当我的ASP.NET核心应用程序成功启动或不启动时,我想从我的Program类登录。问题是:我如何读取我的appsettings.json文件以从我的Program类获取日志文件路径,以便我可以登录到该文件?
我试过了:
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
var configuration = builder.Build();
Log.Logger = new LoggerConfiguration()
.MinimumLevel
.Information().
WriteTo.RollingFile(configuration.GetValue<string>("LogFilePath") + "-{Date}.txt", LogEventLevel.Information)
//.WriteTo.Log4Net()
.CreateLogger();
从我的Program.cs但它无法读取我的appsettings.json。 我已经仔细检查了GetValue是否使用了正确的密钥。
答案 0 :(得分:2)
我认为您SetBasePath
上可能遗漏了ConfigurationBuilder
(请参阅简单配置部分here)。请参阅下面的示例,该示例还适用于特定于环境的appsettings覆盖。
public class Program
{
public static int Main(string[] args)
{
var builder = new ConfigurationBuilder()
.SetBasePath(System.IO.Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json", optional: true)
.AddEnvironmentVariables();
var configuration = builder.Build();
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Information()
.WriteTo.RollingFile(configuration.GetValue<string>("LogFilePath") + "-{Date}.txt", LogEventLevel.Information)
.CreateLogger();
try
{
Log.Information("Starting web host");
BuildWebHost(args).Run();
return 0;
}
catch (Exception ex)
{
Log.Fatal(ex, "Web Host terminated unexpectedly");
return 1;
}
finally
{
Log.CloseAndFlush();
}
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureLogging((ctx, builder) =>
{
builder.ClearProviders();
builder.SetMinimumLevel(LogLevel.Information);
builder.AddSerilog();
})
.UseStartup<Startup>()
.Build();
}
答案 1 :(得分:1)
我通过使用带有logger配置的静态Log类来修复它:
内部Startup.ConfigureServices()
Log.Logger = new LoggerConfiguration()
.MinimumLevel
.Information().
WriteTo.RollingFile(Configuration.GetValue<string>("LogFilePath") + "-{Date}.txt", LogEventLevel.Information)
.CreateLogger();
//all the services.add code...
在我的Program.cs中
public class Program
{
public static void Main(string[] args)
{
var host = BuildWebHost(args);
using (var scope = host.Services.CreateScope())
{
var services = scope.ServiceProvider;
try
{
var context = services.GetRequiredService<UpdateServerContext>();
DbInitializer.Initialize(context);
}
catch (Exception ex)
{
Log.Error(ex, "An error occurred while seeding the database.");
}
}
try
{
Log.Information("Starting web host");
host.Run();
BuildWebHost(args).Run();
}
catch (Exception ex)
{
Log.Fatal(ex, "Starting web host failed.");
}
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseSerilog()
.UseStartup<Startup>()
.Build();
}
通过这种方式,只有在已经从Startup类创建时才使用Log。
答案 2 :(得分:0)
您可以这样做:
notification