Add logging for PowerRename (#14249)

* Add logging for PowerRename

Move call tracer to common/utils/logger
Add logging to both PowerRename dll and PowerRenameUIHost
Add PowerRename to BugReportTool event viewer collection

* Log more errors and exceptions
This commit is contained in:
Stefan Markovic 2021-11-08 13:02:56 +01:00 committed by GitHub
parent c9dca6802e
commit 079a3b49de
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
16 changed files with 177 additions and 53 deletions

View File

@ -1,5 +1,7 @@
#include "pch.h"
#include "CallTracer.h"
#include "call_tracer.h"
#include <map>
#include <thread>
namespace

View File

@ -1,6 +1,8 @@
#pragma once
#include "common/logger/logger.h"
#include <string>
#include "logger.h"
#define _TRACER_ CallTracer callTracer(__FUNCTION__)

View File

@ -31,12 +31,14 @@
</ClCompile>
</ItemDefinitionGroup>
<ItemGroup>
<ClInclude Include="call_tracer.h" />
<ClInclude Include="framework.h" />
<ClInclude Include="logger.h" />
<ClInclude Include="logger_settings.h" />
<ClInclude Include="pch.h" />
</ItemGroup>
<ItemGroup>
<ClCompile Include="call_tracer.cpp" />
<ClCompile Include="logger.cpp" />
<ClCompile Include="logger_settings.cpp" />
<ClCompile Include="pch.cpp">

View File

@ -27,6 +27,9 @@
<ClInclude Include="logger_settings.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="call_tracer.h">
<Filter>Header Files</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<ClCompile Include="logger.cpp">
@ -38,6 +41,9 @@
<ClCompile Include="logger_settings.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="call_tracer.cpp">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />

View File

@ -24,6 +24,7 @@ struct LogSettings
inline const static std::string keyboardManagerLoggerName = "keyboard-manager";
inline const static std::wstring keyboardManagerLogPath = L"Logs\\keyboard-manager-log.txt";
inline const static std::string findMyMouseLoggerName = "find-my-mouse";
inline const static std::string powerRenameLoggerName = "powerrename";
inline const static int retention = 30;
std::wstring logLevel;
LogSettings();

View File

@ -4,6 +4,7 @@
#include <common/display/dpi_aware.h>
#include <common/interop/shared_constants.h>
#include <common/logger/logger.h>
#include <common/logger/call_tracer.h>
#include <common/utils/EventWaiter.h>
#include <common/utils/resources.h>
#include <common/utils/winapi_error.h>
@ -25,7 +26,6 @@
#include "VirtualDesktop.h"
#include "MonitorWorkAreaHandler.h"
#include "util.h"
#include "CallTracer.h"
#include <FancyZonesLib/SecondaryMouseButtonsHook.h>
#include <winrt/Windows.UI.ViewManagement.h>

View File

@ -4,10 +4,10 @@
#include "JsonHelpers.h"
#include "ZoneSet.h"
#include "Settings.h"
#include "CallTracer.h"
#include "GuidUtils.h"
#include <common/Display/dpi_aware.h>
#include <common/logger/call_tracer.h>
#include <common/utils/json.h>
#include <FancyZonesLib/util.h>
#include <FancyZonesLib/FancyZonesWindowProperties.h>

View File

@ -37,7 +37,6 @@
</ClCompile>
</ItemDefinitionGroup>
<ItemGroup>
<ClInclude Include="CallTracer.h" />
<ClInclude Include="FancyZones.h" />
<ClInclude Include="FancyZonesDataTypes.h" />
<ClInclude Include="FancyZonesWinHookEventIDs.h" />
@ -65,7 +64,6 @@
<ClInclude Include="ZoneWindowDrawing.h" />
</ItemGroup>
<ItemGroup>
<ClCompile Include="CallTracer.cpp" />
<ClCompile Include="FancyZones.cpp" />
<ClCompile Include="FancyZonesDataTypes.cpp" />
<ClCompile Include="FancyZonesWinHookEventIDs.cpp" />

View File

@ -78,9 +78,6 @@
<ClInclude Include="ZoneWindowDrawing.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="CallTracer.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="MonitorUtils.h">
<Filter>Header Files</Filter>
</ClInclude>
@ -149,9 +146,6 @@
<ClCompile Include="OnThreadExecutor.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="CallTracer.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="MonitorUtils.cpp">
<Filter>Source Files</Filter>
</ClCompile>

View File

@ -1,7 +1,8 @@
#include "pch.h"
#include <common/logger/call_tracer.h>
#include "on_thread_executor.h"
#include "CallTracer.h"
OnThreadExecutor::OnThreadExecutor() :
_shutdown_request{ false }, _worker_thread{ [this] { worker_thread(); } }

View File

@ -1,6 +1,7 @@
#include "pch.h"
#include "WorkArea.h"
#include <common/logger/call_tracer.h>
#include <common/logger/logger.h>
#include "FancyZonesData.h"
@ -10,7 +11,6 @@
#include "util.h"
#include "on_thread_executor.h"
#include "Settings.h"
#include "CallTracer.h"
#include <ShellScalingApi.h>
#include <mutex>

View File

@ -1,12 +1,12 @@
#include "pch.h"
#include "ZoneWindowDrawing.h"
#include "CallTracer.h"
#include <algorithm>
#include <map>
#include <string>
#include <vector>
#include <common/logger/call_tracer.h>
#include <common/logger/logger.h>
namespace

View File

@ -5,13 +5,22 @@
#include "PowerRenameUIHost.h"
#include <settings.h>
#include <trace.h>
#include <exception>
#include <string>
#include <sstream>
#include <vector>
#include <common/logger/call_tracer.h>
#include <common/logger/logger.h>
#include <common/utils/logger_helper.h>
#include <common/utils/process_path.h>
#define MAX_LOADSTRING 100
// Non-localizable
const std::wstring moduleName = L"PowerRename";
const std::wstring internalPath = L"";
const wchar_t c_WindowClass[] = L"PowerRename";
HINSTANCE g_hostHInst;
@ -19,6 +28,8 @@ int AppWindow::Show(HINSTANCE hInstance, std::vector<std::wstring> files)
{
auto window = AppWindow(hInstance, files);
window.CreateAndShowWindow();
Logger::debug(L"PowerRename UI created. Starting the message loop.");
return window.MessageLoop(window.m_accelerators.get());
}
@ -40,38 +51,54 @@ LRESULT AppWindow::MessageHandler(UINT message, WPARAM wParam, LPARAM lParam) no
AppWindow::AppWindow(HINSTANCE hInstance, std::vector<std::wstring> files) noexcept :
m_instance{ hInstance }, m_managerEvents{ this }
{
HRESULT hr = CPowerRenameManager::s_CreateInstance(&m_prManager);
// Create the factory for our items
CComPtr<IPowerRenameItemFactory> prItemFactory;
hr = CPowerRenameItem::s_CreateInstance(nullptr, IID_PPV_ARGS(&prItemFactory));
hr = m_prManager->PutRenameItemFactory(prItemFactory);
hr = m_prManager->Advise(&m_managerEvents, &m_cookie);
if (SUCCEEDED(hr))
if (SUCCEEDED(CPowerRenameManager::s_CreateInstance(&m_prManager)))
{
CComPtr<IShellItemArray> shellItemArray;
// To test PowerRenameUIHost uncomment this line and update the path to
// your local (absolute or relative) path which you want to see in PowerRename
// files.push_back(L"path");
if (!files.empty())
// Create the factory for our items
CComPtr<IPowerRenameItemFactory> prItemFactory;
if (SUCCEEDED(CPowerRenameItem::s_CreateInstance(nullptr, IID_PPV_ARGS(&prItemFactory))))
{
hr = CreateShellItemArrayFromPaths(files, &shellItemArray);
if (SUCCEEDED(hr))
if(SUCCEEDED(m_prManager->PutRenameItemFactory(prItemFactory)))
{
CComPtr<IEnumShellItems> enumShellItems;
hr = shellItemArray->EnumItems(&enumShellItems);
if (SUCCEEDED(hr))
if (SUCCEEDED(m_prManager->Advise(&m_managerEvents, &m_cookie)))
{
EnumerateShellItems(enumShellItems);
CComPtr<IShellItemArray> shellItemArray;
// To test PowerRenameUIHost uncomment this line and update the path to
// your local (absolute or relative) path which you want to see in PowerRename
//files.push_back(L"<path>");
if (!files.empty())
{
if (SUCCEEDED(CreateShellItemArrayFromPaths(files, &shellItemArray)))
{
CComPtr<IEnumShellItems> enumShellItems;
if (SUCCEEDED(shellItemArray->EnumItems(&enumShellItems)))
{
EnumerateShellItems(enumShellItems);
}
}
}
else
{
Logger::warn(L"No items selected to be renamed.");
}
}
}
}
else
{
Logger::error(L"Error creating PowerRenameItemFactory");
}
}
else
{
Logger::error(L"Error creating PowerRenameManager");
}
}
void AppWindow::CreateAndShowWindow()
{
_TRACER_;
m_accelerators.reset(LoadAcceleratorsW(m_instance, MAKEINTRESOURCE(IDC_POWERRENAMEUIHOST)));
WNDCLASSEXW wcex = { sizeof(wcex) };
@ -99,12 +126,21 @@ void AppWindow::CreateAndShowWindow()
bool AppWindow::OnCreate(HWND, LPCREATESTRUCT) noexcept
{
_TRACER_;
m_mainUserControl = winrt::PowerRenameUILib::MainWindow();
m_xamlIsland = CreateDesktopWindowsXamlSource(WS_TABSTOP, m_mainUserControl);
PopulateExplorerItems();
SetHandlers();
ReadSettings();
try
{
PopulateExplorerItems();
SetHandlers();
ReadSettings();
}
catch (std::exception e)
{
Logger::error("Exception thrown during explorer items population: {}", std::string{ e.what() });
}
m_mainUserControl.UIUpdatesItem().ButtonRenameEnabled(false);
InitAutoComplete();
@ -143,11 +179,15 @@ void AppWindow::OnCommand(HWND, int id, HWND hwndControl, UINT codeNotify) noexc
void AppWindow::OnDestroy(HWND hwnd) noexcept
{
_TRACER_;
base_type::OnDestroy(hwnd);
}
void AppWindow::OnResize(HWND, UINT state, int cx, int cy) noexcept
{
_TRACER_;
SetWindowPos(m_xamlIsland, NULL, 0, 0, cx, cy, SWP_SHOWWINDOW);
}
@ -155,6 +195,8 @@ HRESULT AppWindow::CreateShellItemArrayFromPaths(
std::vector<std::wstring> files,
IShellItemArray** shellItemArray)
{
_TRACER_;
*shellItemArray = nullptr;
PIDLIST_ABSOLUTE* itemList = nullptr;
itemList = new (std::nothrow) PIDLIST_ABSOLUTE[files.size()];
@ -174,14 +216,21 @@ HRESULT AppWindow::CreateShellItemArrayFromPaths(
if (SUCCEEDED(hr) && itemsCnt > 0)
{
hr = SHCreateShellItemArrayFromIDLists(itemsCnt, const_cast<LPCITEMIDLIST*>(itemList), shellItemArray);
for (UINT i = 0; i < itemsCnt; i++)
if (SUCCEEDED(hr))
{
CoTaskMemFree(itemList[i]);
for (UINT i = 0; i < itemsCnt; i++)
{
CoTaskMemFree(itemList[i]);
}
}
else
{
Logger::error(L"Creating ShellItemArray from path list failed.");
}
}
else
{
Logger::error(L"Parsing path list display names failed.");
hr = E_FAIL;
}
@ -191,8 +240,11 @@ HRESULT AppWindow::CreateShellItemArrayFromPaths(
void AppWindow::PopulateExplorerItems()
{
_TRACER_;
UINT count = 0;
m_prManager->GetVisibleItemCount(&count);
Logger::debug(L"Number of visible items: {}", count);
UINT currDepth = 0;
std::stack<UINT> parents{};
@ -245,6 +297,8 @@ void AppWindow::PopulateExplorerItems()
HRESULT AppWindow::InitAutoComplete()
{
_TRACER_;
HRESULT hr = S_OK;
if (CSettingsInstance().GetMRUEnabled())
{
@ -281,6 +335,8 @@ HRESULT AppWindow::InitAutoComplete()
HRESULT AppWindow::EnumerateShellItems(_In_ IEnumShellItems* enumShellItems)
{
_TRACER_;
HRESULT hr = S_OK;
// Enumerate the data object and populate the manager
if (m_prManager)
@ -303,6 +359,9 @@ HRESULT AppWindow::EnumerateShellItems(_In_ IEnumShellItems* enumShellItems)
void AppWindow::SearchReplaceChanged(bool forceRenaming)
{
_TRACER_;
Logger::debug(L"Forced renaming - {}", forceRenaming);
// Pass updated search and replace terms to the IPowerRenameRegEx handler
CComPtr<IPowerRenameRegEx> prRegEx;
if (m_prManager && SUCCEEDED(m_prManager->GetRenameRegEx(&prRegEx)))
@ -359,6 +418,8 @@ void AppWindow::ValidateFlags(PowerRenameFlags flag)
void AppWindow::UpdateFlag(PowerRenameFlags flag, UpdateFlagCommand command)
{
_TRACER_;
DWORD flags{};
m_prManager->GetFlags(&flags);
@ -371,6 +432,8 @@ void AppWindow::UpdateFlag(PowerRenameFlags flag, UpdateFlagCommand command)
flags &= ~flag;
}
Logger::debug(L"Flag {} " + std::wstring{ command == UpdateFlagCommand::Set ? L"set" : L"reset" }, flag);
// Ensure we update flags
if (m_prManager)
{
@ -380,6 +443,8 @@ void AppWindow::UpdateFlag(PowerRenameFlags flag, UpdateFlagCommand command)
void AppWindow::SetHandlers()
{
_TRACER_;
m_mainUserControl.UIUpdatesItem().PropertyChanged([&](winrt::Windows::Foundation::IInspectable const& sender, Data::PropertyChangedEventArgs const& e) {
std::wstring property{ e.PropertyName() };
if (property == L"ShowAll")
@ -538,14 +603,21 @@ void AppWindow::SetHandlers()
void AppWindow::ToggleItem(int32_t id, bool checked)
{
_TRACER_;
Logger::debug(L"Toggling item with id = {}", id);
CComPtr<IPowerRenameItem> spItem;
m_prManager->GetItemById(id, &spItem);
spItem->PutSelected(checked);
if (SUCCEEDED(m_prManager->GetItemById(id, &spItem)))
{
spItem->PutSelected(checked);
}
UpdateCounts();
}
void AppWindow::ToggleAll()
{
_TRACER_;
UINT itemCount = 0;
m_prManager->GetItemCount(&itemCount);
bool selected = m_mainUserControl.CheckBoxSelectAll().IsChecked().GetBoolean();
@ -562,12 +634,16 @@ void AppWindow::ToggleAll()
void AppWindow::SwitchView()
{
_TRACER_;
m_prManager->SwitchFilter(0);
PopulateExplorerItems();
}
void AppWindow::Rename(bool closeWindow)
{
_TRACER_;
if (m_prManager)
{
m_prManager->Rename(m_window, closeWindow);
@ -581,10 +657,15 @@ void AppWindow::Rename(bool closeWindow)
HRESULT AppWindow::ReadSettings()
{
_TRACER_;
bool persistState{ CSettingsInstance().GetPersistState() };
Logger::debug(L"ReadSettings with persistState = {}", persistState);
// Check if we should read flags from settings
// or the defaults from the manager.
DWORD flags = 0;
if (CSettingsInstance().GetPersistState())
if (persistState)
{
flags = CSettingsInstance().GetFlags();
@ -604,6 +685,8 @@ HRESULT AppWindow::ReadSettings()
HRESULT AppWindow::WriteSettings()
{
_TRACER_;
// Check if we should store our settings
if (CSettingsInstance().GetPersistState())
{
@ -835,6 +918,8 @@ HRESULT AppWindow::OnRegExCanceled(_In_ DWORD threadId)
HRESULT AppWindow::OnRegExCompleted(_In_ DWORD threadId)
{
_TRACER_;
if (m_flagValidationInProgress)
{
m_flagValidationInProgress = false;
@ -860,6 +945,9 @@ HRESULT AppWindow::OnRenameStarted()
HRESULT AppWindow::OnRenameCompleted(bool closeUIWindowAfterRenaming)
{
_TRACER_;
Logger::debug(L"Renaming completed. Close UI window - {}", closeUIWindowAfterRenaming);
if (closeUIWindowAfterRenaming)
{
// Close the window
@ -878,11 +966,17 @@ int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
_In_ LPWSTR lpCmdLine,
_In_ int nCmdShow)
{
LoggerHelpers::init_logger(moduleName, internalPath, LogSettings::powerRenameLoggerName);
#define BUFSIZE 4096 * 4
HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);
if (hStdin == INVALID_HANDLE_VALUE)
{
Logger::error(L"Invalid input handle.");
ExitProcess(1);
}
BOOL bSuccess;
WCHAR chBuf[BUFSIZE];
DWORD dwRead;
@ -909,10 +1003,19 @@ int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
break;
}
g_hostHInst = hInstance;
winrt::init_apartment(winrt::apartment_type::single_threaded);
Logger::debug(L"Starting PowerRename with {} files selected", files.size());
winrt::PowerRenameUILib::App app;
const auto result = AppWindow::Show(hInstance, files);
app.Close();
g_hostHInst = hInstance;
try
{
winrt::init_apartment(winrt::apartment_type::single_threaded);
winrt::PowerRenameUILib::App app;
const auto result = AppWindow::Show(hInstance, files);
app.Close();
}
catch (std::exception e)
{
Logger::error("Exception thrown during PowerRename UI initialization: {}", std::string{ e.what() });
}
}

View File

@ -38,8 +38,10 @@
<WindowsAppContainer>false</WindowsAppContainer>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings"></ImportGroup>
<ImportGroup Label="Shared"></ImportGroup>
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
<Import Project="..\..\..\..\Solution.props" />
@ -126,6 +128,7 @@
<Manifest Include="app.manifest" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<Import Project="..\..\..\..\deps\spdlog.props" />
<ImportGroup Label="ExtensionTargets">
<Import Project="..\..\..\..\packages\Microsoft.Toolkit.Win32.UI.SDK.6.1.2\build\Microsoft.Toolkit.Win32.UI.SDK.targets" Condition="Exists('..\..\..\..\packages\Microsoft.Toolkit.Win32.UI.SDK.6.1.2\build\Microsoft.Toolkit.Win32.UI.SDK.targets')" />
<Import Project="..\..\..\..\packages\Microsoft.Toolkit.Win32.UI.XamlApplication.6.1.3\build\native\Microsoft.Toolkit.Win32.UI.XamlApplication.targets" Condition="Exists('..\..\..\..\packages\Microsoft.Toolkit.Win32.UI.XamlApplication.6.1.3\build\native\Microsoft.Toolkit.Win32.UI.XamlApplication.targets')" />
@ -158,6 +161,9 @@
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\$(AppProjectName)\$(AppProjectName).vcxproj" />
<ProjectReference Include="..\..\..\common\logger\logger.vcxproj">
<Project>{d9b8fc84-322a-4f9f-bbb9-20915c47ddfd}</Project>
</ProjectReference>
<ProjectReference Include="..\lib\PowerRenameLib.vcxproj">
<Project>{51920f1f-c28c-4adf-8660-4238766796c2}</Project>
</ProjectReference>

View File

@ -54,6 +54,9 @@
<ProjectReference Include="..\..\..\common\Display\Display.vcxproj">
<Project>{caba8dfb-823b-4bf2-93ac-3f31984150d9}</Project>
</ProjectReference>
<ProjectReference Include="..\..\..\common\logger\logger.vcxproj">
<Project>{d9b8fc84-322a-4f9f-bbb9-20915c47ddfd}</Project>
</ProjectReference>
<ProjectReference Include="..\..\..\common\Themes\Themes.vcxproj">
<Project>{98537082-0fdb-40de-abd8-0dc5a4269bab}</Project>
</ProjectReference>
@ -65,6 +68,7 @@
<None Include="Resources.resx" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<Import Project="..\..\..\..\deps\spdlog.props" />
<ImportGroup Label="ExtensionTargets">
<Import Project="..\..\..\..\packages\Microsoft.Windows.CppWinRT.2.0.200729.8\build\native\Microsoft.Windows.CppWinRT.targets" Condition="Exists('..\..\..\..\packages\Microsoft.Windows.CppWinRT.2.0.200729.8\build\native\Microsoft.Windows.CppWinRT.targets')" />
<Import Project="..\..\..\..\packages\boost.1.72.0.0\build\boost.targets" Condition="Exists('..\..\..\..\packages\boost.1.72.0.0\build\boost.targets')" />

View File

@ -4,6 +4,8 @@
#include <settings.h>
#include <trace.h>
#include <common/SettingsAPI/settings_objects.h>
#include <common/logger/logger.h>
#include <common/utils/logger_helper.h>
#include <common/utils/resources.h>
#include "Generated Files/resource.h"
#include <atomic>
@ -174,6 +176,7 @@ public:
// Enable the powertoy
virtual void enable()
{
Logger::info(L"PowerRename enabled");
m_enabled = true;
save_settings();
}
@ -181,6 +184,7 @@ public:
// Disable the powertoy
virtual void disable()
{
Logger::info(L"PowerRename disabled");
m_enabled = false;
save_settings();
}
@ -261,9 +265,9 @@ public:
Trace::SettingsChanged();
}
catch (std::exception)
catch (std::exception e)
{
// Improper JSON.
Logger::error("Configuration parsing failed: {}", std::string{ e.what() });
}
}
@ -297,6 +301,7 @@ public:
init_settings();
app_name = GET_RESOURCE_STRING(IDS_POWERRENAME_APP_NAME);
app_key = PowerRenameConstants::ModuleKey;
LoggerHelpers::init_logger(app_key, L"ModuleInterface", LogSettings::powerRenameLoggerName);
}
~PowerRenameModule(){};