Skip to content

Commit

Permalink
Better error logging overall (#50)
Browse files Browse the repository at this point in the history
  • Loading branch information
helto4real committed Mar 27, 2020
1 parent 93f51a9 commit 393d581
Show file tree
Hide file tree
Showing 11 changed files with 394 additions and 4,088 deletions.
133 changes: 82 additions & 51 deletions src/App/NetDaemon.App/Common/Fluent.cs
Original file line number Diff line number Diff line change
Expand Up @@ -461,82 +461,113 @@ public void Execute()
foreach (var entityId in _entityIds)
_daemon.ListenState(entityId, async (entityIdInn, newState, oldState) =>
{
var entityManager = (EntityManager)_currentState.Entity!;
if (_currentState.Lambda != null)
try
{
try
var entityManager = (EntityManager)_currentState.Entity!;
if (_currentState.Lambda != null)
{
if (!_currentState.Lambda(newState, oldState))
try
{
if (!_currentState.Lambda(newState, oldState))
return;
}
catch (Exception e)
{
_daemon.Logger.LogWarning(e, "Failed to evaluate function");
return;
}
}
catch (Exception e)
else
{
_daemon.Logger.LogWarning(e, "Failed to evaluate function");
return;
}
}
else
{
if (_currentState.To != null)
if (_currentState.To != newState?.State)
return;
if (_currentState.To != null)
if (_currentState.To != newState?.State)
return;
if (_currentState.From != null)
if (_currentState.From != oldState?.State)
return;
if (_currentState.From != null)
if (_currentState.From != oldState?.State)
return;
// If we don´t accept all changes in the state change
// and we do not have a state change so return
if (newState?.State == oldState?.State && !_currentState.AllChanges)
return;
}
// If we don´t accept all changes in the state change
// and we do not have a state change so return
if (newState?.State == oldState?.State && !_currentState.AllChanges)
return;
}
if (_currentState.ForTimeSpan != TimeSpan.Zero)
{
_daemon.Logger.LogDebug(
$"AndNotChangeFor statement found, delaying {_currentState.ForTimeSpan}");
await Task.Delay(_currentState.ForTimeSpan).ConfigureAwait(false);
var currentState = _daemon.GetState(entityIdInn);
if (currentState != null && currentState.State == newState?.State)
if (_currentState.ForTimeSpan != TimeSpan.Zero)
{
//var timePassed = newState.LastChanged.Subtract(currentState.LastChanged);
if (currentState?.LastChanged == newState?.LastChanged)
_daemon.Logger.LogDebug(
$"AndNotChangeFor statement found, delaying {_currentState.ForTimeSpan}");
await Task.Delay(_currentState.ForTimeSpan).ConfigureAwait(false);
var currentState = _daemon.GetState(entityIdInn);
if (currentState != null && currentState.State == newState?.State)
{
// No state has changed during the period
_daemon.Logger.LogDebug(
$"State same {newState?.State} during period of {_currentState.ForTimeSpan}, executing action!");
// The state has not changed during the time we waited
if (_currentState.FuncToCall == null)
await entityManager.ExecuteAsync(true).ConfigureAwait(false);
//var timePassed = newState.LastChanged.Subtract(currentState.LastChanged);
if (currentState?.LastChanged == newState?.LastChanged)
{
// No state has changed during the period
_daemon.Logger.LogDebug(
$"State same {newState?.State} during period of {_currentState.ForTimeSpan}, executing action!");
// The state has not changed during the time we waited
if (_currentState.FuncToCall == null)
await entityManager.ExecuteAsync(true).ConfigureAwait(false);
else
{
try
{
await _currentState.FuncToCall(entityIdInn, newState, oldState).ConfigureAwait(false);
}
catch (Exception e)
{
_daemon.Logger.LogWarning(e, "Call function error in timespan");
}
}
}
else
await _currentState.FuncToCall(entityIdInn, newState, oldState).ConfigureAwait(false);
{
_daemon.Logger.LogDebug(
$"State same {newState?.State} but different state changed: {currentState?.LastChanged}, expected {newState?.LastChanged}");
}
}
else
{
_daemon.Logger.LogDebug(
$"State same {newState?.State} but different state changed: {currentState?.LastChanged}, expected {newState?.LastChanged}");
$"State not same, do not execute for statement. {newState?.State} found, expected {currentState?.State}");
}
}
else
{
_daemon.Logger.LogDebug(
$"State not same, do not execute for statement. {newState?.State} found, expected {currentState?.State}");
$"State {newState?.State} expected from {oldState?.State}, executing action!");
if (_currentState.FuncToCall != null)
{
try
{
await _currentState.FuncToCall(entityIdInn, newState, oldState).ConfigureAwait(false);
}
catch (Exception e)
{
_daemon.Logger.LogWarning(e, "Call function error");
}
}
else if (_currentState.ScriptToCall != null)
await _daemon.RunScript(_currentState.ScriptToCall).ExecuteAsync().ConfigureAwait(false);
else
await entityManager.ExecuteAsync(true).ConfigureAwait(false);
}
}
else
catch (Exception e)
{
_daemon.Logger.LogDebug(
$"State {newState?.State} expected from {oldState?.State}, executing action!");
if (_currentState.FuncToCall != null)
await _currentState.FuncToCall(entityIdInn, newState, oldState).ConfigureAwait(false);
else if (_currentState.ScriptToCall != null)
await _daemon.RunScript(_currentState.ScriptToCall).ExecuteAsync().ConfigureAwait(false);
else
await entityManager.ExecuteAsync(true).ConfigureAwait(false);
_daemon.Logger.LogWarning(e, "Unhandled error in ListenState");
}
});


