Skip to content

Commit

Permalink
Centralize c# logger (#22760)
Browse files Browse the repository at this point in the history
* Initial commit

* Changed some loggers (WIP)

* ColorPicker

* Add version to all logs

* FancyZones

* push

* PowerOCR and Measuretool

* Settings

* Hosts + Fix settings

* Fix some using statements

* FileLocksmith

* Fix awake

* Fixed Hosts logger

* Fix spelling

* Remove added submodule

* Fiy FileLocksmith and PowerAccent

* Fix PowerAccent

* Test

* Changed logger locic and added ColorPicker

* Fixed package

* Add documentation

* Add locallow capability to Logger and add FancyZones

* Fixed FancyZones and added FileLocksmith

* Add Hosts

* Fixed spelling mistakes

* Add MeasureTool

* Add MouseJump

* Add PowerOCR

* Add PowerAccent

* Add monaco

* Add Settings

* Fixed Monaco

* Update installer

* Update doc/devdocs/logging.md

Co-authored-by: Stefan Markovic <57057282+stefansjfw@users.noreply.github.com>

* Update doc/devdocs/logging.md

Co-authored-by: Stefan Markovic <57057282+stefansjfw@users.noreply.github.com>

* Update doc/devdocs/logging.md

Co-authored-by: Stefan Markovic <57057282+stefansjfw@users.noreply.github.com>

* Update logging.md

* Fix unneccesairy includes.

---------

Co-authored-by: Dustin L. Howett <dustin@howett.net>
Co-authored-by: Stefan Markovic <stefan@janeasystems.com>
Co-authored-by: Stefan Markovic <57057282+stefansjfw@users.noreply.github.com>
  • Loading branch information
4 people committed Mar 21, 2023
1 parent 7d6a774 commit 5da8809
Show file tree
Hide file tree
Showing 68 changed files with 150 additions and 749 deletions.
1 change: 1 addition & 0 deletions .github/actions/spell-check/expect.txt
Expand Up @@ -322,6 +322,7 @@ cxfksword
CXSCREEN
CXSMICON
CXVIRTUALSCREEN
cxxopts
cyberrex
CYSCREEN
CYSMICON
Expand Down
56 changes: 54 additions & 2 deletions doc/devdocs/logging.md
@@ -1,9 +1,61 @@
# How to use
# Logging

