Skip to content

Commit

Permalink
NR use NLog and improve logging and tracking via telemetry
Browse files Browse the repository at this point in the history
  • Loading branch information
jbe2277 committed Dec 27, 2023
1 parent 845d5d1 commit 6486c2a
Show file tree
Hide file tree
Showing 13 changed files with 132 additions and 100 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,7 @@ public async Task<FeedManager> Load()
catch (Exception ex)
{
// Better to forget the settings (data loss) as to never start the app again
Log.Default.Error("DataController.Load: {0}", ex);
Crashes.TrackError(ex);
Log.Default.TrackError(ex, "DataController.Load");
feedManager = new FeedManager();
}
loadCompletion.SetResult(feedManager!);
Expand All @@ -80,8 +79,7 @@ private async Task SignIn()
}
catch (Exception ex)
{
Log.Default.Error("Account sign in failed: {0}", ex);
Crashes.TrackError(ex);
Log.Default.TrackError(ex, "Account sign in failed");
await messageService.ShowMessage(Resources.SignInError, ex.Message);
}
}
Expand All @@ -108,8 +106,7 @@ private async Task DownloadAndMerge()
}
catch (Exception ex)
{
Log.Default.Error("Download failed: {0}", ex);
Crashes.TrackError(ex);
Log.Default.TrackError(ex, "Download failed");
messageService.ShowMessage(Resources.SynchronizationDownloadError, ex.Message).NoWait();
}

Expand All @@ -136,8 +133,7 @@ private async Task Upload()
}
catch (Exception ex)
{
Log.Default.Error("Upload failed: {0}", ex);
Crashes.TrackError(ex);
Log.Default.TrackError(ex, "Upload failed");
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -112,8 +112,7 @@ private async Task LoadFeed(Feed feed, bool ignoreInternetAccessStatus = false)
}
catch (Exception ex)
{
Log.Default.Error("Load Feed failed: {0}", ex);
Crashes.TrackError(ex);
Log.Default.TrackError(ex, "Load Feed failed");
feed.SetLoadError(ex, Resources.ErrorLoadRssFeed + " " + ex.Message);
}
}
Expand Down
8 changes: 4 additions & 4 deletions src/NewsReader/NewsReader.Applications/Log.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
using System.Diagnostics;
using NLog;

namespace Waf.NewsReader.Applications;

public static class Log
internal static class Log
{
public static TraceSource Default { get; } = new TraceSource("App");
}
public static Logger Default { get; } = LogManager.GetLogger("App");
}
19 changes: 19 additions & 0 deletions src/NewsReader/NewsReader.Applications/LogExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
using Microsoft.AppCenter.Crashes;
using NLog;

namespace Waf.NewsReader.Applications;

public static class LogExtensions
{
public static void TrackError(this Logger log, Exception ex, [Localizable(false)] string message)
{
log.Error(ex, message);
Crashes.TrackError(ex);
}

public static void TrackError(this Logger log, Exception ex, [Localizable(false)] string format, params object?[] arguments)
{
log.Error(ex, format, arguments);
Crashes.TrackError(ex);
}
}
8 changes: 8 additions & 0 deletions src/NewsReader/NewsReader.Domain/Log.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
using NLog;

namespace Waf.NewsReader.Domain;

internal static class Log
{
public static Logger Default { get; } = LogManager.GetLogger("Dom");
}
1 change: 1 addition & 0 deletions src/NewsReader/NewsReader.Domain/NewsReader.Domain.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="NLog" Version="5.2.7" />
<PackageReference Include="System.Waf.Core" Version="7.0.1-alpha.0.80" />
</ItemGroup>

Expand Down
9 changes: 9 additions & 0 deletions src/NewsReader/NewsReader.MauiSystem/Log.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
using NLog;

namespace Waf.NewsReader.MauiSystem;

internal static class Log
{
public static Logger Default { get; } = LogManager.GetLogger("Sys");
}