//}
}

Expand Down
63 changes: 51 additions & 12 deletions src/Daemon/NetDaemon.Daemon/Daemon/Scheduler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -88,16 +88,23 @@ public ISchedulerResult RunEveryAsync(TimeSpan timeSpan, Func<Task> func)

private async Task RunEveryInternalAsync(TimeSpan timeSpan, Func<Task> func, CancellationToken token)
{

using CancellationTokenSource linkedCts =
CancellationTokenSource.CreateLinkedTokenSource(_cancelSource.Token, token);

var stopWatch = new Stopwatch();
while (!linkedCts.IsCancellationRequested)
{
stopWatch.Start();
await func.Invoke().ConfigureAwait(false);
stopWatch.Stop();

try
{
stopWatch.Start();
await func.Invoke().ConfigureAwait(false);
stopWatch.Stop();
}
catch (Exception e)
{
_logger.LogWarning(e, "Unhandled exception invoking scheduled function");
}
// If less time spent in func that duration delay the remainder
if (timeSpan > stopWatch.Elapsed)
{
Expand All @@ -111,6 +118,8 @@ private async Task RunEveryInternalAsync(TimeSpan timeSpan, Func<Task> func, Can
}
stopWatch.Reset();
}


}

internal TimeSpan CalculateDailyTimeBetweenNowAndTargetTime(DateTime targetTime)
Expand Down Expand Up @@ -177,17 +186,32 @@ private async Task RunDailyInternalAsync(DateTime timeOfDayToTrigger, IEnumerabl
{
if (runOnDays.Contains(_timeManager!.Current.DayOfWeek))
{
_logger.LogTrace($"RunDaily, Time: Invoke function {_timeManager!.Current}, parsed time: {timeOfDayToTrigger}");
await func.Invoke().ConfigureAwait(false);
try
{
_logger.LogTrace($"RunDaily, Time: Invoke function {_timeManager!.Current}, parsed time: {timeOfDayToTrigger}");
await func.Invoke().ConfigureAwait(false);
}
catch (Exception e)
{
_logger.LogWarning(e, "Unhandled exception invoking scheduled function");
}
}
else
_logger.LogTrace($"RunDaily, Time: {_timeManager!.Current}, parsed time: {timeOfDayToTrigger}, Not run, due to dayofweek");
}
else
{
_logger.LogTrace($"RunDaily, Time: Invoke function {_timeManager!.Current}, parsed time: {timeOfDayToTrigger}");
// No constraints on day of week
await func.Invoke().ConfigureAwait(false);
try
{
_logger.LogTrace($"RunDaily, Time: Invoke function {_timeManager!.Current}, parsed time: {timeOfDayToTrigger}");
// No constraints on day of week
await func.Invoke().ConfigureAwait(false);
}
catch (Exception e)
{
_logger.LogWarning(e, "Unhandled exception invoking scheduled function");
}

}
}
}
Expand Down Expand Up @@ -217,7 +241,14 @@ private async Task RunEveryMinuteInternalAsync(short second, Func<Task> func, Ca
var diff = CalculateEveryMinuteTimeBetweenNowAndTargetTime(second);
_logger.LogTrace($"RunEveryMinute, Delay {diff}");
await _timeManager!.Delay(diff, linkedCts.Token).ConfigureAwait(false);
await func.Invoke().ConfigureAwait(false);
try
{
await func.Invoke().ConfigureAwait(false);
}
catch (Exception e)
{
_logger.LogWarning(e, "Unhandled exception invoking scheduled function");
}
}
}

