CreateLogger()之前被调用过,并且只能被调用一次



我得到以下异常:

CreateLogger()之前被调用过,并且只能被调用一次。

我不知道CreateLogger()何时被调用两次。

我的配置如下:

public static void Main(string[] args)
{
try
{
var host = CreateHostBuilder(args).Build();
Log.Information("Starting host...");
host.Run();
}
catch (Exception ex)
{
Log.Fatal(ex, "Host terminated unexpectedly."); //HERE IS THE EXCEPTION: CreateLogger() was previously called and can only be called once.
}
finally
{
Log.CloseAndFlush();
}
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
webBuilder.UseSerilog((provider, context, loggerConfig) =>
{
loggerConfig.Configure(provider, Configuration);
});
});

我的扩展方法在调用库:

public static void Configure(this LoggerConfiguration loggerConfig,
IServiceProvider provider, IConfiguration config)
{
var sqlserverConnectionString = config["ConnectionStrings:S1"];
var sqlserverLogTable = config["Logging:S2"];
var rollingFileName = config["Logging:S3"];
var sinkOpts = new MSSqlServerSinkOptions();
sinkOpts.TableName = sqlserverLogTable;
sinkOpts.AutoCreateSqlTable = true;
var columnOpts = new ColumnOptions();
columnOpts.Store.Remove(StandardColumn.Properties);
columnOpts.Store.Add(StandardColumn.LogEvent);
columnOpts.LogEvent.DataLength = 2048;
columnOpts.PrimaryKey = columnOpts.TimeStamp;
columnOpts.TimeStamp.NonClusteredIndex = true;

loggerConfig
.ReadFrom.Configuration(config)
.Enrich.FromLogContext()
.Enrich.WithMachineName()
.Enrich.WithAssemblyName()
.Enrich.WithAssemblyVersion()
.Enrich.WithAspnetcoreHttpcontext(provider, GetContextInfo)
.WriteTo.File(rollingFileName)
.WriteTo.MSSqlServer(
connectionString: sqlserverConnectionString,
sinkOptions: sinkOpts,
columnOptions: columnOpts
).CreateLogger();
}

UseSerilog内部调用CreateLogger…所以:

  • 不要自己调用CreateLogger,让UseSerilog为你做
  • UseSerilog使用不同的过载,你给它你自己创建的ILogger

@C。奥古斯托·普罗耶特已经简单地解释过……这是一些细节,如果你想看的话。

你的代码在第183行执行,因为useReload变量应该是空的,如果你没有对记录器做任何事情,变量reloadable应该是假的,因为它最初评估为ReloadableLogger reloadable = Log.Logger as ReloadableLogger;(屏幕后面没有直接显示在该文件上)

相关内容

  • 没有找到相关文章

最新更新