Skip to content

Commit

Permalink
Merge pull request #174 from PepperDash/feature-2/fix-logError-message
Browse files Browse the repository at this point in the history
Logging updates
  • Loading branch information
jgutenplan authored May 16, 2024
2 parents 165841b + e9dcd16 commit d403c29
Show file tree
Hide file tree
Showing 6 changed files with 131 additions and 48 deletions.
37 changes: 37 additions & 0 deletions src/Pepperdash Core/Logging/CrestronEnricher.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
using Crestron.SimplSharp;
using Serilog.Core;
using Serilog.Events;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PepperDash.Core.Logging
{
public class CrestronEnricher : ILogEventEnricher
{
static readonly string _appName;

static CrestronEnricher()
{
switch (CrestronEnvironment.DevicePlatform)
{
case eDevicePlatform.Appliance:
_appName = $"App {InitialParametersClass.ApplicationNumber}";
break;
case eDevicePlatform.Server:
_appName = $"{InitialParametersClass.RoomId}";
break;
}
}


public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
{
var property = propertyFactory.CreateProperty("App", _appName);

logEvent.AddOrUpdateProperty(property);
}
}
}
53 changes: 15 additions & 38 deletions src/Pepperdash Core/Logging/Debug.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
using Serilog.Events;
using Serilog.Formatting.Compact;
using Serilog.Formatting.Json;
using Serilog.Templates;
using System;
using System.Collections.Generic;
using System.Reflection;
Expand Down Expand Up @@ -143,12 +144,17 @@ static Debug()

CrestronConsole.PrintLine($"Saving log files to {logFilePath}");

var errorLogTemplate = CrestronEnvironment.DevicePlatform == eDevicePlatform.Appliance
? "{@t:fff}ms [{@l:u4}]{#if Key is not null}[{Key}]{#end} {@m}{#if @x is not null}\r\n{@x}{#end}"
: "[{@t:yyyy-MM-dd HH:mm:ss.fff}][{@l:u4}][{App}]{#if Key is not null}[{Key}]{#end} {@m}{#if @x is not null}\r\n{@x}{#end}";

