Runner logging (#8068)

This commit is contained in:
Mykhailo Pylyp 2020-11-18 12:15:14 +02:00 committed by GitHub
parent 60a5c3f946
commit 613d1fdf2a
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
24 changed files with 464 additions and 7 deletions

View file

@ -233,6 +233,7 @@ cdpx
cdpxwin
cend
CENTERALIGN
cerr
cfg
Cfg
changecursor

View file

@ -271,6 +271,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "UnitTest-ColorPickerUI", "s
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "logging", "src\logging\logging.vcxproj", "{7E1E3F13-2BD6-3F75-A6A7-873A2B55C60F}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "logger", "src\common\logger\logger.vcxproj", "{D9B8FC84-322A-4F9F-BBB9-20915C47DDFD}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x64 = Debug|x64
@ -549,6 +551,10 @@ Global
{7E1E3F13-2BD6-3F75-A6A7-873A2B55C60F}.Debug|x64.Build.0 = Debug|x64
{7E1E3F13-2BD6-3F75-A6A7-873A2B55C60F}.Release|x64.ActiveCfg = Release|x64
{7E1E3F13-2BD6-3F75-A6A7-873A2B55C60F}.Release|x64.Build.0 = Release|x64
{D9B8FC84-322A-4F9F-BBB9-20915C47DDFD}.Debug|x64.ActiveCfg = Debug|x64
{D9B8FC84-322A-4F9F-BBB9-20915C47DDFD}.Debug|x64.Build.0 = Debug|x64
{D9B8FC84-322A-4F9F-BBB9-20915C47DDFD}.Release|x64.ActiveCfg = Release|x64
{D9B8FC84-322A-4F9F-BBB9-20915C47DDFD}.Release|x64.Build.0 = Release|x64
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
@ -628,6 +634,7 @@ Global
{4FA206A5-F69F-4193-BF8F-F6EEB496734C} = {4AFC9975-2456-4C70-94A4-84073C1CED93}
{090CD7B7-3B0C-4D1D-BC98-83EB5D799BC1} = {1D78B84B-CA39-406C-98F4-71F7EC266CC0}
{7E1E3F13-2BD6-3F75-A6A7-873A2B55C60F} = {1AFB6476-670D-4E80-A464-657E01DFF482}
{D9B8FC84-322A-4F9F-BBB9-20915C47DDFD} = {1AFB6476-670D-4E80-A464-657E01DFF482}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {C3A2F9D1-7930-4EF4-A6FC-7EE0A99821D0}

2
deps/spdlog.props vendored
View file

@ -3,7 +3,7 @@
<ItemDefinitionGroup>
<ClCompile>
<AdditionalIncludeDirectories>$(MSBuildThisFileDirectory)spdlog\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>SPDLOG_WCHAR_TO_UTF8_SUPPORT;SPDLOG_COMPILED_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<PreprocessorDefinitions>SPDLOG_WCHAR_TO_UTF8_SUPPORT;SPDLOG_COMPILED_LIB;SPDLOG_WCHAR_FILENAMES;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
</ItemDefinitionGroup>
</Project>

View file

@ -18,6 +18,7 @@ auto Strings = create_notifications_strings();
#define STR_HELPER(x) #x
#define STR(x) STR_HELPER(x)
namespace // Strings in this namespace should not be localized
{
const wchar_t APPLICATION_ID[] = L"PowerToysInstaller";
@ -61,7 +62,7 @@ void setup_log(fs::path directory, const spdlog::level::level_enum severity)
std::shared_ptr<spdlog::logger> logger;
if (severity != spdlog::level::off)
{
logger = spdlog::basic_logger_mt("file", (directory / LOG_FILENAME).string());
logger = spdlog::basic_logger_mt("file", (directory / LOG_FILENAME).wstring());
std::error_code _;
const DWORD msiSev = severity == spdlog::level::debug ? INSTALLLOGMODE_VERBOSE : INSTALLLOGMODE_ERROR;

View file

@ -0,0 +1,3 @@
#pragma once
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers

View file

@ -0,0 +1,64 @@
// logger.cpp : Defines the functions for the static library.
//
#include "pch.h"
#include "framework.h"
#include "logger.h"
#include "logger_settings.h"
#include <map>
#include <spdlog/sinks/daily_file_sink.h>
#include <spdlog\sinks\stdout_color_sinks-inl.h>
#include <iostream>
using namespace std;
using namespace spdlog;
map<wstring, spdlog::level::level_enum> logLevelMapping = {
{ L"trace", level::trace },
{ L"debug", level::debug },
{ L"info", level::info },
{ L"warn", level::warn },
{ L"err", level::err },
{ L"critical", level::critical },
{ L"off", level::off },
};
level::level_enum getLogLevel(std::wstring_view logSettingsPath)
{
auto logLevel = get_log_settings(logSettingsPath).logLevel;
level::level_enum result = logLevelMapping[LogSettings::defaultLogLevel];
if (logLevelMapping.find(logLevel) != logLevelMapping.end())
{
result = logLevelMapping[logLevel];
}
return result;
}
Logger::Logger()
{
}
Logger::Logger(std::string loggerName, std::wstring logFilePath, std::wstring_view logSettingsPath)
{
auto logLevel = getLogLevel(logSettingsPath);
try
{
auto sink = make_shared<sinks::daily_file_sink_mt>(logFilePath, 0, 0, false, 5);
this->logger = make_shared<spdlog::logger>(loggerName, sink);
}
catch (...)
{
cerr << "Can not create file logger. Create stdout logger instead" << endl;
this->logger = spdlog::stdout_color_mt("some_unique_name");
}
this->logger->set_level(logLevel);
this->logger->set_pattern("[%Y-%m-%d %H:%M:%S.%f] [p-%P] [t-%t] [%l] %v");
spdlog::register_logger(this->logger);
spdlog::flush_every(std::chrono::seconds(3));
}
Logger::~Logger()
{
this->logger.reset();
}

View file

@ -0,0 +1,50 @@
#pragma once
#include <spdlog/spdlog.h>
class Logger
{
private:
std::shared_ptr<spdlog::logger> logger;
public:
Logger();
Logger(std::string loggerName, std::wstring logFilePath, std::wstring_view logSettingsPath);
template<typename FormatString, typename... Args>
void trace(const FormatString& fmt, const Args&... args)
{
this->logger->trace(fmt, args...);
}
template<typename FormatString, typename... Args>
void debug(const FormatString& fmt, const Args&... args)
{
this->logger->debug(fmt, args...);
}
template<typename FormatString, typename... Args>
void info(const FormatString& fmt, const Args&... args)
{
this->logger->info(fmt, args...);
}
template<typename FormatString, typename... Args>
void warn(const FormatString& fmt, const Args&... args)
{
this->logger->warn(fmt, args...);
}
template<typename FormatString, typename... Args>
void error(const FormatString& fmt, const Args&... args)
{
this->logger->error(fmt, args...);
}
template<typename FormatString, typename... Args>
void critical(const FormatString& fmt, const Args&... args)
{
this->logger->critical(fmt, args...);
}
~Logger();
};

View file

@ -0,0 +1,123 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="..\..\..\packages\Microsoft.Windows.CppWinRT.2.0.200729.8\build\native\Microsoft.Windows.CppWinRT.props" Condition="Exists('..\..\..\packages\Microsoft.Windows.CppWinRT.2.0.200729.8\build\native\Microsoft.Windows.CppWinRT.props')" />
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<VCProjectVersion>16.0</VCProjectVersion>
<Keyword>Win32Proj</Keyword>
<ProjectGuid>{d9b8fc84-322a-4f9f-bbb9-20915c47ddfd}</ProjectGuid>
<RootNamespace>logger</RootNamespace>
<WindowsTargetPlatformVersion>10.0.17134.0</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<Import Project="..\..\..\deps\spdlog.props" />
<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" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>_DEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<PrecompiledHeader>Use</PrecompiledHeader>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
<TreatWarningAsError>true</TreatWarningAsError>
</ClCompile>
<Link>
<SubSystem>
</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>NDEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<PrecompiledHeader>Use</PrecompiledHeader>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<TreatWarningAsError>true</TreatWarningAsError>
</ClCompile>
<Link>
<SubSystem>
</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClInclude Include="framework.h" />
<ClInclude Include="logger.h" />
<ClInclude Include="logger_settings.h" />
<ClInclude Include="pch.h" />
</ItemGroup>
<ItemGroup>
<ClCompile Include="logger.cpp" />
<ClCompile Include="logger_settings.cpp" />
<ClCompile Include="pch.cpp">
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">Create</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|x64'">Create</PrecompiledHeader>
</ClCompile>
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\logging\logging.vcxproj">
<Project>{7e1e3f13-2bd6-3f75-a6a7-873a2b55c60f}</Project>
</ProjectReference>
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<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')" />
</ImportGroup>
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('..\..\..\packages\Microsoft.Windows.CppWinRT.2.0.200729.8\build\native\Microsoft.Windows.CppWinRT.props')" Text="$([System.String]::Format('$(ErrorText)', '..\..\..\packages\Microsoft.Windows.CppWinRT.2.0.200729.8\build\native\Microsoft.Windows.CppWinRT.props'))" />
<Error Condition="!Exists('..\..\..\packages\Microsoft.Windows.CppWinRT.2.0.200729.8\build\native\Microsoft.Windows.CppWinRT.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\..\..\packages\Microsoft.Windows.CppWinRT.2.0.200729.8\build\native\Microsoft.Windows.CppWinRT.targets'))" />
</Target>
</Project>

View file

@ -0,0 +1,45 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Source Files">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="Header Files">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd</Extensions>
</Filter>
<Filter Include="Resource Files">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<ClInclude Include="framework.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="pch.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="logger.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="logger_settings.h">
<Filter>Header Files</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<ClCompile Include="logger.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="pch.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="logger_settings.cpp">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,83 @@
#include "pch.h"
#include "logger_settings.h"
#include <fstream>
#include <Windows.h>
#include <winrt/Windows.Data.Json.h>
#include <iostream>
using namespace winrt::Windows::Data::Json;
LogSettings::LogSettings()
{
this->logLevel = LogSettings::defaultLogLevel;
}
std::optional<JsonObject> from_file(std::wstring_view file_name)
{
try
{
std::ifstream file(file_name.data(), std::ios::binary);
if (file.is_open())
{
using isbi = std::istreambuf_iterator<char>;
std::string obj_str{ isbi{ file }, isbi{} };
return JsonValue::Parse(winrt::to_hstring(obj_str)).GetObjectW();
}
return std::nullopt;
}
catch (...)
{
return std::nullopt;
}
}
void to_file(std::wstring_view file_name, const JsonObject& obj)
{
std::wstring obj_str{ obj.Stringify().c_str() };
try
{
std::ofstream{ file_name.data(), std::ios::binary } << winrt::to_string(obj_str);
}
catch (...)
{
std::cerr << "Can not create log config file" << std::endl;
}
}
JsonObject to_json(LogSettings settings)
{
JsonObject result;
result.SetNamedValue(LogSettings::logLevelOption, JsonValue::CreateStringValue(settings.logLevel));
return result;
}
LogSettings to_settings(JsonObject jobject)
{
LogSettings result;
try
{
result.logLevel = jobject.GetNamedString(LogSettings::logLevelOption);
}
catch (...)
{
std::cerr << "Can not read log level from config file" << std::endl;
result.logLevel = LogSettings::defaultLogLevel;
}
return result;
}
// Get log settings from file. File with default options is created if it does not exist
LogSettings get_log_settings(std::wstring_view file_name)
{
auto jobject = from_file(file_name);
if (!jobject.has_value())
{
auto json = to_json(LogSettings());
to_file(file_name, json);
return to_settings(json);
}
return to_settings(jobject.value());
}

View file

@ -0,0 +1,15 @@
#pragma once
#include <string>
struct LogSettings
{
// The following strings are not localizable
inline const static std::wstring defaultLogLevel = L"warn";
inline const static std::wstring logLevelOption = L"logLevel";
std::wstring logLevel;
LogSettings();
};
// Get log settings from file. File with default options is created if it does not exist
LogSettings get_log_settings(std::wstring_view file_name);

View file

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Microsoft.Windows.CppWinRT" version="2.0.200729.8" targetFramework="native" />
</packages>

View file

@ -0,0 +1,5 @@
// pch.cpp: source file corresponding to the pre-compiled header
#include "pch.h"
// When you are using pre-compiled headers, this source file is necessary for compilation to succeed.

13
src/common/logger/pch.h Normal file
View file

@ -0,0 +1,13 @@
// pch.h: This is a precompiled header file.
// Files listed below are compiled only once, improving build performance for future builds.
// This also affects IntelliSense performance, including code completion and many code browsing features.
// However, files listed here are ALL re-compiled if any one of them is updated between builds.
// Do not add files here that you will be updating frequently as this negates the performance advantage.
#ifndef PCH_H
#define PCH_H
// add headers that you want to pre-compile here
#include "framework.h"
#endif //PCH_H

View file

@ -6,6 +6,7 @@
namespace PTSettingsHelper
{
constexpr inline const wchar_t* settings_filename = L"\\settings.json";
constexpr inline const wchar_t* log_settings_filename = L"log_settings.json";
std::wstring get_root_save_folder_location()
{
@ -71,4 +72,11 @@ namespace PTSettingsHelper
auto saved_settings = json::from_file(save_file_location);
return saved_settings.has_value() ? std::move(*saved_settings) : json::JsonObject{};
}
std::wstring get_log_settings_file_location()
{
std::filesystem::path result(PTSettingsHelper::get_root_save_folder_location());
result = result.append(log_settings_filename);
return result.wstring();
}
}

View file

@ -13,5 +13,5 @@ namespace PTSettingsHelper
json::JsonObject load_module_settings(std::wstring_view powertoy_name);
void save_general_settings(const json::JsonObject& settings);
json::JsonObject load_general_settings();
std::wstring get_log_settings_file_location();
}

View file

@ -66,7 +66,7 @@
<RuntimeTypeInfo>true</RuntimeTypeInfo>
<UseFullPaths>false</UseFullPaths>
<WarningLevel>Level4</WarningLevel>
<PreprocessorDefinitions>WIN32;_WINDOWS;SPDLOG_COMPILED_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<PreprocessorDefinitions>WIN32;_WINDOWS;SPDLOG_COMPILED_LIB;SPDLOG_WCHAR_FILENAMES;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ObjectFileName>$(IntDir)</ObjectFileName>
<MultiProcessorCompilation>true</MultiProcessorCompilation>
<FunctionLevelLinking>true</FunctionLevelLinking>

View file

@ -120,6 +120,9 @@
<ProjectReference Include="..\..\..\common\common.vcxproj">
<Project>{74485049-c722-400f-abe5-86ac52d929b3}</Project>
</ProjectReference>
<ProjectReference Include="..\..\..\common\logger\logger.vcxproj">
<Project>{d9b8fc84-322a-4f9f-bbb9-20915c47ddfd}</Project>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<ResourceCompile Include="Generated Files\Microsoft.Launcher.rc" />
@ -132,6 +135,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')" />
</ImportGroup>

View file

@ -11,6 +11,7 @@
<ClInclude Include="Generated Files\resource.h">
<Filter>Generated Files</Filter>
</ClInclude>
<ClInclude Include="LauncherConstants.h" />
</ItemGroup>
<ItemGroup>
<Filter Include="Resource Files">

View file

@ -7,6 +7,9 @@
#include "Generated Files/resource.h"
#include <common/os-detect.h>
#include <launcher\Microsoft.Launcher\LauncherConstants.h>
#include <common/logger/logger.h>
#include <common\settings_helpers.h>
#include <filesystem>
extern "C" IMAGE_DOS_HEADER __ImageBase;
@ -75,12 +78,18 @@ private:
// Handle to event used to invoke the Runner
HANDLE m_hEvent;
std::shared_ptr<Logger> logger;
public:
// Constructor
Microsoft_Launcher()
{
app_name = GET_RESOURCE_STRING(IDS_LAUNCHER_NAME);
app_key = LauncherConstants::ModuleKey;
std::filesystem::path logFilePath(PTSettingsHelper::get_module_save_folder_location(this->app_key));
logFilePath.append("logging.txt");
logger = std::make_shared<Logger>("launcher", logFilePath.wstring(), PTSettingsHelper::get_log_settings_file_location());
logger->info("Launcher object is constructing");
init_settings();
SECURITY_ATTRIBUTES sa;
@ -92,6 +101,8 @@ public:
~Microsoft_Launcher()
{
logger->info("Launcher object is destroying");
logger.reset();
if (m_enabled)
{
terminateProcess();
@ -172,6 +183,7 @@ public:
// Enable the powertoy
virtual void enable()
{
this->logger->info("Launcher is enabling");
ResetEvent(m_hEvent);
// Start PowerLauncher.exe only if the OS is 19H1 or higher
if (UseNewSettings())
@ -243,6 +255,7 @@ public:
// Disable the powertoy
virtual void disable()
{
this->logger->info("Launcher is disabling");
if (m_enabled)
{
ResetEvent(m_hEvent);
@ -311,7 +324,12 @@ public:
void terminateProcess()
{
DWORD processID = GetProcessId(m_hProcess);
TerminateProcess(m_hProcess, 1);
if (TerminateProcess(m_hProcess, 1) == 0)
{
auto err = get_last_error_message(GetLastError());
this->logger->error(L"Launcher process was not terminated. {}", err.has_value() ? err.value() : L"");
}
// Temporarily disable sending a message to close
/*
EnumWindows(&requestMainWindowClose, processID);

View file

@ -22,4 +22,4 @@ struct GeneralSettings
json::JsonObject load_general_settings();
GeneralSettings get_general_settings();
void apply_general_settings(const json::JsonObject& general_configs, bool save = true);
void start_initial_powertoys();
void start_initial_powertoys();

View file

@ -33,6 +33,8 @@
#if _DEBUG && _WIN64
#include "unhandled_exception_handler.h"
#endif
#include <common\settings_helpers.h>
#include <common/logger/logger.h>
extern "C" IMAGE_DOS_HEADER __ImageBase;
extern updating::notifications::strings Strings;
@ -43,6 +45,7 @@ namespace
const wchar_t POWER_TOYS_MODULE_LOAD_FAIL[] = L"Failed to load "; // Module name will be appended on this message and it is not localized.
}
std::shared_ptr<Logger> logger;
void chdir_current_executable()
{
// Change current directory to the path of the executable.
@ -73,6 +76,7 @@ void open_menu_from_another_instance()
int runner(bool isProcessElevated)
{
logger->info("Runner is starting. Elevated={}", isProcessElevated);
DPIAware::EnableDPIAwarenessForThisProcess();
#if _DEBUG && _WIN64
@ -290,6 +294,11 @@ int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine
{
return 0;
}
std::filesystem::path logFilePath(PTSettingsHelper::get_root_save_folder_location());
logFilePath = logFilePath.append(L"runner-logging.txt");
logger = std::make_shared<Logger>("runner", logFilePath.wstring(), PTSettingsHelper::get_log_settings_file_location());
int n_cmd_args = 0;
LPWSTR* cmd_arg_list = CommandLineToArgvW(GetCommandLineW(), &n_cmd_args);
switch (should_run_in_special_mode(n_cmd_args, cmd_arg_list))

View file

@ -238,6 +238,9 @@
<ProjectReference Include="..\common\common.vcxproj">
<Project>{74485049-c722-400f-abe5-86ac52d929b3}</Project>
</ProjectReference>
<ProjectReference Include="..\common\logger\logger.vcxproj">
<Project>{d9b8fc84-322a-4f9f-bbb9-20915c47ddfd}</Project>
</ProjectReference>
<ProjectReference Include="..\common\updating\updating.vcxproj">
<Project>{17da04df-e393-4397-9cf0-84dabe11032e}</Project>
</ProjectReference>
@ -249,6 +252,7 @@
<Manifest Include="PowerToys.exe.manifest" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<Import Project="..\..\deps\spdlog.props" />
<ImportGroup Label="ExtensionTargets">
<Import Project="..\..\packages\Microsoft.Windows.ImplementationLibrary.1.0.200902.2\build\native\Microsoft.Windows.ImplementationLibrary.targets" Condition="Exists('..\..\packages\Microsoft.Windows.ImplementationLibrary.1.0.200902.2\build\native\Microsoft.Windows.ImplementationLibrary.targets')" />
<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')" />

View file

@ -244,7 +244,6 @@ BOOL run_settings_non_elevated(LPCWSTR executable_path, LPWSTR executable_args,
return process_created;
}
DWORD g_settings_process_id = 0;
void run_settings_window()