Skip to content

Commit

Permalink
Added Special loggers (#66)
Browse files Browse the repository at this point in the history
  • Loading branch information
helto4real authored Apr 10, 2020
2 parents 6b8adca + b9adb0a commit 8fee408
Show file tree
Hide file tree
Showing 10 changed files with 246 additions and 30 deletions.
3 changes: 2 additions & 1 deletion exampleapps/apps/test1.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ public class GlobalApp : NetDaemonApp
public override async Task InitializeAsync()
{
SharedThing = "Hello world";

Log("Logging from global app");
LogError("OMG SOMETING IS WRONG {error}", "The error!");
}
}

Expand Down
3 changes: 3 additions & 0 deletions exampleapps/apps/test2.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ public class BatteryManager : NetDaemonApp
public string? HelloWorldSecret { get; set; }
public override async Task InitializeAsync()
{
Log("Hello");
Log("Hello {name}", "Tomas");

// Scheduler.RunEvery(5000, () => { var x = 0; var z = 4 / x; return Task.CompletedTask; });
// Entity("sun.sun").WhenStateChange(allChanges: true).Call((entityid, to, from) => throw new Exception("Test")).Execute();
// var app = (GlobalApp)GetApp("global_app");
Expand Down
2 changes: 1 addition & 1 deletion exampleapps/apps/test2.yaml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
app:
my_app:
class: BatteryManager
# HelloWorldSecret: !secret test_secret
dependencies:
Expand Down
32 changes: 23 additions & 9 deletions src/App/NetDaemon.App/Common/Fluent/Fluent.cs
Original file line number Diff line number Diff line change
Expand Up @@ -508,7 +508,8 @@ public void Execute()
}
catch (Exception e)
{
Daemon.Logger.LogWarning(e, $"Failed to evaluate function in App {App.Id}, EntityId: {entityIdInn}, From: {newState?.State} To: {oldState?.State}");
Daemon.Logger.LogWarning(e,
"Failed to evaluate function in App {appId}, EntityId: {entityId}, From: {newState} To: {oldState}", App.Id, entityIdInn, $"{newState?.State}", $"{oldState?.State}");
return;
}
}
Expand All @@ -531,7 +532,7 @@ public void Execute()
if (_currentState.ForTimeSpan != TimeSpan.Zero)
{
Daemon.Logger.LogDebug(
$"AndNotChangeFor statement found, delaying {_currentState.ForTimeSpan}");
"AndNotChangeFor statement found, delaying {time}", _currentState.ForTimeSpan);
await Task.Delay(_currentState.ForTimeSpan).ConfigureAwait(false);
var currentState = Daemon.GetState(entityIdInn);
if (currentState != null && currentState.State == newState?.State)
Expand All @@ -541,7 +542,7 @@ public void Execute()
{
// No state has changed during the period
Daemon.Logger.LogDebug(
$"State same {newState?.State} during period of {_currentState.ForTimeSpan}, executing action!");
"State same {newState} during period of {time}, executing action!", $"{newState?.State}", _currentState.ForTimeSpan);
// The state has not changed during the time we waited
if (_currentState.FuncToCall == null)
await entityManager.ExecuteAsync(true).ConfigureAwait(false);
Expand All @@ -553,27 +554,37 @@ public void Execute()
}
catch (Exception e)
{
Daemon.Logger.LogWarning(e, $"Call function error in timespan in App {App.Id}, EntityId: {entityIdInn}, From: {newState?.State} To: {oldState?.State}");
Daemon.Logger.LogWarning(e,
"Call function error in timespan in App {appId}, EntityId: {entityId}, From: {newState} To: {oldState}",
App.Id, entityIdInn, $"{newState?.State}", $"{oldState?.State}");
}
}
}
else
{
Daemon.Logger.LogDebug(
$"State same {newState?.State} but different state changed: {currentState?.LastChanged}, expected {newState?.LastChanged}");
"State same {newState} but different state changed: {currentLastChanged}, expected {newLastChanged}",
$"{newState?.State}",
currentState?.LastChanged,
newState?.LastChanged);
}
}
else
{
Daemon.Logger.LogDebug(
$"State not same, do not execute for statement. {newState?.State} found, expected {currentState?.State}");
"State not same, do not execute for statement. {newState} found, expected {currentState}",
$"{newState?.State}",
$"{currentState?.State}");
}
}
else
{
Daemon.Logger.LogDebug(
$"State {newState?.State} expected from {oldState?.State}, executing action!");
"State {newState} expected from {oldState}, executing action!",
$"{newState?.State}",
$"{oldState?.State}"
);
if (_currentState.FuncToCall != null)
{
Expand All @@ -583,7 +594,10 @@ public void Execute()
}
catch (Exception e)
{
Daemon.Logger.LogWarning(e, $"Call function error, in App {App.Id}, EntityId: {entityIdInn}, From: {newState?.State} To: {oldState?.State}");
Daemon.Logger.LogWarning(e,
"Call function error in App {appId}, EntityId: {entityId}, From: {newState} To: {oldState}",
App.Id, entityIdInn, $"{newState?.State}", $"{oldState?.State}");
}
}
Expand All @@ -595,7 +609,7 @@ public void Execute()
}
catch (Exception e)
{
Daemon.Logger.LogWarning(e, $"Unhandled error in ListenState in App {App.Id}");
Daemon.Logger.LogWarning(e, "Unhandled error in ListenState in App {appId}", App.Id);
}
});
Expand Down
83 changes: 81 additions & 2 deletions src/App/NetDaemon.App/Common/NetDaemonApp.cs
Original file line number Diff line number Diff line change
Expand Up @@ -147,10 +147,89 @@ public Task SaveDataAsync<T>(string id, T data)
}

