added logging to HostedServiceBase

This commit is contained in:
sbwalker 2023-06-23 15:19:18 -04:00
parent f6cca5cb35
commit 1e18d913e0

View File

@ -5,6 +5,7 @@ using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Oqtane.Models; using Oqtane.Models;
using Oqtane.Repository; using Oqtane.Repository;
using Oqtane.Shared; using Oqtane.Shared;
@ -38,17 +39,23 @@ namespace Oqtane.Infrastructure
{ {
await Task.Yield(); // required so that this method does not block startup await Task.Yield(); // required so that this method does not block startup
try
{
while (!stoppingToken.IsCancellationRequested) while (!stoppingToken.IsCancellationRequested)
{ {
using (var scope = _serviceScopeFactory.CreateScope()) using (var scope = _serviceScopeFactory.CreateScope())
{ {
ILogger<HostedServiceBase> _filelogger = scope.ServiceProvider.GetRequiredService<ILogger<HostedServiceBase>>();
try
{
var jobs = scope.ServiceProvider.GetRequiredService<IJobRepository>();
var jobLogs = scope.ServiceProvider.GetRequiredService<IJobLogRepository>();
var tenantRepository = scope.ServiceProvider.GetRequiredService<ITenantRepository>();
var tenantManager = scope.ServiceProvider.GetRequiredService<ITenantManager>();
// get name of job // get name of job
string jobType = Utilities.GetFullTypeName(GetType().AssemblyQualifiedName); string jobType = Utilities.GetFullTypeName(GetType().AssemblyQualifiedName);
// load jobs and find current job // load jobs and find current job
IJobRepository jobs = scope.ServiceProvider.GetRequiredService<IJobRepository>();
Job job = jobs.GetJobs().Where(item => item.JobType == jobType).FirstOrDefault(); Job job = jobs.GetJobs().Where(item => item.JobType == jobType).FirstOrDefault();
if (job != null && job.IsEnabled && !job.IsExecuting) if (job != null && job.IsEnabled && !job.IsExecuting)
{ {
@ -73,7 +80,9 @@ namespace Oqtane.Infrastructure
// determine if the job should be run // determine if the job should be run
if (NextExecution <= DateTime.UtcNow && (job.EndDate == null || job.EndDate >= DateTime.UtcNow)) if (NextExecution <= DateTime.UtcNow && (job.EndDate == null || job.EndDate >= DateTime.UtcNow))
{ {
IJobLogRepository jobLogs = scope.ServiceProvider.GetRequiredService<IJobLogRepository>(); // update the job to indicate it is running
job.IsExecuting = true;
jobs.UpdateJob(job);
// create a job log entry // create a job log entry
JobLog log = new JobLog(); JobLog log = new JobLog();
@ -84,16 +93,10 @@ namespace Oqtane.Infrastructure
log.Notes = ""; log.Notes = "";
log = jobLogs.AddJobLog(log); log = jobLogs.AddJobLog(log);
// update the job to indicate it is running
job.IsExecuting = true;
jobs.UpdateJob(job);
// execute the job // execute the job
try try
{ {
var notes = ""; var notes = "";
var tenantRepository = scope.ServiceProvider.GetRequiredService<ITenantRepository>();
var tenantManager = scope.ServiceProvider.GetRequiredService<ITenantManager>();
foreach (var tenant in tenantRepository.GetTenants()) foreach (var tenant in tenantRepository.GetTenants())
{ {
// set tenant and execute job // set tenant and execute job
@ -133,17 +136,20 @@ namespace Oqtane.Infrastructure
} }
} }
} }
catch (Exception ex)
{
// can occur during the initial installation because the database has not yet been created
if (!ex.Message.Contains("No database provider has been configured for this DbContext"))
{
_filelogger.LogError(Utilities.LogMessage(this, $"An Error Occurred Executing Scheduled Job: {Name} - {ex}"));
}
}
}
// wait 1 minute // wait 1 minute
await Task.Delay(TimeSpan.FromMinutes(1), stoppingToken); await Task.Delay(TimeSpan.FromMinutes(1), stoppingToken);
} }
} }
catch
{
// can occur during the initial installation as there is no DBContext
}
}
private DateTime CalculateNextExecution(DateTime nextExecution, Job job) private DateTime CalculateNextExecution(DateTime nextExecution, Job job)
{ {
@ -190,10 +196,12 @@ namespace Oqtane.Infrastructure
} }
public Task StartAsync(CancellationToken cancellationToken) public Task StartAsync(CancellationToken cancellationToken)
{
try
{ {
using (var scope = _serviceScopeFactory.CreateScope()) using (var scope = _serviceScopeFactory.CreateScope())
{
ILogger<HostedServiceBase> _filelogger = scope.ServiceProvider.GetRequiredService<ILogger<HostedServiceBase>>();
try
{ {
string jobTypeName = Utilities.GetFullTypeName(GetType().AssemblyQualifiedName); string jobTypeName = Utilities.GetFullTypeName(GetType().AssemblyQualifiedName);
IJobRepository jobs = scope.ServiceProvider.GetRequiredService<IJobRepository>(); IJobRepository jobs = scope.ServiceProvider.GetRequiredService<IJobRepository>();
@ -207,7 +215,7 @@ namespace Oqtane.Infrastructure
} }
else else
{ {
// auto registration - job will not run on initial installation but will run after restart // auto registration - job will not run on initial installation due to no DBContext but will run after restart
job = new Job { JobType = jobTypeName }; job = new Job { JobType = jobTypeName };
// optional HostedServiceBase properties // optional HostedServiceBase properties
@ -233,6 +241,15 @@ namespace Oqtane.Infrastructure
jobs.AddJob(job); jobs.AddJob(job);
} }
} }
catch (Exception ex)
{
// can occur during the initial installation because the database has not yet been created
if (!ex.Message.Contains("No database provider has been configured for this DbContext"))
{
_filelogger.LogError(Utilities.LogMessage(this, $"An Error Occurred Starting Scheduled Job: {Name} - {ex}"));
}
}
}
_executingTask = ExecuteAsync(_cancellationTokenSource.Token); _executingTask = ExecuteAsync(_cancellationTokenSource.Token);
@ -240,20 +257,17 @@ namespace Oqtane.Infrastructure
{ {
return _executingTask; return _executingTask;
} }
}
catch
{
// can occur during the initial installation because this method is called during startup and the database has not yet been created
}
return Task.CompletedTask; return Task.CompletedTask;
} }
public async Task StopAsync(CancellationToken cancellationToken) public async Task StopAsync(CancellationToken cancellationToken)
{
try
{ {
using (var scope = _serviceScopeFactory.CreateScope()) using (var scope = _serviceScopeFactory.CreateScope())
{
ILogger<HostedServiceBase> _filelogger = scope.ServiceProvider.GetRequiredService<ILogger<HostedServiceBase>>();
try
{ {
string jobTypeName = Utilities.GetFullTypeName(GetType().AssemblyQualifiedName); string jobTypeName = Utilities.GetFullTypeName(GetType().AssemblyQualifiedName);
IJobRepository jobs = scope.ServiceProvider.GetRequiredService<IJobRepository>(); IJobRepository jobs = scope.ServiceProvider.GetRequiredService<IJobRepository>();
@ -266,10 +280,11 @@ namespace Oqtane.Infrastructure
jobs.UpdateJob(job); jobs.UpdateJob(job);
} }
} }
} catch (Exception ex)
catch
{ {
// error updating the job // error updating the job
_filelogger.LogError(Utilities.LogMessage(this, $"An Error Occurred Stopping Scheduled Job: {Name} - {ex}"));
}
} }
// stop called without start // stop called without start