58 changes: 46 additions & 12 deletions src/NewsReader/NewsReader.Presentation/App.xaml.cs
Original file line number Diff line number Diff line change
@@ -1,19 +1,22 @@
using Microsoft.AppCenter.Analytics;
using Microsoft.AppCenter.Crashes;
using Microsoft.AppCenter;
using System.Diagnostics;
using System.Globalization;
using System.Waf.Applications.Services;
using Waf.NewsReader.Applications.Controllers;
using Waf.NewsReader.Applications.Properties;
using Waf.NewsReader.Applications.Services;
using NLog;
using NLog.Targets;
using NLog.Targets.Wrappers;
using LogLevel = NLog.LogLevel;
using Waf.NewsReader.Presentation.Services;
using Waf.NewsReader.Applications;

namespace Waf.NewsReader.Presentation;

// Telemetry data collection with https://appcenter.ms
// Provide the secrets via separate file 'App.xaml.keys.cs' which will be excluded from GIT:
// Provide the secrets via separate file 'App.xaml.keys.cs' which is excluded from GIT:
//
//public partial class App
//{
// static partial void GetAppCenterSecret(ref string? appSecret)
Expand All @@ -24,6 +27,16 @@ namespace Waf.NewsReader.Presentation;

public partial class App : Application
{
// TODO: Share log file in Debug view

private static readonly (string loggerNamePattern, LogLevel minLevel)[] logSettings =
[
("Dom", LogLevel.Info),
("App", LogLevel.Info),
("Pre", LogLevel.Info),
("Sys", LogLevel.Info),
];

private readonly ISettingsService settingsService;
private readonly IAppInfoService appInfoService;
private readonly IAppController appController;
Expand All @@ -45,6 +58,8 @@ public App(ISettingsService settingsService, IAppInfoService appInfoService, Laz
MainPage = (Page)this.appController.MainView;
}

public static string LogFileName { get; } = Path.Combine(FileSystem.Current.CacheDirectory, "Logging", "AppLog.txt");

protected override Window CreateWindow(IActivationState? activationState)
{
var window = base.CreateWindow(activationState);
Expand All @@ -69,6 +84,7 @@ private void OnCreated()
string? appSecret = null;
GetAppCenterSecret(ref appSecret);
if (appSecret != null) AppCenter.Start(appSecret, typeof(Analytics), typeof(Crashes));
Analytics.TrackEvent("App started");
appController.Start();
}

Expand Down Expand Up @@ -104,16 +120,34 @@ private void OnResumed()

private static void InitializeLogging()
{
Log.Default.Switch.Level = SourceLevels.All;
var sources = new[]
LogManager.Setup().LoadConfiguration(c =>
{
Log.Default
};
foreach (var source in sources)
{
source.Listeners.Clear();
source.Listeners.Add(new AppTraceListener());
}
c.Configuration.DefaultCultureInfo = CultureInfo.InvariantCulture;
var layout = "${date:format=yyyy-MM-dd HH\\:mm\\:ss.ff} [${level:format=FirstCharacter}] ${logger} ${message} ${exception}";
var fileTarget = c.ForTarget("fileTarget").WriteTo(new FileTarget
{
FileName = LogFileName,
Layout = layout,
ArchiveAboveSize = 5_000_000, // 5 MB
MaxArchiveFiles = 1,
ArchiveNumbering = ArchiveNumberingMode.Rolling
}).WithAsync(AsyncTargetWrapperOverflowAction.Block);
#if DEBUG
var traceTarget = c.ForTarget("traceTarget").WriteTo(new AppTraceTarget
{
Layout = layout,
}).WithAsync(AsyncTargetWrapperOverflowAction.Block);
#endif
foreach (var (loggerNamePattern, minLevel) in logSettings)
{
c.ForLogger(loggerNamePattern).FilterMinLevel(minLevel).WriteTo(fileTarget)
#if DEBUG
.WriteTo(traceTarget)
#endif
;
}
});
}