/// <inheritdoc/>
public void Log(string message, LogLevel level = LogLevel.Information) => Logger.Log(level, message);
public void Log(string message) => Log(LogLevel.Information, message);

/// <inheritdoc/>
public void Log(string message, Exception exception, LogLevel level = LogLevel.Information) => Logger.Log(level, exception, message);
public void LogWarning(string message) => Log(LogLevel.Warning, message);

/// <inheritdoc/>
public void LogError(string message) => Log(LogLevel.Error, message);

/// <inheritdoc/>
public void LogTrace(string message) => Log(LogLevel.Trace, message);

/// <inheritdoc/>
public void LogDebug(string message) => Log(LogLevel.Debug, message);

/// <inheritdoc/>
public void Log(Exception exception, string message) => Log(LogLevel.Information, exception, message);
/// <inheritdoc/>
public void LogWarning(Exception exception, string message) => Log(LogLevel.Warning, exception, message);
/// <inheritdoc/>
public void LogError(Exception exception, string message) => Log(LogLevel.Error, exception, message);
/// <inheritdoc/>
public void LogDebug(Exception exception, string message) => Log(LogLevel.Debug, exception, message);
/// <inheritdoc/>
public void LogTrace(Exception exception, string message) => Log(LogLevel.Trace, exception, message);

/// <inheritdoc/>
public void Log(LogLevel level, string message, params object[] param)
{
if (param is object && param.Length > 0)
{
var result = param.Prepend(Id).ToArray();
Logger.Log(level, $" {{Id}}: {message}", result);
}
else
{
Logger.Log(level, $" {{Id}}: {message}", new object[] { Id ?? "" });
}
}

/// <inheritdoc/>
public void Log(string message, params object[] param) => Log(LogLevel.Information, message, param);

/// <inheritdoc/>
public void LogWarning(string message, params object[] param) => Log(LogLevel.Warning, message, param);

/// <inheritdoc/>
public void LogError(string message, params object[] param) => Log(LogLevel.Error, message, param);

/// <inheritdoc/>
public void LogDebug(string message, params object[] param) => Log(LogLevel.Debug, message, param);

/// <inheritdoc/>
public void LogTrace(string message, params object[] param) => Log(LogLevel.Trace, message, param);


/// <inheritdoc/>
public void Log(LogLevel level, Exception exception, string message, params object[] param)
{
if (param is object && param.Length > 0)
{
var result = param.Prepend(Id).ToArray();
Logger.Log(level, exception, $" {{Id}}: {message}", result);
}
else
{
Logger.Log(level, exception, $" {{Id}}: {message}", new object[] { Id ?? "" });
}
}

/// <inheritdoc/>
public void Log(Exception exception, string message, params object[] param) => Log(LogLevel.Information, exception, message, param);

/// <inheritdoc/>
public void LogWarning(Exception exception, string message, params object[] param) => Log(LogLevel.Warning, exception, message, param);

/// <inheritdoc/>
public void LogError(Exception exception, string message, params object[] param) => Log(LogLevel.Error, exception, message, param);