We use the awesome [spdlog](https://github.com/gabime/spdlog) library for logging as a git submodule under the `deps` directory. To use it in your project, just include [spdlog.props](../../deps/spdlog.props) in a .vcxproj like this:
Logging plays an important part in determining bugs in our code. It provides context for the developers about where and when errors occur.

## Where are the logs saved

* Most of the logs are saved under `%LOCALAPPDATA%/Microsoft/PowerToys`.
* For low-privilege processes (like preview handlers) the logs are saved under `%USERPROFILE%/AppData/LocalLow/Microsoft/PowerToys`.

Logs are normally in a subfolder with the module name as title.

The [BugReportTool](/tools/BugReportTool) will take logs from both locations when executed.

## Using a logger in a project

### Spdlog

In C++ projects we use the awesome [spdlog](https://github.com/gabime/spdlog) library for logging as a git submodule under the `deps` directory. To use it in your project, just include [spdlog.props](/deps/spdlog.props) in a .vcxproj like this:

```xml
<Import Project="..\..\..\deps\spdlog.props" />
```
It'll add the required include dirs and link the library binary itself.

### PowerToys Logger in ManagedCommon

For C# projects there is a static logger class in Managed Common called `Logger`.

To use it, add a project reference to `ManagedCommon` and add the following line of code to all the files using the logger:

```Csharp
using ManagedCommon;
```

In the `Main` function (or a function with a similar meaning (like `App` in a `App.xaml.cs` file)) you have to call `InitializeLogger` and specify the location where the logs will be saved (always use a path scheme similar to this example):

```Csharp
Logger.InitializeLogger("\\FancyZones\\Editor\\Logs");
```

For a low-privilege process you have to set the optional second parameter to `true`:

```Csharp
Logger.InitializeLogger("\\FileExplorer\\Monaco\\Logs", true);
```

The `Logger` class contains the following logging functions:

```Csharp
// Logs an error that the utility encountered
Logger.LogError(string message);
Logger.LogError(string message, Exception ex);
// Logs an error that isn't that grave
Logger.LogWarning(string message);
// Logs what the app is doing at the moment
Logger.LogInfo(string message);
// Like LogInfo just with infos important for debugging
Logger.LogDebug(string message);
// Logs the current state of the utility.
Logger.LogTrace();
```
2 changes: 1 addition & 1 deletion installer/PowerToysSetup/FileLocksmith.wxs
Expand Up @@ -4,7 +4,7 @@

<?include $(sys.CURRENTDIR)\Common.wxi?>

<?define FileLocksmithFiles=Microsoft.Win32.SystemEvents.dll;Microsoft.Xaml.Interactions.dll;Microsoft.Xaml.Interactivity.dll;CommunityToolkit.WinUI.dll;CommunityToolkit.WinUI.UI.dll;CommunityToolkit.Common.dll;CommunityToolkit.Mvvm.dll;CommunityToolkit.Labs.WinUI.SettingsControls.dll;Ijwhost.dll;Microsoft.InteractiveExperiences.Projection.dll;Microsoft.Windows.ApplicationModel.DynamicDependency.Projection.dll;Microsoft.Windows.ApplicationModel.Resources.Projection.dll;Microsoft.Windows.ApplicationModel.WindowsAppRuntime.Projection.dll;Microsoft.Windows.AppLifecycle.Projection.dll;Microsoft.Windows.SDK.NET.dll;Microsoft.Windows.System.Power.Projection.dll;Microsoft.WindowsAppRuntime.Bootstrap.Net.dll;Microsoft.WinUI.dll;PowerToys.ManagedCommon.dll;PowerToys.ManagedTelemetry.dll;PowerToys.FileLocksmithExt.dll;PowerToys.FileLocksmithLib.Interop.dll;PowerToys.FileLocksmithUI.exe;PowerToys.FileLocksmithUI.dll;PowerToys.FileLocksmithUI.deps.json;PowerToys.FileLocksmithUI.runtimeconfig.json;System.CodeDom.dll;System.Drawing.Common.dll;System.Management.dll;WinRT.Runtime.dll;WinUIEx.dll;resources.pri;PowerToys.GPOWrapper.dll;WindowsBase.dll;System.Text.Json.dll?>
<?define FileLocksmithFiles=System.IO.Abstractions.dll;Microsoft.Win32.SystemEvents.dll;Microsoft.Xaml.Interactions.dll;Microsoft.Xaml.Interactivity.dll;CommunityToolkit.WinUI.dll;CommunityToolkit.WinUI.UI.dll;CommunityToolkit.Common.dll;CommunityToolkit.Mvvm.dll;CommunityToolkit.Labs.WinUI.SettingsControls.dll;Ijwhost.dll;Microsoft.InteractiveExperiences.Projection.dll;Microsoft.Windows.ApplicationModel.DynamicDependency.Projection.dll;Microsoft.Windows.ApplicationModel.Resources.Projection.dll;Microsoft.Windows.ApplicationModel.WindowsAppRuntime.Projection.dll;Microsoft.Windows.AppLifecycle.Projection.dll;Microsoft.Windows.SDK.NET.dll;Microsoft.Windows.System.Power.Projection.dll;Microsoft.WindowsAppRuntime.Bootstrap.Net.dll;Microsoft.WinUI.dll;PowerToys.ManagedCommon.dll;PowerToys.ManagedTelemetry.dll;PowerToys.FileLocksmithExt.dll;PowerToys.FileLocksmithLib.Interop.dll;PowerToys.FileLocksmithUI.exe;PowerToys.FileLocksmithUI.dll;PowerToys.FileLocksmithUI.deps.json;PowerToys.FileLocksmithUI.runtimeconfig.json;System.CodeDom.dll;System.Drawing.Common.dll;System.Management.dll;WinRT.Runtime.dll;WinUIEx.dll;resources.pri;PowerToys.GPOWrapper.dll;WindowsBase.dll;System.Text.Json.dll?>
<?define FileLocksmithAssetsFiles=Icon.ico?>

<Fragment>
Expand Down
2 changes: 1 addition & 1 deletion installer/PowerToysSetup/MeasureTool.wxs
Expand Up @@ -4,7 +4,7 @@

<?include $(sys.CURRENTDIR)\Common.wxi?>

<?define MeasureToolFiles=Ijwhost.dll;Microsoft.InteractiveExperiences.Projection.dll;Microsoft.Windows.ApplicationModel.DynamicDependency.Projection.dll;Microsoft.Windows.ApplicationModel.Resources.Projection.dll;Microsoft.Windows.ApplicationModel.WindowsAppRuntime.Projection.dll;Microsoft.Windows.AppLifecycle.Projection.dll;Microsoft.Windows.SDK.NET.dll;Microsoft.Windows.System.Power.Projection.dll;Microsoft.WindowsAppRuntime.Bootstrap.Net.dll;Microsoft.WinUI.dll;PowerToys.ManagedCommon.dll;PowerToys.ManagedTelemetry.dll;PowerToys.MeasureToolCore.dll;PowerToys.MeasureToolUI.deps.json;PowerToys.MeasureToolUI.dll;PowerToys.MeasureToolUI.exe;PowerToys.MeasureToolUI.runtimeconfig.json;resources.pri;System.CodeDom.dll;System.Management.dll;System.Text.Json.dll;WinRT.Runtime.dll;WinUIEx.dll;PowerToys.GPOWrapper.dll;WindowsBase.dll?>
<?define MeasureToolFiles=System.IO.Abstractions.dll;Ijwhost.dll;Microsoft.InteractiveExperiences.Projection.dll;Microsoft.Windows.ApplicationModel.DynamicDependency.Projection.dll;Microsoft.Windows.ApplicationModel.Resources.Projection.dll;Microsoft.Windows.ApplicationModel.WindowsAppRuntime.Projection.dll;Microsoft.Windows.AppLifecycle.Projection.dll;Microsoft.Windows.SDK.NET.dll;Microsoft.Windows.System.Power.Projection.dll;Microsoft.WindowsAppRuntime.Bootstrap.Net.dll;Microsoft.WinUI.dll;PowerToys.ManagedCommon.dll;PowerToys.ManagedTelemetry.dll;PowerToys.MeasureToolCore.dll;PowerToys.MeasureToolUI.deps.json;PowerToys.MeasureToolUI.dll;PowerToys.MeasureToolUI.exe;PowerToys.MeasureToolUI.runtimeconfig.json;resources.pri;System.CodeDom.dll;System.Management.dll;System.Text.Json.dll;WinRT.Runtime.dll;WinUIEx.dll;PowerToys.GPOWrapper.dll;WindowsBase.dll?>
<?define MeasureToolMicrosoftUIXamlAssetsInstallFiles=NoiseAsset_256x256_PNG.png?>

<Fragment>
Expand Down
Expand Up @@ -8,32 +8,46 @@
using System.IO;
using System.IO.Abstractions;
using System.Reflection;
using System.Runtime.Serialization;
using interop;

namespace FancyZonesEditor.Logs
namespace ManagedCommon
{
public static class Logger
{
private static readonly IFileSystem _fileSystem = new FileSystem();
private static readonly Assembly Assembly = Assembly.GetExecutingAssembly();
public static readonly string Version = FileVersionInfo.GetVersionInfo(Assembly.Location).ProductVersion;
private static readonly string ApplicationLogPath = Path.Combine(Constants.AppDataPath(), "FancyZones\\Editor\\Logs\\", Version);
private static readonly string Version = FileVersionInfo.GetVersionInfo(Assembly.Location).ProductVersion;

private static readonly string Error = "Error";
private static readonly string Warning = "Warning";
private static readonly string Info = "Info";
private static readonly string Debug = "Debug";
private static readonly string TraceFlag = "Trace";

static Logger()
/// <summary>
/// Initializes the logger and sets the path for logging.
/// </summary>
/// <example>InitializeLogger("\\FancyZones\\Editor\\Logs")</example>
/// <param name="applicationLogPath">The path to the log files folder.</param>
/// <param name="isLocalLow">If the process using Logger is a low-privilege process.</param>
public static void InitializeLogger(string applicationLogPath, bool isLocalLow = false)
{
if (!_fileSystem.Directory.Exists(ApplicationLogPath))
if (isLocalLow)
{
_fileSystem.Directory.CreateDirectory(ApplicationLogPath);
applicationLogPath = Environment.GetEnvironmentVariable("userprofile") + "\\appdata\\LocalLow\\Microsoft\\PowerToys" + applicationLogPath + "\\" + Version;
}
else
{
applicationLogPath = Constants.AppDataPath() + applicationLogPath + "\\" + Version;
}

if (!_fileSystem.Directory.Exists(applicationLogPath))
{
_fileSystem.Directory.CreateDirectory(applicationLogPath);
}

// Using InvariantCulture since this is used for a log file name
var logFilePath = _fileSystem.Path.Combine(ApplicationLogPath, "Log_" + DateTime.Now.ToString(@"yyyy-MM-dd", CultureInfo.InvariantCulture) + ".txt");
var logFilePath = _fileSystem.Path.Combine(applicationLogPath, "Log_" + DateTime.Now.ToString(@"yyyy-MM-dd", CultureInfo.InvariantCulture) + ".txt");

Trace.Listeners.Add(new TextWriterTraceListener(logFilePath));

Expand Down Expand Up @@ -91,7 +105,7 @@ private static void Log(string message, string type)

private static string GetCallerInfo()
{
StackTrace stackTrace = new StackTrace();
StackTrace stackTrace = new();

var methodName = stackTrace.GetFrame(3)?.GetMethod();
var className = methodName?.DeclaringType.Name;
Expand Down
2 changes: 2 additions & 0 deletions src/common/ManagedCommon/ManagedCommon.csproj
Expand Up @@ -13,10 +13,12 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="System.IO.Abstractions" />
<PackageReference Include="System.Management" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\interop\PowerToys.Interop.vcxproj" />
<ProjectReference Include="..\ManagedTelemetry\Telemetry\ManagedTelemetry.csproj" />
</ItemGroup>

Expand Down
3 changes: 2 additions & 1 deletion src/modules/FileLocksmith/FileLocksmithUI/App.xaml.cs
Expand Up @@ -4,7 +4,6 @@

using System;
using System.Linq;
using FileLocksmithUI.Helpers;
using ManagedCommon;
using Microsoft.UI.Dispatching;
using Microsoft.UI.Xaml;
Expand All @@ -23,6 +22,8 @@ public partial class App : Application
/// </summary>
public App()
{
Logger.InitializeLogger("\\File Locksmith\\FileLocksmithUI\\Logs");

this.InitializeComponent();
}

Expand Down
76 changes: 0 additions & 76 deletions src/modules/FileLocksmith/FileLocksmithUI/Helpers/Logger.cs

This file was deleted.

Expand Up @@ -12,7 +12,7 @@
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using FileLocksmith.Interop;
using global::FileLocksmithUI.Helpers;
using ManagedCommon;

namespace PowerToys.FileLocksmithUI.ViewModels
{
Expand Down
1 change: 1 addition & 0 deletions src/modules/Hosts/Hosts/Helpers/HostsService.cs
Expand Up @@ -15,6 +15,7 @@
using System.Threading.Tasks;
using Hosts.Models;
using Hosts.Settings;
using ManagedCommon;
using Microsoft.Win32;
using Settings.UI.Library.Enumerations;

Expand Down
80 changes: 0 additions & 80 deletions src/modules/Hosts/Hosts/Helpers/Logger.cs

This file was deleted.

4 changes: 3 additions & 1 deletion src/modules/Hosts/Hosts/Program.cs
Expand Up @@ -4,7 +4,7 @@

using System;
using System.Threading;
using Hosts.Helpers;
using ManagedCommon;
using Microsoft.UI.Dispatching;
using Microsoft.Windows.AppLifecycle;

Expand All @@ -15,6 +15,8 @@ public static class Program
[STAThread]
public static void Main(string[] args)
{
Logger.InitializeLogger("\\Hosts\\Logs");

WinRT.ComWrappersSupport.InitializeComWrappers();

if (PowerToys.GPOWrapper.GPOWrapper.GetConfiguredHostsFileEditorEnabledValue() == PowerToys.GPOWrapper.GpoRuleConfigured.Disabled)
Expand Down
1 change: 1 addition & 0 deletions src/modules/Hosts/Hosts/Settings/UserSettings.cs
Expand Up @@ -5,6 +5,7 @@
using System;
using System.IO.Abstractions;
using System.Threading;
using ManagedCommon;
using Microsoft.PowerToys.Settings.UI.Library;
using Microsoft.PowerToys.Settings.UI.Library.Utilities;
using Settings.UI.Library.Enumerations;
Expand Down
1 change: 1 addition & 0 deletions src/modules/Hosts/Hosts/ViewModels/MainViewModel.cs
Expand Up @@ -17,6 +17,7 @@
using Hosts.Helpers;
using Hosts.Models;
using Hosts.Settings;
using ManagedCommon;
using Microsoft.UI.Dispatching;

namespace Hosts.ViewModels
Expand Down

0 comments on commit 5da8809

Please sign in to comment.