Skip to content

Commit

Permalink
chore: core logging functionality implemented
Browse files Browse the repository at this point in the history
  • Loading branch information
jp-weber committed Mar 9, 2024
1 parent 54c4418 commit dc8a312
Show file tree
Hide file tree
Showing 17 changed files with 234 additions and 28 deletions.
1 change: 1 addition & 0 deletions Project2FA.Core/Constants.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,6 @@ public static class Constants
public const string SupportSubscriptionId = "9N0PKJ5MF92B";
public const string LifeTimeId = "9PCLBSQW4DLN";
public const string EnterpriseAppManagementContainer = "Managed.App.Settings";
public const string LogName = "AppLog.log";
}
}
2 changes: 2 additions & 0 deletions Project2FA.Shared/Project2FA.Shared.projitems
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,8 @@
<Compile Include="$(MSBuildThisFileDirectory)Models\SymbolModel.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Models\TwoFACodeModel.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Services\DataService.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Services\Logging\ILoggingService.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Services\Logging\LoggingService.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Services\Parser\IProject2FAParser.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Services\Parser\Project2FAParser.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Services\SerializationService.cs" />
Expand Down
22 changes: 17 additions & 5 deletions Project2FA.Shared/Services/DataService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@
using CommunityToolkit.WinUI.Helpers;
using CommunityToolkit.WinUI.Collections;
using UNOversal.Services.Serialization;
using Project2FA.Services.Logging;