/// <inheritdoc/>
public void LogDebug(Exception exception, string message, params object[] param) => Log(LogLevel.Debug, exception, message, param);

/// <inheritdoc/>
public void LogTrace(Exception exception, string message, params object[] param) => Log(LogLevel.Trace, exception, message, param);

/// <inheritdoc/>
public IMediaPlayer MediaPlayer(params string[] entityIds)
Expand Down
12 changes: 6 additions & 6 deletions src/Daemon/NetDaemon.Daemon/Daemon/NetDaemonHost.cs
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ public IEntity Entities(INetDaemonApp app, Func<IEntityProperties, bool> func)
}
catch (Exception e)
{
Logger.LogError(e, "Failed to select entities using func");
Logger.LogError(e, "Failed to select entities using func in app {appId}", app.Id);
throw;
}
}
Expand Down Expand Up @@ -177,7 +177,7 @@ public IMediaPlayer MediaPlayers(INetDaemonApp app, Func<IEntityProperties, bool
}
catch (Exception e)
{
Logger.LogError(e, "Failed to select mediaplayers func");
Logger.LogError(e, "Failed to select mediaplayers func in app {appId}", app.Id);
throw;
}
}
Expand All @@ -199,7 +199,7 @@ public ICamera Cameras(INetDaemonApp app, Func<IEntityProperties, bool> func)
}
catch (Exception e)
{
Logger.LogError(e, "Failed to select camera func");
Logger.LogError(e, "Failed to select camera func in app {appId}", app.Id);
throw;
}
}
Expand Down Expand Up @@ -245,7 +245,7 @@ public async Task Run(string host, short port, bool ssl, string token, Cancellat
if (!connectResult)
{
Connected = false;
Logger.LogWarning($"Home assistant is unavailable, retrying in {_reconnectIntervall} seconds...");
Logger.LogWarning($"Home assistant is unavailable, retrying in {_reconnectIntervall / 1000} seconds...");
await _hassClient.CloseAsync().ConfigureAwait(false);
await Task.Delay(_reconnectIntervall, cancellationToken).ConfigureAwait(false);

Expand All @@ -264,7 +264,7 @@ public async Task Run(string host, short port, bool ssl, string token, Cancellat
Logger.LogInformation(
hassioToken != null
? "Successfully connected to Home Assistant Core in Home Assistant Add-on"
: $"Successfully connected to Home Assistant Core on host {host}:{port}");
: "Successfully connected to Home Assistant Core on host {host}:{port}", host, port);

while (!cancellationToken.IsCancellationRequested)
{
Expand Down Expand Up @@ -341,7 +341,7 @@ public async Task Run(string host, short port, bool ssl, string token, Cancellat
}
catch (Exception e)
{
Logger.LogError(e, "Failed to set state");
Logger.LogError(e, "Failed to set state for entity {entityId}", entityId);
throw;
}
}
Expand Down
14 changes: 7 additions & 7 deletions src/Daemon/NetDaemon.Daemon/Daemon/Scheduler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ private async Task RunEveryInternalAsync(TimeSpan timeSpan, Func<Task> func, Can
if (timeSpan > stopWatch.Elapsed)
{
var diff = timeSpan.Subtract(stopWatch.Elapsed);
_logger.LogTrace($"RunEvery, Time: {_timeManager!.Current}, Span: {timeSpan}, Delay {diff}");
_logger.LogTrace("RunEvery, Time: {time}, Span: {timeSpan}, Delay {diff}", _timeManager!.Current, timeSpan, diff);
await _timeManager!.Delay(diff, linkedCts.Token).ConfigureAwait(false);
}
else
Expand Down Expand Up @@ -179,7 +179,7 @@ private async Task RunDailyInternalAsync(DateTime timeOfDayToTrigger, IEnumerabl
while (!linkedCts.IsCancellationRequested)
{
var diff = CalculateDailyTimeBetweenNowAndTargetTime(timeOfDayToTrigger);
_logger.LogTrace($"RunDaily, Time: {_timeManager!.Current}, parsed time: {timeOfDayToTrigger}, Delay {diff}");
_logger.LogTrace("RunDaily, Time: {time}, parsed time: {timeOfDayToTrigger}, Delay {diff}", _timeManager!.Current, timeOfDayToTrigger, diff);
await _timeManager!.Delay(diff, linkedCts.Token).ConfigureAwait(false);

if (runOnDays != null)
Expand All @@ -188,7 +188,7 @@ private async Task RunDailyInternalAsync(DateTime timeOfDayToTrigger, IEnumerabl
{
try
{
_logger.LogTrace($"RunDaily, Time: Invoke function {_timeManager!.Current}, parsed time: {timeOfDayToTrigger}");
_logger.LogTrace("RunDaily, Time: Invoke function {time}, parsed time: {timeOfDayToTrigger}", _timeManager!.Current, timeOfDayToTrigger);
await func.Invoke().ConfigureAwait(false);
}
catch (Exception e)
Expand All @@ -197,13 +197,13 @@ private async Task RunDailyInternalAsync(DateTime timeOfDayToTrigger, IEnumerabl
}
}
else
_logger.LogTrace($"RunDaily, Time: {_timeManager!.Current}, parsed time: {timeOfDayToTrigger}, Not run, due to dayofweek");
_logger.LogTrace("RunDaily, Time: {time}, parsed time: {timeOfDayToTrigger}, Not run, due to dayofweek", _timeManager!.Current, timeOfDayToTrigger);
}
else
{
try
{
_logger.LogTrace($"RunDaily, Time: Invoke function {_timeManager!.Current}, parsed time: {timeOfDayToTrigger}");
_logger.LogTrace("RunDaily, Time: Invoke function {time}, parsed time: {timeOfDayToTrigger}", _timeManager!.Current, timeOfDayToTrigger);
// No constraints on day of week
await func.Invoke().ConfigureAwait(false);
}
Expand Down Expand Up @@ -239,7 +239,7 @@ private async Task RunEveryMinuteInternalAsync(short second, Func<Task> func, Ca
{
var now = _timeManager?.Current;
var diff = CalculateEveryMinuteTimeBetweenNowAndTargetTime(second);
_logger.LogTrace($"RunEveryMinute, Delay {diff}");
_logger.LogTrace("RunEveryMinute, Delay {diff}", diff);
await _timeManager!.Delay(diff, linkedCts.Token).ConfigureAwait(false);
try
{
Expand Down Expand Up @@ -279,7 +279,7 @@ private async Task InternalRunInAsync(TimeSpan timeSpan, Func<Task> func, Cancel
using CancellationTokenSource linkedCts =
CancellationTokenSource.CreateLinkedTokenSource(_cancelSource.Token, token);

_logger.LogTrace($"RunIn, Delay {timeSpan}");
_logger.LogTrace("RunIn, Delay {timeSpan}", timeSpan);
await _timeManager!.Delay(timeSpan, linkedCts.Token).ConfigureAwait(false);
try
{
Expand Down
8 changes: 4 additions & 4 deletions src/DaemonRunner/DaemonRunner/Service/App/CodeManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ MethodInfo method
}
catch (Exception e)
{
_daemon.Logger.LogError(e, "Failed to invoke the ServiceCall funcition");
_daemon.Logger.LogError(e, "Failed to invoke the ServiceCall function for app {appId}", netDaemonApp.Id);
}
});
}
Expand Down Expand Up @@ -118,7 +118,7 @@ private static void HandleServiceCallAttribute(INetDaemon _daemon, INetDaemonApp
}
catch (Exception e)
{
_daemon.Logger.LogError(e, "Failed to invoke the ServiceCall function");
_daemon.Logger.LogError(e, "Failed to invoke the ServiceCall function for app {appId}", netDaemonApp);
}
});
}
Expand Down Expand Up @@ -249,7 +249,7 @@ public async Task<IEnumerable<INetDaemonApp>> InstanceAndInitApplications(INetDa
if (!appInstance.IsEnabled)
{
appInstance.Dispose();
host!.Logger.LogInformation($"Skipped disabled app {appInstance.GetType().Name}");
host!.Logger.LogInformation("Skipped disabled app class {class}", appInstance.GetType().Name);
continue;
}

Expand Down Expand Up @@ -285,7 +285,7 @@ public async Task<IEnumerable<INetDaemonApp>> InstanceAndInitApplications(INetDa
{
await app.InitializeAsync().ConfigureAwait(false);
app.HandleAttributeInitialization(host!);
host!.Logger.LogInformation($"Successfully loaded app {app.GetType().Name}");
host!.Logger.LogInformation("Successfully loaded app {appId} ({class})", app.Id, app.GetType().Name);
}

_instanciatedDaemonApps.AddRange(result);
Expand Down
Loading

0 comments on commit 8fee408

Please sign in to comment.