Expand Down Expand Up @@ -250,7 +281,15 @@ private async Task InternalRunInAsync(TimeSpan timeSpan, Func<Task> func, Cancel

_logger.LogTrace($"RunIn, Delay {timeSpan}");
await _timeManager!.Delay(timeSpan, linkedCts.Token).ConfigureAwait(false);
await func.Invoke().ConfigureAwait(false);
try
{
await func.Invoke().ConfigureAwait(false);
}
catch (Exception e)
{
_logger.LogWarning(e, "Unhandled exception invoking scheduled function");
}

}

/// <summary>
Expand All @@ -272,7 +311,7 @@ public async Task Stop()
}

/// <summary>
/// Restarts the scheduler.
/// Restarts the scheduler.
/// Existing schedules are cancelled and the scheduler remains usable.
/// </summary>
public async Task Restart()
Expand Down
9 changes: 5 additions & 4 deletions src/DaemonRunner/DaemonRunner/Service/App/CodeManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -167,16 +167,17 @@ private static (bool, string) CheckIfStateChangedSignatureIsOk(MethodInfo method
public sealed class CodeManager : IDisposable
{
private readonly string _codeFolder;

private readonly ILogger _logger;
private readonly List<Type> _loadedDaemonApps;

private readonly YamlConfig _yamlConfig;

private readonly List<INetDaemonApp> _instanciatedDaemonApps;

public CodeManager(string codeFolder)
public CodeManager(string codeFolder, ILogger logger)
{
_codeFolder = codeFolder;
_logger = logger;
_loadedDaemonApps = new List<Type>(100);
_instanciatedDaemonApps = new List<INetDaemonApp>(100);

Expand Down Expand Up @@ -210,7 +211,7 @@ private async Task ReloadApplicationsAsync(INetDaemonHost host)
{
await host.StopDaemonActivitiesAsync();

foreach(var app in _instanciatedDaemonApps)
foreach (var app in _instanciatedDaemonApps)
{
app.Dispose();
}
Expand Down Expand Up @@ -343,7 +344,7 @@ private void LoadAllCodeToLoadContext()
}
}
var err = msg.ToString();
System.Console.WriteLine(err);
_logger.LogError(err);
}
}
alc.Unload();
Expand Down
18 changes: 9 additions & 9 deletions src/DaemonRunner/DaemonRunner/Service/RunnerService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -82,19 +82,19 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
if (_daemonHost.Connected)
{
using (var codeManager = new CodeManager(sourceFolder))
try
{
try
using (var codeManager = new CodeManager(sourceFolder, _daemonHost.Logger))
{
await codeManager.EnableApplicationDiscoveryServiceAsync(_daemonHost, discoverServicesOnStartup: true);
}
catch (Exception e)
{
_logger.LogError(e, "Failed to load applications");
}

// Wait until daemon stops
await daemonHostTask.ConfigureAwait(false);
// Wait until daemon stops
await daemonHostTask.ConfigureAwait(false);
}
}
catch (Exception e)
{
_logger.LogError(e, "Failed to load applications");
}
}
else
Expand Down
Loading

0 comments on commit 393d581

Please sign in to comment.