Expand Down Expand Up @@ -84,6 +86,7 @@ public SemaphoreSlim CollectionAccessSemaphore
private ISerializationService SerializationService { get; }
private bool _initialization, _errorOccurred;
private INewtonsoftJSONService NewtonsoftJSONService { get; }
private ILoggingService LoggingService { get; }
public Stopwatch TOTPEventStopwatch { get; }
public AdvancedCollectionView ACVCollection { get; }
public ObservableCollection<TwoFACodeModel> Collection { get; } = new ObservableCollection<TwoFACodeModel>();
Expand Down Expand Up @@ -124,6 +127,7 @@ private DataService()
SerializationService = App.Current.Container.Resolve<ISerializationService>();
NetworkTimeService = App.Current.Container.Resolve<INetworkTimeService>();
NetworkService = App.Current.Container.Resolve<INetworkService>();
LoggingService = App.Current.Container.Resolve<ILoggingService>();
ACVCollection = new AdvancedCollectionView(Collection, true);
TOTPEventStopwatch = new Stopwatch();
//ACVCollection.SortDescriptions.Add(new SortDescription("Label", SortDirection.Ascending));
Expand Down Expand Up @@ -151,6 +155,7 @@ private async Task LoadFontIconList()
}
catch (Exception exc)
{
LoggingService.LogException(exc);
#if WINDOWS_UWP
TrackingManager.TrackExceptionCatched(nameof(LoadFontIconList), exc);
#endif
Expand Down Expand Up @@ -182,6 +187,7 @@ private async Task CheckTime()
}
catch (Exception exc)
{
LoggingService.LogException(exc);
Logger.Log("NTP exception: " + exc.Message, Category.Exception, Priority.Low);
//TrackingManager.TrackException(exc);
}
Expand Down Expand Up @@ -487,6 +493,7 @@ await Task.Run(async () => {
}
catch (Exception exc)
{
await LoggingService.LogException(exc);
_errorOccurred = true;
#if WINDOWS_UWP
TrackingManager.TrackExceptionCatched(nameof(CheckLocalDatafile) + " PW", exc);
Expand All @@ -506,7 +513,6 @@ await Task.Run(async () => {
}
#endif
}

}
// file not found case
else
Expand All @@ -528,6 +534,7 @@ await Task.Run(async () => {
catch (Exception exc)
#pragma warning restore CA1031 // Do not catch general exception types
{
await LoggingService.LogException(exc);
_errorOccurred = true;
if (exc is UnauthorizedAccessException)
{
Expand Down Expand Up @@ -802,6 +809,7 @@ await Task.Run(async () => {
catch (Exception exc)
{
CollectionAccessSemaphore.Release();
await LoggingService.LogException(exc);
#if WINDOWS_UWP
TrackingManager.TrackExceptionCatched(nameof(WriteLocalDatafile), exc);
#endif
Expand Down Expand Up @@ -848,6 +856,7 @@ await FileService.WriteStringAsync(
}
catch (Exception exc)
{
await LoggingService.LogException(exc);
#if WINDOWS_UWP
TrackingManager.TrackExceptionCatched(nameof(RestoreLastDatafile), exc);
#endif
Expand Down Expand Up @@ -892,14 +901,17 @@ public async Task GenerateTOTP(int i)
}
else
{
Collection[i].TwoFACode = "Error";
await LoggingService.Log("ArgumentNullException " + Collection[i].Label);
throw new ArgumentNullException(Collection[i].Label);
}
}
catch (Exception ex)
catch (Exception exc)
{
Logger.Log(ex.Message, Category.Exception, Priority.High);
await LoggingService.LogException(exc);
Logger.Log(exc.Message, Category.Exception, Priority.High);
#if WINDOWS_UWP
TrackingManager.TrackExceptionCatched(nameof(GenerateTOTP), ex);
TrackingManager.TrackExceptionCatched(nameof(GenerateTOTP), exc);
#endif
_reloadCollectionCounter++;
if (_reloadCollectionCounter < 3)
Expand All @@ -910,7 +922,7 @@ public async Task GenerateTOTP(int i)
{
// track if the creation finally failed
#if WINDOWS_UWP
TrackingManager.TrackExceptionUnhandled(nameof(GenerateTOTP), ex);
TrackingManager.TrackExceptionUnhandled(nameof(GenerateTOTP), exc);
#endif
Collection[i].TwoFACode = string.Empty;
await ErrorDialogs.SecretKeyError(Collection[i].Label).ConfigureAwait(false);
Expand Down
14 changes: 14 additions & 0 deletions Project2FA.Shared/Services/Logging/ILoggingService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Project2FA.Services.Logging
{
public interface ILoggingService
{
Task Log(string message);
Task LogException(Exception exc);
}
}
85 changes: 85 additions & 0 deletions Project2FA.Shared/Services/Logging/LoggingService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
using Project2FA.Core;
using Project2FA.Services.Enums;
using System;
using System.Threading.Tasks;
using UNOversal.Services.File;
using Windows.Storage;

namespace Project2FA.Services.Logging
{
/// <summary>
/// Service for logging of exception and custom messages
/// </summary>
public class LoggingService : ILoggingService
{
private string _timeStemp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " - ";

private IFileService FileService { get; }

public LoggingService(IFileService fileService)
{
FileService = fileService;
}

/// <summary>
/// Log a custom message
/// </summary>
/// <param name="message"></param>
/// <returns></returns>
public async Task Log(string message)
{
if (SettingsService.Instance.LoggingSetting == LoggingPreferEnum.Full)
{
if(await FileService.FileExistsAsync(Constants.LogName, ApplicationData.Current.LocalFolder))
{
var file = await ApplicationData.Current.LocalFolder.GetFileAsync(Constants.LogName);
await FileIO.AppendTextAsync(file, _timeStemp + message);
}
else
{
var file = await ApplicationData.Current.LocalFolder.CreateFileAsync(Constants.LogName);
await FileIO.AppendTextAsync(file, _timeStemp + message);
}
}
}

/// <summary>
/// Log a exception
/// </summary>
/// <param name="exc"></param>
/// <returns></returns>
public async Task LogException(Exception exc)
{
if (SettingsService.Instance.LoggingSetting == LoggingPreferEnum.Simple ||
SettingsService.Instance.LoggingSetting == LoggingPreferEnum.Full)
{
if (await FileService.FileExistsAsync(Constants.LogName, ApplicationData.Current.LocalFolder))
{
var file = await ApplicationData.Current.LocalFolder.GetFileAsync(Constants.LogName);
await WriteExceptionLog(exc, file);

}
else
{
var file = await ApplicationData.Current.LocalFolder.CreateFileAsync(Constants.LogName);
await WriteExceptionLog(exc, file);
}
}
}

/// <summary>
/// Write the exception to a file
/// </summary>
/// <param name="exc"></param>
/// <param name="file"></param>
/// <returns></returns>
private async Task WriteExceptionLog(Exception exc, StorageFile file)
{
await FileIO.AppendTextAsync(file, _timeStemp + exc.Source + " - " + exc.Message + "\n");
if (exc.InnerException != null)
{
await FileIO.AppendTextAsync(file, "InnerException - " + exc.InnerException.ToString() + "\n");
}
}
}
}
6 changes: 6 additions & 0 deletions Project2FA.Shared/Strings/de/Resources.resw
Original file line number Diff line number Diff line change
Expand Up @@ -1322,4 +1322,10 @@ Derzeit verfügbar:
<data name="SettingsOpenLogBTN.Content" xml:space="preserve">
<value>Fehlerprotokoll anzeigen</value>
</data>
<data name="SettingsPageNoLogDialogContent" xml:space="preserve">
<value>Derzeit wurde kein Fehlerbericht erstellt.</value>
</data>
<data name="SettingsPageNoLogDialogTitle" xml:space="preserve">
<value>Kein Fehlerbericht vorhanden</value>
</data>
</root>
21 changes: 21 additions & 0 deletions Project2FA.Shared/Strings/en/Resources.generated.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1980,6 +1980,27 @@ public static string LoginPageWindowsHelloError
}
}
#endregion

#region SettingsPageNoLogDialogTitle
public static string SettingsPageNoLogDialogTitle
{
get
{
return _resourceLoader.GetString("SettingsPageNoLogDialogTitle");
}
}
#endregion

#region SettingsPageNoLogDialogContent
public static string SettingsPageNoLogDialogContent
{
get
{
return _resourceLoader.GetString("SettingsPageNoLogDialogContent");
}
}
#endregion

}

[global::System.CodeDom.Compiler.GeneratedCodeAttribute("DotNetPlus.ReswPlus", "2.1.3")]
Expand Down
6 changes: 6 additions & 0 deletions Project2FA.Shared/Strings/en/Resources.resw
Original file line number Diff line number Diff line change
Expand Up @@ -1316,4 +1316,10 @@ Currently available:
<data name="SettingsOpenLogBTN.Content" xml:space="preserve">
<value>Show error log</value>
</data>
<data name="SettingsPageNoLogDialogContent" xml:space="preserve">
<value>No error report has been created at this time.</value>
</data>
<data name="SettingsPageNoLogDialogTitle" xml:space="preserve">
<value>No error report available</value>
</data>
</root>
10 changes: 8 additions & 2 deletions Project2FA.Shared/ViewModels/AccountCodePageViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@
using System.Collections.Generic;
using System.Linq;
using Project2FA.Core.Utils;
using Project2FA.Services.Logging;




Expand Down Expand Up @@ -74,6 +76,7 @@ public class AccountCodePageViewModel : ObservableRecipient, IConfirmNavigationA
public ICommand NavigateToSettingsCommand { get; }
public ICommand SetFilterCommand { get; }
public ICommand CameraCommand { get; }
private ILoggingService LoggingService { get; }

public ICommand ShowProFeatureCommand { get; }

Expand All @@ -89,11 +92,12 @@ public class AccountCodePageViewModel : ObservableRecipient, IConfirmNavigationA
private bool _proFeatureRequest;


public AccountCodePageViewModel(IDialogService dialogService, ILoggerFacade loggerFacade, INavigationService navigationService)
public AccountCodePageViewModel(IDialogService dialogService, ILoggerFacade loggerFacade, INavigationService navigationService, ILoggingService loggingService)
{
DialogService = dialogService;
Logger = loggerFacade;
NavigationService = navigationService;
LoggingService = loggingService;

_dispatcherTOTPTimer = new DispatcherTimer();
_dispatcherTOTPTimer.Interval = new TimeSpan(0, 0, 0, 1); //every second
Expand Down Expand Up @@ -350,8 +354,9 @@ private async Task<bool> CopyCodeToClipboardCommandTask(TwoFACodeModel model)
Clipboard.SetContent(dataPackage);
return true;
}
catch (System.Exception)
catch (Exception exc)
{
await LoggingService.LogException(exc);
ContentDialog dialog = new ContentDialog();
dialog.Title = Strings.Resources.ErrorHandle;
dialog.Content = Strings.Resources.ErrorClipboardTask;
Expand Down Expand Up @@ -603,6 +608,7 @@ public void SetSuggestionList(string searchText)
}
catch (System.Exception exc)
{
LoggingService.LogException(exc);
TwoFADataService.ACVCollection.Filter = null;
#if WINDOWS_UWP
TrackingManager.TrackExceptionCatched(nameof(SetSuggestionList), exc);
Expand Down
5 changes: 5 additions & 0 deletions Project2FA.Shared/ViewModels/FileActivationPageViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@
using CommunityToolkit.Mvvm.Messaging;
using Project2FA.Core.Messenger;
using Project2FA.Core.Services.Crypto;
using Project2FA.Services.Logging;


#if WINDOWS_UWP
using Windows.Security.Cryptography;
Expand Down Expand Up @@ -48,6 +50,7 @@ public class FileActivationPageViewModel : ObservableRecipient
private IDialogService DialogService { get; }
private ISecretService SecretService { get; }
private IFileService FileService { get; }
private ILoggingService LoggingService { get; }
private INewtonsoftJSONService NewtonsoftJSONService { get; }
private string _applicationTitle;
private bool _isScreenCaptureEnabled;
Expand All @@ -58,6 +61,7 @@ public FileActivationPageViewModel()
DialogService = App.Current.Container.Resolve<IDialogService>();
NewtonsoftJSONService = App.Current.Container.Resolve<INewtonsoftJSONService>();
FileService = App.Current.Container.Resolve<IFileService>();
LoggingService = App.Current.Container.Resolve<ILoggingService>();
LoginCommand = new RelayCommand(CheckLogin);
App.ShellPageInstance.ViewModel.NavigationIsAllowed = false;
var title = Windows.ApplicationModel.Package.Current.DisplayName;
Expand Down Expand Up @@ -174,6 +178,7 @@ await Task.Run(async () =>
}
catch (Exception exc)
{
await LoggingService.LogException(exc);
//Error = exc.Message;
//ShowError = true;
//Password = string.Empty;
Expand Down
5 changes: 5 additions & 0 deletions Project2FA.Shared/ViewModels/LoginPageViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
using Windows.ApplicationModel.Core;

using Windows.ApplicationModel.DataTransfer;
using Project2FA.Services.Logging;




Expand Down Expand Up @@ -60,6 +62,7 @@ namespace Project2FA.ViewModels
#endif
public class LoginPageViewModel : CredentialViewModelBase
{
private ILoggingService LoggingService { get; }
#if ANDROID || IOS
private IBiometryService BiometryService { get; }
private readonly CancellationToken _cancellationToken = CancellationToken.None;
Expand All @@ -70,6 +73,7 @@ public class LoginPageViewModel : CredentialViewModelBase
public LoginPageViewModel()
{
DialogService = App.Current.Container.Resolve<IDialogService>();
LoggingService = App.Current.Container.Resolve<LoggingService>();
LoginCommand = new RelayCommand(CheckLogin);
#if WINDOWS_UWP
WindowsHelloLoginCommand = new RelayCommand(WindowsHelloLoginCommandTask);
Expand Down Expand Up @@ -198,6 +202,7 @@ private async void WindowsHelloLoginCommandTask()
}
catch (Exception exc)
{
await LoggingService.LogException(exc);
TrackingManager.TrackExceptionCatched(nameof(WindowsHelloLoginCommandTask), exc);
var dialog = new ContentDialog
{
Expand Down
Loading

0 comments on commit dc8a312

Please sign in to comment.