_defaultLoggerConfiguration = new LoggerConfiguration()
.MinimumLevel.Verbose()
.Enrich.FromLogContext()
.WriteTo.Sink(new DebugConsoleSink(new JsonFormatter(renderMessage: true)), levelSwitch: _consoleLoggingLevelSwitch)
.Enrich.With(new CrestronEnricher())
.WriteTo.Sink(new DebugConsoleSink(new ExpressionTemplate("[{@t:yyyy-MM-dd HH:mm:ss.fff}][{@l:u4}][{App}]{#if Key is not null}[{Key}]{#end} {@m}{#if @x is not null}\r\n{@x}{#end}")), levelSwitch: _consoleLoggingLevelSwitch)
.WriteTo.Sink(_websocketSink, levelSwitch: _websocketLoggingLevelSwitch)
.WriteTo.Sink(new DebugErrorLogSink(), levelSwitch: _errorLogLevelSwitch)
.WriteTo.Sink(new DebugErrorLogSink(new ExpressionTemplate(errorLogTemplate)), levelSwitch: _errorLogLevelSwitch)
.WriteTo.File(new RenderedCompactJsonFormatter(), logFilePath,
rollingInterval: RollingInterval.Day,
restrictedToMinimumLevel: LogEventLevel.Debug,
Expand Down Expand Up @@ -187,7 +193,7 @@ static Debug()

CrestronConsole.PrintLine(msg);

LogError(ErrorLogLevel.Notice, msg);
LogMessage(LogEventLevel.Information,msg);

IncludedExcludedKeys = new Dictionary<string, object>();

Expand Down Expand Up @@ -591,7 +597,7 @@ public static void ShowDebugLog(string s)
/// <param name="args">Args to put into message template</param>
public static void LogMessage(Exception ex, string message, IKeyed device = null, params object[] args)
{
using (LogContext.PushProperty("Key", device?.Key ?? string.Empty))
using (LogContext.PushProperty("Key", device?.Key))
{
_logger.Error(ex, message, args);
}
Expand All @@ -606,7 +612,7 @@ public static void LogMessage(Exception ex, string message, IKeyed device = null
/// <param name="args">Args to put into message template</param>
public static void LogMessage(LogEventLevel level, string message, IKeyed device=null, params object[] args)
{
using (LogContext.PushProperty("Key", device?.Key ?? string.Empty))
using (LogContext.PushProperty("Key", device?.Key))
{
_logger.Write(level, message, args);
}
Expand Down Expand Up @@ -691,25 +697,8 @@ public static void Console(uint level, IKeyed dev, string format, params object[
[Obsolete("Use LogMessage methods")]
public static void Console(uint level, IKeyed dev, ErrorLogLevel errorLogLevel,
string format, params object[] items)
{

var str = string.Format("[{0}] {1}", dev.Key, string.Format(format, items));
if (errorLogLevel != ErrorLogLevel.None)
{
LogError(errorLogLevel, str);
}

{
LogMessage(level, dev, format, items);

//var log = _logger.ForContext("Key", dev.Key);
//var message = string.Format(format, items);

//log.Write((LogEventLevel)level, message);

//if (Level >= level)
//{
// Console(level, str);
//}
}

/// <summary>
Expand All @@ -719,17 +708,7 @@ public static void Console(uint level, IKeyed dev, ErrorLogLevel errorLogLevel,
public static void Console(uint level, ErrorLogLevel errorLogLevel,
string format, params object[] items)
{
var str = string.Format(format, items);
if (errorLogLevel != ErrorLogLevel.None)
{
LogError(errorLogLevel, str);
}

LogMessage(level, format, items);
//if (Level >= level)
//{
// Console(level, str);
//}
}

/// <summary>
Expand Down Expand Up @@ -770,18 +749,16 @@ public static void ConsoleWithLog(uint level, IKeyed dev, string format, params
[Obsolete("Use LogMessage methods")]
public static void LogError(ErrorLogLevel errorLogLevel, string str)
{

var msg = IsRunningOnAppliance ? string.Format("App {0}:{1}", InitialParametersClass.ApplicationNumber, str) : string.Format("Room {0}:{1}", InitialParametersClass.RoomId, str);
switch (errorLogLevel)
{
case ErrorLogLevel.Error:
ErrorLog.Error(msg);
LogMessage(LogEventLevel.Error, str);
break;
case ErrorLogLevel.Warning:
ErrorLog.Warn(msg);
LogMessage(LogEventLevel.Warning, str);
break;
case ErrorLogLevel.Notice:
ErrorLog.Notice(msg);
LogMessage(LogEventLevel.Information, str);
break;
}
}
Expand Down
12 changes: 10 additions & 2 deletions src/Pepperdash Core/Logging/DebugConsoleSink.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
using Serilog.Events;
using Serilog.Formatting;
using Serilog.Formatting.Json;
using System.IO;
using System.Text;


namespace PepperDash.Core
Expand All @@ -17,12 +19,18 @@ public void Emit(LogEvent logEvent)
{
if (!Debug.IsRunningOnAppliance) return;

string message = $"[{logEvent.Timestamp}][{logEvent.Level}][App {InitialParametersClass.ApplicationNumber}]{logEvent.RenderMessage()}";
/*string message = $"[{logEvent.Timestamp}][{logEvent.Level}][App {InitialParametersClass.ApplicationNumber}]{logEvent.RenderMessage()}";
if(logEvent.Properties.TryGetValue("Key",out var value) && value is ScalarValue sv && sv.Value is string rawValue)
{
message = $"[{logEvent.Timestamp}][{logEvent.Level}][App {InitialParametersClass.ApplicationNumber}][{rawValue,3}]: {logEvent.RenderMessage()}";
}
}*/

var buffer = new StringWriter(new StringBuilder(256));

_textFormatter.Format(logEvent, buffer);

var message = buffer.ToString();

CrestronConsole.PrintLine(message);
}
Expand Down
33 changes: 27 additions & 6 deletions src/Pepperdash Core/Logging/DebugErrorLogSink.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
using Crestron.SimplSharp;
using Serilog.Core;
using Serilog.Events;
using Serilog.Formatting;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
Expand All @@ -11,6 +13,8 @@ namespace PepperDash.Core.Logging
{
public class DebugErrorLogSink : ILogEventSink
{
private ITextFormatter _formatter;

private Dictionary<LogEventLevel, Action<string>> _errorLogMap = new Dictionary<LogEventLevel, Action<string>>
{
{ LogEventLevel.Verbose, (msg) => ErrorLog.Notice(msg) },
Expand All @@ -22,15 +26,27 @@ public class DebugErrorLogSink : ILogEventSink
};
public void Emit(LogEvent logEvent)
{
var programId = CrestronEnvironment.DevicePlatform == eDevicePlatform.Appliance
? $"App {InitialParametersClass.ApplicationNumber}"
: $"Room {InitialParametersClass.RoomId}";
string message;

if (_formatter == null)
{
var programId = CrestronEnvironment.DevicePlatform == eDevicePlatform.Appliance
? $"App {InitialParametersClass.ApplicationNumber}"
: $"Room {InitialParametersClass.RoomId}";

string message = $"[{logEvent.Timestamp}][{logEvent.Level}][{programId}]{logEvent.RenderMessage()}";
message = $"[{logEvent.Timestamp}][{logEvent.Level}][{programId}]{logEvent.RenderMessage()}";

if (logEvent.Properties.TryGetValue("Key", out var value) && value is ScalarValue sv && sv.Value is string rawValue)
if (logEvent.Properties.TryGetValue("Key", out var value) && value is ScalarValue sv && sv.Value is string rawValue)
{
message = $"[{logEvent.Timestamp}][{logEvent.Level}][{programId}][{rawValue}]: {logEvent.RenderMessage()}";
}
} else
{
message = $"[{logEvent.Timestamp}][{logEvent.Level}][{programId}][{rawValue}]: {logEvent.RenderMessage()}";
var buffer = new StringWriter(new StringBuilder(256));

_formatter.Format(logEvent, buffer);

message = buffer.ToString();
}

if(!_errorLogMap.TryGetValue(logEvent.Level, out var handler))
Expand All @@ -40,5 +56,10 @@ public void Emit(LogEvent logEvent)

handler(message);
}

public DebugErrorLogSink(ITextFormatter formatter = null)
{
_formatter = formatter;
}
}
}
39 changes: 39 additions & 0 deletions src/Pepperdash Core/Logging/DebugExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
using Serilog;
using Serilog.Events;
using Log = PepperDash.Core.Debug;

namespace PepperDash.Core.Logging
{
public static class DebugExtensions
{
public static void LogVerbose(this IKeyed device, string message, params object[] args)
{
Log.LogMessage(LogEventLevel.Verbose, device, message, args);
}

public static void LogDebug(this IKeyed device, string message, params object[] args)
{
Log.LogMessage(LogEventLevel.Debug, device, message, args);
}

public static void LogInformation(this IKeyed device, string message, params object[] args)
{
Log.LogMessage(LogEventLevel.Information, device, message, args);
}

public static void LogWarning(this IKeyed device, string message, params object[] args)
{
Log.LogMessage(LogEventLevel.Warning, device, message, args);
}

public static void LogError(this IKeyed device, string message, params object[] args)
{
Log.LogMessage(LogEventLevel.Error, device, message, args);
}

public static void LogFatal(this IKeyed device, string message, params object[] args)
{
Log.LogMessage(LogEventLevel.Fatal, device, message, args);
}
}
}
5 changes: 3 additions & 2 deletions src/Pepperdash Core/PepperDash_Core.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,11 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="BouncyCastle" Version="1.8.9" />
<PackageReference Include="Crestron.SimplSharp.SDK.Library" Version="2.20.42" />
<PackageReference Include="Crestron.SimplSharp.SDK.Library" Version="2.20.66" />
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.Expressions" Version="4.0.0" />
<PackageReference Include="Serilog.Formatting.Compact" Version="2.0.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="5.0.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="5.0.1" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
<PackageReference Include="WebSocketSharp" Version="1.0.3-rc11" />
</ItemGroup>
Expand Down

0 comments on commit d403c29

Please sign in to comment.