2021年5月5日星期三

Quartz.Net + AspNetCore + SeriLog : no Log output

I have written a windows service, asp.netcore + quartz + serilog but for some reason the DATABASE log only writes the first log statement outside of the hostbuilder but further stays empty (serilog sqlserver sink)

So its specific to https://github.com/serilog/serilog-sinks-mssqlserver

So I assume I do something wrong around the hostbuilder. So the .UseSerilog does not take the sql log config but it does take the loggers in appsettings. So tis the Log.Logger created logger that needs to be somewhere else i think


I have one startup class:

public static class Program  {      static readonly LoggerProviderCollection Providers = new LoggerProviderCollection();      public static string GetCurrentProcessPath()      {          var pathToExe = Process.GetCurrentProcess().MainModule.FileName;          var pathToContentRoot = Path.GetDirectoryName(pathToExe);          return pathToContentRoot;      }      public static IConfiguration Configuration { get; } = new ConfigurationBuilder()          .SetBasePath(GetCurrentProcessPath())          .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)          .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true)           .AddEnvironmentVariables()          .Build();        public static ColumnOptions SeriLogColumns()      {          ColumnOptions columnOptions = new();          columnOptions.Store.Remove(StandardColumn.MessageTemplate);          columnOptions.Store.Remove(StandardColumn.Properties);          columnOptions.Store.Add(StandardColumn.LogEvent);          columnOptions.DisableTriggers = true;          columnOptions.ClusteredColumnstoreIndex = false;          columnOptions.Store.Remove(StandardColumn.Id);          columnOptions.TimeStamp.ConvertToUtc = true;          columnOptions.AdditionalColumns = new Collection<SqlColumn>          {              new SqlColumn { ColumnName = "RequestPath", PropertyName = "RequestPath", DataType = SqlDbType.NVarChar, DataLength = 255 },              new SqlColumn { ColumnName = "SourceContext", PropertyName = "SourceContext", DataType = SqlDbType.NVarChar, DataLength = 255 },              new SqlColumn { ColumnName = "ActionName", PropertyName = "ActionName", DataType = SqlDbType.NVarChar, DataLength = 255 },                new SqlColumn { ColumnName = "ThreadId", PropertyName = "ThreadId", DataType = SqlDbType.NVarChar, DataLength = 255 },              new SqlColumn { ColumnName = "RequestId", PropertyName = "RequestId", DataType = SqlDbType.NVarChar, DataLength = 255 },              new SqlColumn { ColumnName = "ActionId", PropertyName = "ActionId", DataType = SqlDbType.NVarChar, DataLength = 255 },                new SqlColumn { ColumnName = "MachineName", PropertyName = "MachineName", DataType = SqlDbType.NVarChar, DataLength = 255 },              new SqlColumn { ColumnName = "MemoryUsage", PropertyName = "MemoryUsage", DataType = SqlDbType.NVarChar, DataLength = 16 }          };          return columnOptions;      }          public static LoggerConfiguration LoggerConfiguration()      {          return new LoggerConfiguration()              .ReadFrom.Configuration(Configuration)              .MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Warning)              .MinimumLevel.Override("Quartz", LogEventLevel.Warning)              .WriteTo.Providers(Providers)              .Enrich.WithExceptionDetails(new DestructuringOptionsBuilder()                  .WithDefaultDestructurers()                  .WithDestructurers(new[] { new DbUpdateExceptionDestructurer() }))              .WriteTo.MSSqlServer(                  connectionString: Configuration.GetConnectionString("ABC"),                  sinkOptions: new Serilog.Sinks.MSSqlServer.MSSqlServerSinkOptions                  {                      TableName = "_LogEvent_WorkerService",                      SchemaName = "ABC",                      BatchPeriod = new TimeSpan(0, 0, 5),                      AutoCreateSqlTable = true,                      BatchPostingLimit = 50,                      EagerlyEmitFirstEvent = true                  },                  columnOptions: SeriLogColumns()                  );      }        static async Task Main(string[] args)      {                     Log.Logger = LoggerConfiguration().CreateLogger();            try          {              Log.Information("Starting Background Job Service"); // this works                            var hostBuilder = new HostBuilder()                  .ConfigureServices((context, services) => {                  Log.Information("This will never show");                        services.AddSingleton(_ => Configuration);                        // Mapper                      services.AddAutoMapper(typeof(Program));                      AutoMapperConfig.Register(services);                        services.AddQuartz(q =>                      {                          q.SchedulerId = "JobScheduler";                          q.SchedulerName = "Job Scheduler";                          q.UseMicrosoftDependencyInjectionJobFactory();                          q.UseSimpleTypeLoader();                          q.UseInMemoryStore(); // using the db would be nice                          q.UseDefaultThreadPool(tp => { tp.MaxConcurrency = 10; });                          q.AddJobAndTrigger<AdSyncJob>(Configuration);                          q.AddJobAndTrigger<JobQueueCleaner_Job>(Configuration);                          q.AddJobAndTrigger<JobQueueProcessor_Job>(Configuration);                                                });                   services.AddQuartzHostedService(options =>                      {                                                      options.WaitForJobsToComplete = true;                      });                    })                  .UseSerilog(providers: Providers);                      var isDebugging = !(Debugger.IsAttached || args.Contains("--console"));              if (isDebugging && RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) {                   await hostBuilder.RunTheServiceAsync();               }              else               {                   await hostBuilder.RunConsoleAsync();               }          }          catch (Exception ex)          {              Log.Fatal(ex, "Background Job Service terminated unexpectedly (use --console to run as console app)");          }          finally          {              Log.CloseAndFlush();          }      }  

and then for example in a IJob:

 [DisallowConcurrentExecution]   public class JobQueueProcessor_Job : BackgroundService, IJob   {       private readonly ILogger<JobQueueProcessor_Job> _logger;         public JobQueueProcessor_Job(ILogger<JobQueueProcessor_Job> logger) {           _logger = logger;       }        public async Task Execute(IJobExecutionContext context)      {          _logger.LogDebug("this will never show");      }    }  
https://stackoverflow.com/questions/67410646/quartz-net-aspnetcore-serilog-no-log-output May 06, 2021 at 09:11AM

没有评论:

发表评论