private static void InitializeCultures(AppSettings appSettings)
Expand Down
4 changes: 3 additions & 1 deletion src/NewsReader/NewsReader.Presentation/GlobalSuppressions.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
[assembly: SuppressMessage("Design", "CA1001:Types that own disposable fields should be disposable", Justification = "<Pending>", Scope = "type", Target = "~T:Waf.NewsReader.Presentation.Views.FeedItemView")]

[assembly: SuppressMessage("Design", "CA1001:Types that own disposable fields should be disposable", Justification = "<Pending>", Scope = "type", Target = "~T:Waf.NewsReader.Presentation.Views.FeedItemView")]
[assembly: SuppressMessage("Security", "CA5350:Do Not Use Weak Cryptographic Algorithms", Justification = "<Pending>", Scope = "member", Target = "~M:Waf.NewsReader.Presentation.Services.DataService.GetHash~System.String")]
[assembly: SuppressMessage("Performance", "CA1812: Avoid uninstantiated internal classes", Scope = "type", Target = "~T:Waf.NewsReader.Presentation.Services.WebStorageService")]
[assembly: SuppressMessage("Naming", "CA1724:Type names should not match namespaces", Justification = "<Pending>", Scope = "type", Target = "~T:Waf.NewsReader.Presentation.App")]
[assembly: SuppressMessage("Globalization", "CA1305:Specify IFormatProvider", Justification = "<Pending>", Scope = "member", Target = "~M:Waf.NewsReader.Presentation.App.OnCreated")]
9 changes: 9 additions & 0 deletions src/NewsReader/NewsReader.Presentation/Log.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
using NLog;

namespace Waf.NewsReader.Presentation;

internal static class Log
{
public static Logger Default { get; } = LogManager.GetLogger("Pre");
}

This file was deleted.

27 changes: 27 additions & 0 deletions src/NewsReader/NewsReader.Presentation/Services/AppTraceTarget.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
using NLog;
using NLog.Targets;

namespace Waf.NewsReader.Presentation.Services;

internal sealed class AppTraceTarget : TargetWithLayout

Check warning on line 6 in src/NewsReader/NewsReader.Presentation/Services/AppTraceTarget.cs

View workflow job for this annotation

GitHub Actions / iOS

'AppTraceTarget' is an internal class that is apparently never instantiated. If so, remove the code from the assembly. If this class is intended to contain only static members, make it 'static' (Module in Visual Basic). (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1812)

Check warning on line 6 in src/NewsReader/NewsReader.Presentation/Services/AppTraceTarget.cs

View workflow job for this annotation

GitHub Actions / iOS

'AppTraceTarget' is an internal class that is apparently never instantiated. If so, remove the code from the assembly. If this class is intended to contain only static members, make it 'static' (Module in Visual Basic). (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1812)
{
protected override void Write(LogEventInfo logEvent)
{
string message = RenderLogEvent(Layout, logEvent);
#if ANDROID
var x = logEvent.Level;
if (x == LogLevel.Fatal || x == LogLevel.Error)
Android.Util.Log.Error(logEvent.LoggerName, message);
else if (x == LogLevel.Warn)
Android.Util.Log.Warn(logEvent.LoggerName, message);
else if (x == LogLevel.Info)
Android.Util.Log.Info(logEvent.LoggerName, message);
else
Android.Util.Log.Verbose(logEvent.LoggerName, message);
#elif IOS
Console.WriteLine(message);
#else
System.Diagnostics.Trace.WriteLine(message);
#endif
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,7 @@ public async Task<bool> TrySilentSignIn()
}
catch (Exception ex)
{
Log.Default.Warn("Silent login failed: {0}", ex);
Crashes.TrackError(ex);
Log.Default.TrackError(ex, "Silent login failed");
// Ignore (e.g. no internet access)
}
return false;
Expand Down

0 comments on commit 6486c2a

Please sign in to comment.