diff options
author | saturneric <[email protected]> | 2024-01-05 12:55:15 +0000 |
---|---|---|
committer | saturneric <[email protected]> | 2024-01-05 12:55:15 +0000 |
commit | 644aa4397b03dbef73f8bfedc13925b51cad836b (patch) | |
tree | 7788d1cd2f0687dd8e576b111d9990c580092e7a /src | |
parent | fix: slove some known issues (diff) | |
download | GpgFrontend-644aa4397b03dbef73f8bfedc13925b51cad836b.tar.gz GpgFrontend-644aa4397b03dbef73f8bfedc13925b51cad836b.zip |
feat: integrate logging api to core
Diffstat (limited to 'src')
104 files changed, 1217 insertions, 1146 deletions
diff --git a/src/GpgFrontendContext.h b/src/GpgFrontendContext.h index baa2c7a7..9bf591d4 100644 --- a/src/GpgFrontendContext.h +++ b/src/GpgFrontendContext.h @@ -28,8 +28,6 @@ #pragma once -#include "core/function/SecureMemoryAllocator.h" - namespace GpgFrontend { struct GpgFrontendContext; diff --git a/src/app.cpp b/src/app.cpp index f978ef8b..69262737 100644 --- a/src/app.cpp +++ b/src/app.cpp @@ -35,7 +35,7 @@ #include "ui/GpgFrontendUIInit.h" // main -#include "init.h" +#include "main.h" /** * \brief Store the jump buff and make it possible to recover from a crash. @@ -60,22 +60,22 @@ constexpr int kCrashCode = ~0; ///< auto StartApplication(const GFCxtWPtr& p_ctx) -> int { GFCxtSPtr ctx = p_ctx.lock(); if (ctx == nullptr) { - SPDLOG_ERROR("cannot get gpgfrontend context."); + GF_MAIN_LOG_ERROR("cannot get gpgfrontend context."); return -1; } if (!ctx->load_ui_env) { - SPDLOG_ERROR("the loading of gui application is forbidden."); + GF_MAIN_LOG_ERROR("the loading of gui application is forbidden."); return -1; } auto* app = ctx->GetGuiApp(); if (app == nullptr) { - SPDLOG_ERROR("cannot get qapplication from gpgfrontend context."); + GF_MAIN_LOG_ERROR("cannot get qapplication from gpgfrontend context."); return -1; } - SPDLOG_INFO("start running gui application"); + GF_MAIN_LOG_INFO("start running gui application"); /** * internationalisation. loop to restart main window @@ -97,7 +97,7 @@ auto StartApplication(const GFCxtWPtr& p_ctx) -> int { // finally create main window return_from_event_loop_code = GpgFrontend::UI::RunGpgFrontendUI(app); } else { - SPDLOG_ERROR("recover from a crash"); + GF_MAIN_LOG_ERROR("recover from a crash"); // when signal is caught, restart the main window auto* message_box = new QMessageBox( QMessageBox::Critical, _("A serious error has occurred"), @@ -110,7 +110,7 @@ auto StartApplication(const GFCxtWPtr& p_ctx) -> int { return_from_event_loop_code = kCrashCode; } - SPDLOG_DEBUG("try to destroy modules system and core"); + GF_MAIN_LOG_DEBUG("try to destroy modules system and core"); // first should shutdown the module system GpgFrontend::Module::ShutdownGpgFrontendModules(); @@ -118,23 +118,24 @@ auto StartApplication(const GFCxtWPtr& p_ctx) -> int { // then shutdown the core GpgFrontend::DestroyGpgFrontendCore(); - SPDLOG_DEBUG("core and modules system destroyed"); + GF_MAIN_LOG_DEBUG("core and modules system destroyed"); restart_count++; - SPDLOG_DEBUG("restart loop refresh, event loop code: {}, restart count: {}", - return_from_event_loop_code, restart_count); + GF_MAIN_LOG_DEBUG( + "restart loop refresh, event loop code: {}, restart count: {}", + return_from_event_loop_code, restart_count); } while (return_from_event_loop_code == GpgFrontend::kRestartCode && restart_count < 3); // log for debug - SPDLOG_INFO("GpgFrontend is about to exit."); + GF_MAIN_LOG_INFO("GpgFrontend is about to exit."); // deep restart mode if (return_from_event_loop_code == GpgFrontend::kDeepRestartCode || return_from_event_loop_code == kCrashCode) { // log for debug - SPDLOG_DEBUG( + GF_MAIN_LOG_DEBUG( "deep restart or cash loop status caught, restart a new application"); QProcess::startDetached(qApp->arguments()[0], qApp->arguments()); }; diff --git a/src/cmd.cpp b/src/cmd.cpp index 5c554f32..29a8114d 100644 --- a/src/cmd.cpp +++ b/src/cmd.cpp @@ -28,6 +28,8 @@ #include "cmd.h" +#include "main.h" + // std #include <iostream> @@ -83,16 +85,15 @@ auto ParseLogLevel(const po::variables_map& vm) -> spdlog::level::level_enum { } auto RunTest(const GFCxtWPtr& p_ctx) -> int { - GpgFrontend::GFCxtSPtr ctx = p_ctx.lock(); + GpgFrontend::GFCxtSPtr const ctx = p_ctx.lock(); if (ctx == nullptr) { - SPDLOG_ERROR("cannot get gpgfrontend context for test running"); + GF_MAIN_LOG_ERROR("cannot get gpgfrontend context for test running"); return -1; } GpgFrontend::Test::GpgFrontendContext test_init_args; test_init_args.argc = ctx->argc; test_init_args.argv = ctx->argv; - test_init_args.log_level = ctx->log_level; return GpgFrontend::Test::ExecuteAllTestCase(test_init_args); } diff --git a/src/core/GpgCoreInit.cpp b/src/core/GpgCoreInit.cpp index 7ccb2438..dcda6b44 100644 --- a/src/core/GpgCoreInit.cpp +++ b/src/core/GpgCoreInit.cpp @@ -52,62 +52,7 @@ namespace GpgFrontend { -/** - * @brief setup logging system and do proper initialization - * - */ -void InitCoreLoggingSystem(spdlog::level::level_enum level) { - // get the log directory - auto logfile_path = - (GlobalSettingStation::GetInstance().GetLogDir() / "core"); - logfile_path.replace_extension(".log"); - - // sinks - std::vector<spdlog::sink_ptr> sinks; - sinks.push_back(GpgFrontend::SecureCreateSharedObject< - spdlog::sinks::stderr_color_sink_mt>()); - sinks.push_back(GpgFrontend::SecureCreateSharedObject< - spdlog::sinks::rotating_file_sink_mt>(logfile_path.u8string(), - 1048576 * 32, 8)); - - // thread pool - spdlog::init_thread_pool(1024, 2); - - // logger - auto core_logger = - GpgFrontend::SecureCreateSharedObject<spdlog::async_logger>( - "core", begin(sinks), end(sinks), spdlog::thread_pool()); - core_logger->set_pattern( - "[%H:%M:%S.%e] [T:%t] [%=6n] %^[%=8l]%$ [%s:%#] [%!] -> %v (+%ius)"); - - // set the level of logger - core_logger->set_level(level); - - // flush policy -#ifdef DEBUG - core_logger->flush_on(spdlog::level::trace); -#else - core_logger->flush_on(spdlog::level::err); -#endif - spdlog::flush_every(std::chrono::seconds(5)); - - // register it as default logger - spdlog::set_default_logger(core_logger); -} - -void ShutdownCoreLoggingSystem() { -#ifdef WINDOWS - // Under VisualStudio, this must be called before main finishes to workaround - // a known VS issue - spdlog::drop_all(); - spdlog::shutdown(); -#endif -} - -void DestroyGpgFrontendCore() { - SingletonStorageCollection::Destroy(); - ShutdownCoreLoggingSystem(); -} +void DestroyGpgFrontendCore() { SingletonStorageCollection::Destroy(); } auto VerifyGpgconfPath(const std::filesystem::path& gnupg_install_fs_path) -> bool { @@ -136,7 +81,7 @@ auto SearchGpgconfPath(const std::vector<std::string>& candidate_paths) auto SearchKeyDatabasePath(const std::vector<std::string>& candidate_paths) -> std::filesystem::path { for (const auto& path : candidate_paths) { - SPDLOG_DEBUG("searh for candidate key database path: {}", path); + GF_CORE_LOG_DEBUG("searh for candidate key database path: {}", path); if (VerifyKeyDatabasePath(std::filesystem::path{path})) { return std::filesystem::path{path}; } @@ -171,7 +116,7 @@ auto InitGpgME() -> bool { continue; } - SPDLOG_DEBUG( + GF_CORE_LOG_DEBUG( "gpg context engine info: {} {} {} {}", gpgme_get_protocol_name(engine_info->protocol), std::string(engine_info->file_name == nullptr ? "null" @@ -233,12 +178,12 @@ auto InitGpgME() -> bool { const auto gnupg_version = Module::RetrieveRTValueTypedOrDefault<>( "core", "gpgme.ctx.gnupg_version", std::string{"0.0.0"}); - SPDLOG_DEBUG("got gnupg version from rt: {}", gnupg_version); + GF_CORE_LOG_DEBUG("got gnupg version from rt: {}", gnupg_version); // conditional check: only support gpg 2.1.x now if (!(CompareSoftwareVersion(gnupg_version, "2.1.0") >= 0 && find_gpgconf && find_openpgp && find_cms)) { - SPDLOG_ERROR("gpgme env check failed, abort"); + GF_CORE_LOG_ERROR("gpgme env check failed, abort"); return false; } @@ -255,7 +200,7 @@ void InitGpgFrontendCore(CoreInitArgs args) { Module::UpsertRTValue("core", "env.state.all", 0); // initialize locale environment - SPDLOG_DEBUG("locale: {}", setlocale(LC_CTYPE, nullptr)); + GF_CORE_LOG_DEBUG("locale: {}", setlocale(LC_CTYPE, nullptr)); // initialize library gpgme if (!InitGpgME()) { @@ -299,10 +244,10 @@ void InitGpgFrontendCore(CoreInitArgs args) { GpgFrontend::GlobalSettingStation::GetInstance().LookupSettings( "general.use_pinentry_as_password_input_dialog", false); - SPDLOG_DEBUG("core loaded if use custom key databse path: {}", - use_custom_key_database_path); - SPDLOG_DEBUG("core loaded custom key databse path: {}", - custom_key_database_path); + GF_CORE_LOG_DEBUG("core loaded if use custom key databse path: {}", + use_custom_key_database_path); + GF_CORE_LOG_DEBUG("core loaded custom key databse path: {}", + custom_key_database_path); std::filesystem::path gnupg_install_fs_path; // user defined @@ -317,19 +262,20 @@ void InitGpgFrontendCore(CoreInitArgs args) { if (!VerifyGpgconfPath(gnupg_install_fs_path)) { use_custom_gnupg_install_path = false; - SPDLOG_ERROR("core loaded custom gpgconf path is illegal: {}", - gnupg_install_fs_path.u8string()); + GF_CORE_LOG_ERROR( + "core loaded custom gpgconf path is illegal: {}", + gnupg_install_fs_path.u8string()); } else { - SPDLOG_DEBUG("core loaded custom gpgconf path: {}", - gnupg_install_fs_path.u8string()); + GF_CORE_LOG_DEBUG("core loaded custom gpgconf path: {}", + gnupg_install_fs_path.u8string()); } } else { #ifdef MACOS use_custom_gnupg_install_path = true; gnupg_install_fs_path = SearchGpgconfPath( {"/usr/local/bin/gpgconf", "/opt/homebrew/bin/gpgconf"}); - SPDLOG_DEBUG("core loaded searched gpgconf path: {}", - gnupg_install_fs_path.u8string()); + GF_CORE_LOG_DEBUG("core loaded searched gpgconf path: {}", + gnupg_install_fs_path.u8string()); #endif } @@ -339,21 +285,22 @@ void InitGpgFrontendCore(CoreInitArgs args) { if (!custom_key_database_path.empty()) { key_database_fs_path = custom_key_database_path; if (VerifyKeyDatabasePath(key_database_fs_path)) { - SPDLOG_ERROR( + GF_CORE_LOG_ERROR( "core loaded custom gpg key database is illegal: {}", key_database_fs_path.u8string()); } else { use_custom_key_database_path = true; - SPDLOG_DEBUG("core loaded custom gpg key database path: {}", - key_database_fs_path.u8string()); + GF_CORE_LOG_DEBUG( + "core loaded custom gpg key database path: {}", + key_database_fs_path.u8string()); } } else { #ifdef MACOS use_custom_key_database_path = true; key_database_fs_path = SearchKeyDatabasePath( {QDir::home().filesystemPath() / ".gnupg"}); - SPDLOG_DEBUG("core loaded searched key database path: {}", - key_database_fs_path.u8string()); + GF_CORE_LOG_DEBUG("core loaded searched key database path: {}", + key_database_fs_path.u8string()); #endif } @@ -387,7 +334,7 @@ void InitGpgFrontendCore(CoreInitArgs args) { // exit if failed if (!ctx.Good()) { - SPDLOG_ERROR("default gnupg context init error, abort"); + GF_CORE_LOG_ERROR("default gnupg context init error, abort"); CoreSignalStation::GetInstance()->SignalBadGnupgEnv( _("GpgME Context inilization failed")); return -1; @@ -399,7 +346,7 @@ void InitGpgFrontendCore(CoreInitArgs args) { if (args.gather_external_gnupg_info && Module::IsModuleAcivate("com.bktus.gpgfrontend.module." "integrated.gnupg-info-gathering")) { - SPDLOG_DEBUG("gnupg-info-gathering is activated"); + GF_CORE_LOG_DEBUG("gnupg-info-gathering is activated"); // gather external gnupg info Module::TriggerEvent( @@ -407,7 +354,7 @@ void InitGpgFrontendCore(CoreInitArgs args) { [](const Module::EventIdentifier& /*e*/, const Module::Event::ListenerIdentifier& l_id, DataObjectPtr o) { - SPDLOG_DEBUG( + GF_CORE_LOG_DEBUG( "received event GPGFRONTEND_CORE_INITLIZED callback " "from module: {}", l_id); @@ -415,7 +362,7 @@ void InitGpgFrontendCore(CoreInitArgs args) { if (l_id == "com.bktus.gpgfrontend.module.integrated.gnupg-info-" "gathering") { - SPDLOG_DEBUG( + GF_CORE_LOG_DEBUG( "received callback from gnupg-info-gathering "); // try to restart all components @@ -423,14 +370,14 @@ void InitGpgFrontendCore(CoreInitArgs args) { Module::UpsertRTValue("core", "env.state.gnupg", 1); // announce that all checkings were finished - SPDLOG_INFO( + GF_CORE_LOG_INFO( "all env checking finished, including gpgme, " "ctx and gnupg"); Module::UpsertRTValue("core", "env.state.all", 1); } }); } else { - SPDLOG_DEBUG("gnupg-info-gathering is not activated"); + GF_CORE_LOG_DEBUG("gnupg-info-gathering is not activated"); Module::UpsertRTValue("core", "env.state.all", 1); } @@ -440,7 +387,7 @@ void InitGpgFrontendCore(CoreInitArgs args) { _("Gpg Key Detabase inilization failed")); }; } - SPDLOG_INFO( + GF_CORE_LOG_INFO( "basic env checking finished, including gpgme, ctx, and key " "infos"); Module::UpsertRTValue("core", "env.state.basic", 1); diff --git a/src/core/GpgCoreInit.h b/src/core/GpgCoreInit.h index e1458e95..15f0254d 100644 --- a/src/core/GpgCoreInit.h +++ b/src/core/GpgCoreInit.h @@ -41,19 +41,6 @@ struct CoreInitArgs { * @brief * */ -void GPGFRONTEND_CORE_EXPORT -InitCoreLoggingSystem(spdlog::level::level_enum level); - -/** - * @brief - * - */ -void GPGFRONTEND_CORE_EXPORT ShutdownCoreLoggingSystem(); - -/** - * @brief - * - */ void GPGFRONTEND_CORE_EXPORT DestroyGpgFrontendCore(); /** diff --git a/src/core/function/ArchiveFileOperator.cpp b/src/core/function/ArchiveFileOperator.cpp index d186fee2..af311f3f 100644 --- a/src/core/function/ArchiveFileOperator.cpp +++ b/src/core/function/ArchiveFileOperator.cpp @@ -48,14 +48,14 @@ auto CopyData(struct archive *ar, struct archive *aw) -> int { r = archive_read_data_block(ar, &buff, &size, &offset); if (r == ARCHIVE_EOF) return (ARCHIVE_OK); if (r != ARCHIVE_OK) { - SPDLOG_ERROR("archive_read_data_block() failed: {}", - archive_error_string(ar)); + GF_CORE_LOG_ERROR("archive_read_data_block() failed: {}", + archive_error_string(ar)); return (r); } r = archive_write_data_block(aw, buff, size, offset); if (r != ARCHIVE_OK) { - SPDLOG_ERROR("archive_write_data_block() failed: {}", - archive_error_string(aw)); + GF_CORE_LOG_ERROR("archive_write_data_block() failed: {}", + archive_error_string(aw)); return (r); } } @@ -107,8 +107,8 @@ void ArchiveFileOperator::NewArchive2DataExchanger( auto r = archive_read_disk_open(disk, target_directory.c_str()); if (r != ARCHIVE_OK) { - SPDLOG_ERROR("archive_read_disk_open() failed: {}, abort...", - archive_error_string(disk)); + GF_CORE_LOG_ERROR("archive_read_disk_open() failed: {}, abort...", + archive_error_string(disk)); archive_read_free(disk); archive_write_free(archive); return -1; @@ -119,7 +119,7 @@ void ArchiveFileOperator::NewArchive2DataExchanger( r = archive_read_next_header2(disk, entry); if (r == ARCHIVE_EOF) break; if (r != ARCHIVE_OK) { - SPDLOG_ERROR( + GF_CORE_LOG_ERROR( "archive_read_next_header2() failed, ret: {}, explain: {}", r, archive_error_string(disk)); ret = -1; @@ -137,13 +137,14 @@ void ArchiveFileOperator::NewArchive2DataExchanger( r = archive_write_header(archive, entry); if (r < ARCHIVE_OK) { - SPDLOG_ERROR("archive_write_header() failed, ret: {}, explain: {} ", - r, archive_error_string(archive)); + GF_CORE_LOG_ERROR( + "archive_write_header() failed, ret: {}, explain: {} ", r, + archive_error_string(archive)); continue; } if (r == ARCHIVE_FATAL) { - SPDLOG_ERROR( + GF_CORE_LOG_ERROR( "archive_write_header() failed, ret: {}, explain: {}, " "abort ...", r, archive_error_string(archive)); @@ -180,15 +181,17 @@ void ArchiveFileOperator::ExtractArchiveFromDataExchanger( auto r = archive_read_support_filter_all(archive); if (r != ARCHIVE_OK) { - SPDLOG_ERROR("archive_read_support_filter_all(), ret: {}, reason: {}", - r, archive_error_string(archive)); + GF_CORE_LOG_ERROR( + "archive_read_support_filter_all(), ret: {}, reason: {}", r, + archive_error_string(archive)); return r; } r = archive_read_support_format_all(archive); if (r != ARCHIVE_OK) { - SPDLOG_ERROR("archive_read_support_format_all(), ret: {}, reason: {}", - r, archive_error_string(archive)); + GF_CORE_LOG_ERROR( + "archive_read_support_format_all(), ret: {}, reason: {}", r, + archive_error_string(archive)); return r; } @@ -198,15 +201,16 @@ void ArchiveFileOperator::ExtractArchiveFromDataExchanger( r = archive_read_open(archive, &rdata, nullptr, ArchiveReadCallback, nullptr); if (r != ARCHIVE_OK) { - SPDLOG_ERROR("archive_read_open(), ret: {}, reason: {}", r, - archive_error_string(archive)); + GF_CORE_LOG_ERROR("archive_read_open(), ret: {}, reason: {}", r, + archive_error_string(archive)); return r; } r = archive_write_disk_set_options(ext, 0); if (r != ARCHIVE_OK) { - SPDLOG_ERROR("archive_write_disk_set_options(), ret: {}, reason: {}", - r, archive_error_string(archive)); + GF_CORE_LOG_ERROR( + "archive_write_disk_set_options(), ret: {}, reason: {}", r, + archive_error_string(archive)); return r; } @@ -215,8 +219,8 @@ void ArchiveFileOperator::ExtractArchiveFromDataExchanger( r = archive_read_next_header(archive, &entry); if (r == ARCHIVE_EOF) break; if (r != ARCHIVE_OK) { - SPDLOG_ERROR("archive_read_next_header(), ret: {}, reason: {}", r, - archive_error_string(archive)); + GF_CORE_LOG_ERROR("archive_read_next_header(), ret: {}, reason: {}", + r, archive_error_string(archive)); break; } @@ -227,8 +231,8 @@ void ArchiveFileOperator::ExtractArchiveFromDataExchanger( r = archive_write_header(ext, entry); if (r != ARCHIVE_OK) { - SPDLOG_ERROR("archive_write_header(), ret: {}, reason: {}", r, - archive_error_string(archive)); + GF_CORE_LOG_ERROR("archive_write_header(), ret: {}, reason: {}", r, + archive_error_string(archive)); } else { r = CopyData(archive, ext); } @@ -236,13 +240,13 @@ void ArchiveFileOperator::ExtractArchiveFromDataExchanger( r = archive_read_free(archive); if (r != ARCHIVE_OK) { - SPDLOG_ERROR("archive_read_free(), ret: {}, reason: {}", r, - archive_error_string(archive)); + GF_CORE_LOG_ERROR("archive_read_free(), ret: {}, reason: {}", r, + archive_error_string(archive)); } r = archive_write_free(ext); if (r != ARCHIVE_OK) { - SPDLOG_ERROR("archive_read_free(), ret: {}, reason: {}", r, - archive_error_string(archive)); + GF_CORE_LOG_ERROR("archive_read_free(), ret: {}, reason: {}", r, + archive_error_string(archive)); } return 0; @@ -263,8 +267,8 @@ void ArchiveFileOperator::ListArchive( 10240); // Note 1 if (r != ARCHIVE_OK) return; while (archive_read_next_header(a, &entry) == ARCHIVE_OK) { - SPDLOG_DEBUG("File: {}", archive_entry_pathname(entry)); - SPDLOG_DEBUG("File Path: {}", archive_entry_pathname(entry)); + GF_CORE_LOG_DEBUG("File: {}", archive_entry_pathname(entry)); + GF_CORE_LOG_DEBUG("File Path: {}", archive_entry_pathname(entry)); archive_read_data_skip(a); // Note 2 } r = archive_read_free(a); // Note 3 diff --git a/src/core/function/CacheManager.cpp b/src/core/function/CacheManager.cpp index f9fa41ac..cf1417fb 100644 --- a/src/core/function/CacheManager.cpp +++ b/src/core/function/CacheManager.cpp @@ -108,7 +108,7 @@ class CacheManager::Impl : public QObject { if (std::find(key_storage_.begin(), key_storage_.end(), key) == key_storage_.end()) { - SPDLOG_DEBUG("register new key of cache", key); + GF_CORE_LOG_DEBUG("register new key of cache", key); key_storage_.push_back(key); } @@ -160,8 +160,8 @@ class CacheManager::Impl : public QObject { void slot_flush_cache_storage() { for (const auto& cache : cache_storage_.mirror()) { auto key = get_data_object_key(cache.first); - SPDLOG_TRACE("save cache into filesystem, key {}, value size: {}", key, - cache.second.size()); + GF_CORE_LOG_TRACE("save cache into filesystem, key {}, value size: {}", + key, cache.second.size()); GpgFrontend::DataObjectOperator::GetInstance().SaveDataObj(key, cache.second); } @@ -210,7 +210,7 @@ class CacheManager::Impl : public QObject { * */ void load_all_cache_storage() { - SPDLOG_DEBUG("start to load all cache from file system"); + GF_CORE_LOG_DEBUG("start to load all cache from file system"); auto stored_data = GpgFrontend::DataObjectOperator::GetInstance().GetDataObject(drk_key_); @@ -223,7 +223,7 @@ class CacheManager::Impl : public QObject { if (!registered_key_list.is_array()) { GpgFrontend::DataObjectOperator::GetInstance().SaveDataObj( drk_key_, nlohmann::json::array()); - SPDLOG_ERROR("drk_key_ is not an array, abort."); + GF_CORE_LOG_ERROR("drk_key_ is not an array, abort."); return; } diff --git a/src/core/function/CharsetOperator.cpp b/src/core/function/CharsetOperator.cpp index a5f96344..40978701 100644 --- a/src/core/function/CharsetOperator.cpp +++ b/src/core/function/CharsetOperator.cpp @@ -35,6 +35,8 @@ #include <cstddef> +#include "core/utils/LogUtils.h" + namespace GpgFrontend { auto CharsetOperator::Detect(const std::string &buffer) @@ -45,15 +47,16 @@ auto CharsetOperator::Detect(const std::string &buffer) status = U_ZERO_ERROR; if (U_FAILURE(status) != 0) { - SPDLOG_ERROR("failed to open charset detector: {}", u_errorName(status)); + GF_CORE_LOG_ERROR("failed to open charset detector: {}", + u_errorName(status)); return {"unknown", "unknown", 0}; } status = U_ZERO_ERROR; ucsdet_setText(csd, buffer.data(), buffer.size(), &status); if (U_FAILURE(status) != 0) { - SPDLOG_ERROR("failed to set text to charset detector: {}", - u_errorName(status)); + GF_CORE_LOG_ERROR("failed to set text to charset detector: {}", + u_errorName(status)); return {"unknown", "unknown", 0}; } @@ -74,7 +77,7 @@ auto CharsetOperator::Detect(const std::string &buffer) const char *language = ucsdet_getLanguage(ucm, &status); if (U_FAILURE(status) != 0) return {name, "unknown", confidence}; - SPDLOG_DEBUG("detected charset: {} {} {}", name, language, confidence); + GF_CORE_LOG_DEBUG("detected charset: {} {} {}", name, language, confidence); return {name, language, confidence}; } @@ -85,14 +88,14 @@ auto CharsetOperator::Convert2Utf8(const std::string &buffer, const auto from_encode = std::string("utf-8"); const auto &to_encode = from_charset_name; - SPDLOG_DEBUG("Converting buffer: {}", buffer.size()); + GF_CORE_LOG_DEBUG("Converting buffer: {}", buffer.size()); // test if the charset is supported UConverter *conv = ucnv_open(from_encode.c_str(), &status); ucnv_close(conv); if (U_FAILURE(status) != 0) { - SPDLOG_ERROR("failed to open converter: {}, from encode: {}", - u_errorName(status), from_encode); + GF_CORE_LOG_ERROR("failed to open converter: {}, from encode: {}", + u_errorName(status), from_encode); return false; } @@ -100,8 +103,8 @@ auto CharsetOperator::Convert2Utf8(const std::string &buffer, conv = ucnv_open(to_encode.c_str(), &status); ucnv_close(conv); if (U_FAILURE(status) != 0) { - SPDLOG_ERROR("failed to open converter: {}, to encode: {}", - u_errorName(status), to_encode); + GF_CORE_LOG_ERROR("failed to open converter: {}, to encode: {}", + u_errorName(status), to_encode); return false; } @@ -122,11 +125,11 @@ auto CharsetOperator::Convert2Utf8(const std::string &buffer, } if (U_FAILURE(status) != 0) { - SPDLOG_ERROR("failed to convert to utf-8: {}", u_errorName(status)); + GF_CORE_LOG_ERROR("failed to convert to utf-8: {}", u_errorName(status)); return false; } - SPDLOG_DEBUG("converted buffer: {} bytes", out_buffer.size()); + GF_CORE_LOG_DEBUG("converted buffer: {} bytes", out_buffer.size()); return true; } diff --git a/src/core/function/DataObjectOperator.cpp b/src/core/function/DataObjectOperator.cpp index 9607de59..437e6f11 100644 --- a/src/core/function/DataObjectOperator.cpp +++ b/src/core/function/DataObjectOperator.cpp @@ -38,7 +38,7 @@ namespace GpgFrontend { void DataObjectOperator::init_app_secure_key() { - SPDLOG_TRACE("initializing application secure key"); + GF_CORE_LOG_TRACE("initializing application secure key"); WriteFileStd(app_secure_key_path_, PassphraseGenerator::GetInstance().Generate(256)); std::filesystem::permissions( @@ -56,13 +56,13 @@ DataObjectOperator::DataObjectOperator(int channel) std::string key; if (!ReadFileStd(app_secure_key_path_.u8string(), key)) { - SPDLOG_ERROR("failed to read app secure key file: {}", - app_secure_key_path_.u8string()); + GF_CORE_LOG_ERROR("failed to read app secure key file: {}", + app_secure_key_path_.u8string()); throw std::runtime_error("failed to read app secure key file"); } hash_key_ = QCryptographicHash::hash(QByteArray::fromStdString(key), QCryptographicHash::Sha256); - SPDLOG_TRACE("app secure key loaded {} bytes", hash_key_.size()); + GF_CORE_LOG_TRACE("app secure key loaded {} bytes", hash_key_.size()); if (!exists(app_data_objs_path_)) create_directory(app_data_objs_path_); } @@ -95,8 +95,8 @@ auto DataObjectOperator::SaveDataObj(const std::string& _key, QAESEncryption::Padding::ISO); auto encoded = encryption.encode(QByteArray::fromStdString(to_string(value)), hash_key_); - SPDLOG_TRACE("saving data object {} to {} , size: {} bytes", hash_obj_key, - obj_path.u8string(), encoded.size()); + GF_CORE_LOG_TRACE("saving data object {} to {} , size: {} bytes", + hash_obj_key, obj_path.u8string(), encoded.size()); WriteFileStd(obj_path.u8string(), encoded.toStdString()); @@ -106,7 +106,7 @@ auto DataObjectOperator::SaveDataObj(const std::string& _key, auto DataObjectOperator::GetDataObject(const std::string& _key) -> std::optional<nlohmann::json> { try { - SPDLOG_TRACE("get data object from disk {}", _key); + GF_CORE_LOG_TRACE("get data object from disk {}", _key); auto hash_obj_key = QCryptographicHash::hash(hash_key_ + QByteArray::fromStdString(_key), QCryptographicHash::Sha256) @@ -116,13 +116,13 @@ auto DataObjectOperator::GetDataObject(const std::string& _key) const auto obj_path = app_data_objs_path_ / hash_obj_key; if (!std::filesystem::exists(obj_path)) { - SPDLOG_WARN("data object not found, key: {}", _key); + GF_CORE_LOG_WARN("data object not found, key: {}", _key); return {}; } std::string buffer; if (!ReadFileStd(obj_path.u8string(), buffer)) { - SPDLOG_ERROR("failed to read data object, key: {}", _key); + GF_CORE_LOG_ERROR("failed to read data object, key: {}", _key); return {}; } @@ -130,17 +130,17 @@ auto DataObjectOperator::GetDataObject(const std::string& _key) QAESEncryption encryption(QAESEncryption::AES_256, QAESEncryption::ECB, QAESEncryption::Padding::ISO); - SPDLOG_TRACE("decrypting data object {} , hash key size: {}", - encoded.size(), hash_key_.size()); + GF_CORE_LOG_TRACE("decrypting data object {} , hash key size: {}", + encoded.size(), hash_key_.size()); auto decoded = encryption.removePadding(encryption.decode(encoded, hash_key_)); - SPDLOG_TRACE("data object decoded: {}", _key); + GF_CORE_LOG_TRACE("data object decoded: {}", _key); return nlohmann::json::parse(decoded.toStdString()); } catch (...) { - SPDLOG_ERROR("failed to get data object, caught exception: {}", _key); + GF_CORE_LOG_ERROR("failed to get data object, caught exception: {}", _key); return {}; } } diff --git a/src/core/function/GlobalSettingStation.cpp b/src/core/function/GlobalSettingStation.cpp index 6290e866..09dd1c90 100644 --- a/src/core/function/GlobalSettingStation.cpp +++ b/src/core/function/GlobalSettingStation.cpp @@ -43,10 +43,10 @@ class GlobalSettingStation::Impl { * */ explicit Impl() noexcept { - SPDLOG_INFO("app path: {}", app_path_.u8string()); + GF_CORE_LOG_INFO("app path: {}", app_path_.u8string()); auto portable_file_path = app_path_ / "PORTABLE.txt"; if (std::filesystem::exists(portable_file_path)) { - SPDLOG_INFO( + GF_CORE_LOG_INFO( "dectected portable mode, reconfiguring config and data path..."); Module::UpsertRTValue("core", "env.state.portable", 1); @@ -60,15 +60,15 @@ class GlobalSettingStation::Impl { app_data_objs_path_ = app_data_path_ / "data_objs"; } - SPDLOG_INFO("app configure path: {}", app_configure_path_.u8string()); - SPDLOG_INFO("app data path: {}", app_data_path_.u8string()); - SPDLOG_INFO("app log path: {}", app_log_path_.u8string()); - SPDLOG_INFO("app locale path: {}", app_locale_path_.u8string()); - SPDLOG_INFO("app conf path: {}", main_config_path_.u8string()); + GF_CORE_LOG_INFO("app configure path: {}", app_configure_path_.u8string()); + GF_CORE_LOG_INFO("app data path: {}", app_data_path_.u8string()); + GF_CORE_LOG_INFO("app log path: {}", app_log_path_.u8string()); + GF_CORE_LOG_INFO("app locale path: {}", app_locale_path_.u8string()); + GF_CORE_LOG_INFO("app conf path: {}", main_config_path_.u8string()); - SPDLOG_INFO("app log files total size: {}", GetLogFilesSize()); - SPDLOG_INFO("app data objects files total size: {}", - GetDataObjectsFilesSize()); + GF_CORE_LOG_INFO("app log files total size: {}", GetLogFilesSize()); + GF_CORE_LOG_INFO("app data objects files total size: {}", + GetDataObjectsFilesSize()); if (!is_directory(app_configure_path_)) { create_directory(app_configure_path_); @@ -80,24 +80,27 @@ class GlobalSettingStation::Impl { if (!exists(main_config_path_)) { try { this->ui_cfg_.writeFile(main_config_path_.u8string().c_str()); - SPDLOG_DEBUG("user interface configuration successfully written to {}", - main_config_path_.u8string()); + GF_CORE_LOG_DEBUG( + "user interface configuration successfully written to {}", + main_config_path_.u8string()); } catch (const libconfig::FileIOException &fioex) { - SPDLOG_DEBUG( + GF_CORE_LOG_DEBUG( "i/o error while writing UserInterface configuration file {}", main_config_path_.u8string()); } } else { try { this->ui_cfg_.readFile(main_config_path_.u8string().c_str()); - SPDLOG_DEBUG("user interface configuration successfully read from {}", - main_config_path_.u8string()); + GF_CORE_LOG_DEBUG( + "user interface configuration successfully read from {}", + main_config_path_.u8string()); } catch (const libconfig::FileIOException &fioex) { - SPDLOG_ERROR("i/o error while reading UserInterface configure file"); + GF_CORE_LOG_ERROR( + "i/o error while reading UserInterface configure file"); } catch (const libconfig::ParseException &pex) { - SPDLOG_ERROR("parse error at {} : {} - {}", pex.getFile(), - pex.getLine(), pex.getError()); + GF_CORE_LOG_ERROR("parse error at {} : {} - {}", pex.getFile(), + pex.getLine(), pex.getError()); } } } @@ -134,7 +137,7 @@ class GlobalSettingStation::Impl { try { value = static_cast<T>(GetMainSettings().lookup(path)); } catch (...) { - SPDLOG_WARN("setting not found: {}", path); + GF_CORE_LOG_WARN("setting not found: {}", path); } return value; } @@ -212,12 +215,12 @@ class GlobalSettingStation::Impl { void SyncSettings() noexcept { try { ui_cfg_.writeFile(main_config_path_.u8string().c_str()); - SPDLOG_DEBUG("updated ui configuration successfully written to {}", - main_config_path_.u8string()); + GF_CORE_LOG_DEBUG("updated ui configuration successfully written to {}", + main_config_path_.u8string()); } catch (const libconfig::FileIOException &fioex) { - SPDLOG_ERROR("i/o error while writing ui configuration file: {}", - main_config_path_.u8string()); + GF_CORE_LOG_ERROR("i/o error while writing ui configuration file: {}", + main_config_path_.u8string()); } } diff --git a/src/core/function/GlobalSettingStation.h b/src/core/function/GlobalSettingStation.h index 282e115d..5582562a 100644 --- a/src/core/function/GlobalSettingStation.h +++ b/src/core/function/GlobalSettingStation.h @@ -163,7 +163,7 @@ class GPGFRONTEND_CORE_EXPORT GlobalSettingStation try { value = static_cast<T>(GetMainSettings().lookup(path)); } catch (...) { - SPDLOG_WARN("setting not found: {}", path); + GF_CORE_LOG_WARN("setting not found: {}", path); } return value; } diff --git a/src/core/function/KeyPackageOperator.cpp b/src/core/function/KeyPackageOperator.cpp index e986ef44..4232937a 100644 --- a/src/core/function/KeyPackageOperator.cpp +++ b/src/core/function/KeyPackageOperator.cpp @@ -44,7 +44,7 @@ namespace GpgFrontend { auto KeyPackageOperator::GeneratePassphrase( const std::filesystem::path& phrase_path, std::string& phrase) -> bool { phrase = PassphraseGenerator::GetInstance().Generate(256); - SPDLOG_DEBUG("generated passphrase: {} bytes", phrase.size()); + GF_CORE_LOG_DEBUG("generated passphrase: {} bytes", phrase.size()); return WriteFileStd(phrase_path, phrase); } @@ -52,12 +52,12 @@ auto KeyPackageOperator::GenerateKeyPackage( const std::filesystem::path& key_package_path, const std::string& key_package_name, KeyIdArgsListPtr& key_ids, std::string& phrase, bool secret) -> bool { - SPDLOG_DEBUG("generating key package: {}", key_package_name); + GF_CORE_LOG_DEBUG("generating key package: {}", key_package_name); ByteArrayPtr key_export_data = nullptr; if (!GpgKeyImportExporter::GetInstance().ExportAllKeys( key_ids, key_export_data, secret)) { - SPDLOG_ERROR("failed to export keys"); + GF_CORE_LOG_ERROR("failed to export keys"); return false; } @@ -69,7 +69,7 @@ auto KeyPackageOperator::GenerateKeyPackage( QAESEncryption::Padding::ISO); auto encoded = encryption.encode(data, hash_key); - SPDLOG_DEBUG("writing key package: {}", key_package_name); + GF_CORE_LOG_DEBUG("writing key package: {}", key_package_name); return WriteFileStd(key_package_path, encoded.toStdString()); } @@ -77,21 +77,22 @@ auto KeyPackageOperator::ImportKeyPackage( const std::filesystem::path& key_package_path, const std::filesystem::path& phrase_path, GpgImportInformation& import_info) -> bool { - SPDLOG_DEBUG("importing key package: {]", key_package_path.u8string()); + GF_CORE_LOG_DEBUG("importing key package: {]", key_package_path.u8string()); std::string encrypted_data; ReadFileStd(key_package_path, encrypted_data); if (encrypted_data.empty()) { - SPDLOG_ERROR("failed to read key package: {}", key_package_path.u8string()); + GF_CORE_LOG_ERROR("failed to read key package: {}", + key_package_path.u8string()); return false; }; std::string passphrase; ReadFileStd(phrase_path, passphrase); - SPDLOG_DEBUG("passphrase: {} bytes", passphrase.size()); + GF_CORE_LOG_DEBUG("passphrase: {} bytes", passphrase.size()); if (passphrase.size() != 256) { - SPDLOG_ERROR("failed to read passphrase: {}", phrase_path.u8string()); + GF_CORE_LOG_ERROR("failed to read passphrase: {}", phrase_path.u8string()); return false; } @@ -105,7 +106,7 @@ auto KeyPackageOperator::ImportKeyPackage( auto decoded = encryption.removePadding(encryption.decode(encoded, hash_key)); auto key_data = QByteArray::fromBase64(decoded); - SPDLOG_DEBUG("key data size: {}", key_data.size()); + GF_CORE_LOG_DEBUG("key data size: {}", key_data.size()); if (!key_data.startsWith(PGP_PUBLIC_KEY_BEGIN) && !key_data.startsWith(PGP_PRIVATE_KEY_BEGIN)) { return false; diff --git a/src/core/function/LoggerManager.cpp b/src/core/function/LoggerManager.cpp new file mode 100644 index 00000000..cac373ed --- /dev/null +++ b/src/core/function/LoggerManager.cpp @@ -0,0 +1,155 @@ +/** + * Copyright (C) 2021 Saturneric <[email protected]> + * + * This file is part of GpgFrontend. + * + * GpgFrontend is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * GpgFrontend is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with GpgFrontend. If not, see <https://www.gnu.org/licenses/>. + * + * The initial version of the source code is inherited from + * the gpg4usb project, which is under GPL-3.0-or-later. + * + * All the source code of GpgFrontend was modified and released by + * Saturneric <[email protected]> starting on May 12, 2021. + * + * SPDX-License-Identifier: GPL-3.0-or-later + * + */ + +#include "LoggerManager.h" + +#include <spdlog/async.h> +#include <spdlog/common.h> +#include <spdlog/sinks/rotating_file_sink.h> +#include <spdlog/sinks/stdout_color_sinks.h> + +#include "core/function/GlobalSettingStation.h" + +namespace GpgFrontend { + +std::shared_ptr<spdlog::logger> LoggerManager::default_logger = nullptr; +spdlog::level::level_enum LoggerManager::default_log_level = + spdlog::level::debug; + +LoggerManager::LoggerManager(int channel) + : SingletonFunctionObject<LoggerManager>(channel) { + spdlog::init_thread_pool(1024, 2); + spdlog::flush_every(std::chrono::seconds(5)); +} + +LoggerManager::~LoggerManager() { +#ifdef WINDOWS + // Under VisualStudio, this must be called before main finishes to workaround + // a known VS issue + spdlog::drop_all(); + spdlog::shutdown(); +#endif + + if (default_logger) default_logger = nullptr; +} + +auto LoggerManager::GetLogger(const std::string& id) + -> std::shared_ptr<spdlog::logger> { + auto m_it = logger_map_.find(id); + if (m_it == logger_map_.end()) return GetDefaultLogger(); + return m_it->second; +} + +auto LoggerManager::RegisterAsyncLogger(const std::string& id, + spdlog::level::level_enum level) + -> std::shared_ptr<spdlog::logger> { + // get the log directory + auto log_file_path = (GlobalSettingStation::GetInstance().GetLogDir() / id); + log_file_path.replace_extension(".log"); + + // sinks + std::vector<spdlog::sink_ptr> sinks; + sinks.push_back(GpgFrontend::SecureCreateSharedObject< + spdlog::sinks::stderr_color_sink_mt>()); + sinks.push_back(GpgFrontend::SecureCreateSharedObject< + spdlog::sinks::rotating_file_sink_mt>( + log_file_path.u8string(), 1048576 * 32, 8)); + + // logger + auto logger = GpgFrontend::SecureCreateSharedObject<spdlog::async_logger>( + id, begin(sinks), end(sinks), spdlog::thread_pool()); + logger->set_pattern( + "[%H:%M:%S.%e] [T:%t] [%=6n] %^[%=8l]%$ [%s:%#] [%!] -> %v (+%ius)"); + + // set the level of logger + logger->set_level(level); + + // flush policy +#ifdef DEBUG + logger->flush_on(spdlog::level::trace); +#else + core_logger->flush_on(spdlog::level::err); +#endif + + logger_map_[id] = logger; + return logger; +} + +auto LoggerManager::RegisterSyncLogger(const std::string& id, + spdlog::level::level_enum level) + -> std::shared_ptr<spdlog::logger> { + // get the log directory + auto log_file_path = (GlobalSettingStation::GetInstance().GetLogDir() / id); + log_file_path.replace_extension(".log"); + + // sinks + std::vector<spdlog::sink_ptr> sinks; + sinks.push_back(GpgFrontend::SecureCreateSharedObject< + spdlog::sinks::stderr_color_sink_mt>()); + sinks.push_back(GpgFrontend::SecureCreateSharedObject< + spdlog::sinks::rotating_file_sink_mt>( + log_file_path.u8string(), 1048576 * 32, 8)); + + // logger + auto logger = GpgFrontend::SecureCreateSharedObject<spdlog::logger>( + id, begin(sinks), end(sinks)); + logger->set_pattern( + "[%H:%M:%S.%e] [T:%t] [%=6n] %^[%=8l]%$ [%s:%#] [%!] -> %v (+%ius)"); + + // set the level of logger + logger->set_level(level); + + logger_map_[id] = logger; + return logger; +} + +auto LoggerManager::GetDefaultLogger() -> std::shared_ptr<spdlog::logger> { + if (default_logger == nullptr) { + // sinks + std::vector<spdlog::sink_ptr> sinks; + sinks.push_back(GpgFrontend::SecureCreateSharedObject< + spdlog::sinks::stderr_color_sink_mt>()); + + // logger + auto logger = GpgFrontend::SecureCreateSharedObject<spdlog::logger>( + "default", begin(sinks), end(sinks)); + logger->set_pattern( + "[%H:%M:%S.%e] [T:%t] [%=6n] %^[%=8l]%$ [%s:%#] [%!] -> %v (+%ius)"); + + // set the level of logger + logger->set_level(default_log_level); + spdlog::set_default_logger(logger); + default_logger = logger; + } + return default_logger; +} + +void LoggerManager::SetDefaultLogLevel(spdlog::level::level_enum level) { + default_log_level = level; +} +} // namespace GpgFrontend
\ No newline at end of file diff --git a/src/core/function/LoggerManager.h b/src/core/function/LoggerManager.h new file mode 100644 index 00000000..531e6efe --- /dev/null +++ b/src/core/function/LoggerManager.h @@ -0,0 +1,65 @@ +/** + * Copyright (C) 2021 Saturneric <[email protected]> + * + * This file is part of GpgFrontend. + * + * GpgFrontend is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * GpgFrontend is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with GpgFrontend. If not, see <https://www.gnu.org/licenses/>. + * + * The initial version of the source code is inherited from + * the gpg4usb project, which is under GPL-3.0-or-later. + * + * All the source code of GpgFrontend was modified and released by + * Saturneric <[email protected]> starting on May 12, 2021. + * + * SPDX-License-Identifier: GPL-3.0-or-later + * + */ + +#pragma once + +#include "core/function/basic/GpgFunctionObject.h" + +namespace spdlog { +class logger; +} + +namespace GpgFrontend { + +class GPGFRONTEND_CORE_EXPORT LoggerManager + : public SingletonFunctionObject<LoggerManager> { + public: + explicit LoggerManager(int channel); + + ~LoggerManager() override; + + auto RegisterAsyncLogger(const std::string& id, spdlog::level::level_enum) + -> std::shared_ptr<spdlog::logger>; + + auto RegisterSyncLogger(const std::string& id, spdlog::level::level_enum) + -> std::shared_ptr<spdlog::logger>; + + auto GetLogger(const std::string& id) -> std::shared_ptr<spdlog::logger>; + + static auto GetDefaultLogger() -> std::shared_ptr<spdlog::logger>; + + static void SetDefaultLogLevel(spdlog::level::level_enum); + + private: + static spdlog::level::level_enum default_log_level; + static std::shared_ptr<spdlog::logger> default_logger; + + std::map<std::string, std::shared_ptr<spdlog::logger>> logger_map_; +}; + +} // namespace GpgFrontend
\ No newline at end of file diff --git a/src/core/function/SecureMemoryAllocator.cpp b/src/core/function/SecureMemoryAllocator.cpp index 02efcbe0..692c36c5 100644 --- a/src/core/function/SecureMemoryAllocator.cpp +++ b/src/core/function/SecureMemoryAllocator.cpp @@ -40,9 +40,6 @@ auto SecureMemoryAllocator::Allocate(std::size_t size) -> void* { #else auto* addr = malloc(size); #endif - - SPDLOG_TRACE("secure memory allocator trys to alloc memory, address: {}", - static_cast<void*>(addr)); return addr; } @@ -52,11 +49,6 @@ auto SecureMemoryAllocator::Reallocate(void* ptr, std::size_t size) -> void* { #else auto* addr = realloc(ptr, size); #endif - - SPDLOG_TRACE( - "secure memory allocator trys to realloc memory, " - "old address: {}, new address: {}", - static_cast<void*>(ptr), static_cast<void*>(addr)); return addr; } diff --git a/src/core/function/basic/GpgFunctionObject.cpp b/src/core/function/basic/GpgFunctionObject.cpp index e31ff2d6..e9e444f1 100644 --- a/src/core/function/basic/GpgFunctionObject.cpp +++ b/src/core/function/basic/GpgFunctionObject.cpp @@ -32,8 +32,8 @@ #include <mutex> #include <typeinfo> -#include "function/SecureMemoryAllocator.h" -#include "function/basic/ChannelObject.h" +#include "core/function/SecureMemoryAllocator.h" +#include "core/function/basic/ChannelObject.h" struct FunctionObjectTypeLockInfo { std::map<int, std::mutex> channel_lock_map; @@ -66,8 +66,8 @@ auto GetGlobalFunctionObjectTypeLock(const std::type_info& type) */ auto GetChannelObjectInstance(const std::type_info& type, int channel) -> ChannelObject* { - SPDLOG_TRACE("try to get instance of type: {} at channel: {}", type.name(), - channel); + GF_DEFAULT_LOG_TRACE("try to get instance of type: {} at channel: {}", + type.name(), channel); // lock this channel std::lock_guard<std::mutex> guard( @@ -75,13 +75,13 @@ auto GetChannelObjectInstance(const std::type_info& type, int channel) auto* p_storage = SingletonStorageCollection::GetInstance(false)->GetSingletonStorage(type); - SPDLOG_TRACE("get singleton storage result, p_storage: {}", - static_cast<void*>(p_storage)); + GF_DEFAULT_LOG_TRACE("get singleton storage result, p_storage: {}", + static_cast<void*>(p_storage)); auto* p_pbj = static_cast<ChannelObject*>(p_storage->FindObjectInChannel(channel)); - SPDLOG_TRACE("find channel object result, channel {}, p_pbj: {}", channel, - static_cast<void*>(p_pbj)); + GF_DEFAULT_LOG_TRACE("find channel object result, channel {}, p_pbj: {}", + channel, static_cast<void*>(p_pbj)); return p_pbj; } @@ -95,8 +95,8 @@ auto CreateChannelObjectInstance(const std::type_info& type, int channel, auto* p_storage = SingletonStorageCollection::GetInstance(false)->GetSingletonStorage(type); - SPDLOG_TRACE("create channel object, channel {}, type: {}", channel, - type.name()); + GF_DEFAULT_LOG_TRACE("create channel object, channel {}, type: {}", channel, + type.name()); // do create object of this channel return p_storage->SetObjectInChannel(channel, std::move(channel_object)); diff --git a/src/core/function/basic/SingletonStorage.cpp b/src/core/function/basic/SingletonStorage.cpp index f6507567..eab71e0f 100644 --- a/src/core/function/basic/SingletonStorage.cpp +++ b/src/core/function/basic/SingletonStorage.cpp @@ -53,7 +53,8 @@ class SingletonStorage::Impl { std::shared_lock<std::shared_mutex> lock(instances_mutex_); ins_it = instances_map_.find(channel); if (ins_it == instances_map_.end()) { - SPDLOG_TRACE("cannot find channel object, channel: {}", channel); + GF_DEFAULT_LOG_TRACE("cannot find channel object, channel: {}", + channel); return nullptr; } return ins_it->second.get(); @@ -71,14 +72,14 @@ class SingletonStorage::Impl { auto SetObjectInChannel(int channel, ChannelObjectPtr p_obj) -> GpgFrontend::ChannelObject* { - SPDLOG_TRACE("set channel object, type: {} in channel: {}, address: {}", - typeid(p_obj.get()).name(), channel, - static_cast<void*>(p_obj.get())); + GF_DEFAULT_LOG_TRACE( + "set channel object, type: {} in channel: {}, address: {}", + typeid(p_obj.get()).name(), channel, static_cast<void*>(p_obj.get())); assert(p_obj != nullptr); if (p_obj == nullptr) { - SPDLOG_ERROR("cannot set a nullptr as a channel obejct of channel: {}", - channel); + GF_DEFAULT_LOG_ERROR( + "cannot set a nullptr as a channel obejct of channel: {}", channel); return nullptr; } @@ -86,7 +87,7 @@ class SingletonStorage::Impl { auto* raw_obj = p_obj.get(); { - SPDLOG_TRACE( + GF_DEFAULT_LOG_TRACE( "register channel object to instances map, " "channel: {}, address: {}", channel, static_cast<void*>(p_obj.get())); @@ -94,8 +95,9 @@ class SingletonStorage::Impl { instances_map_[channel] = std::move(p_obj); } - SPDLOG_TRACE("set channel: {} success, current channel object address: {}", - channel, static_cast<void*>(raw_obj)); + GF_DEFAULT_LOG_TRACE( + "set channel: {} success, current channel object address: {}", channel, + static_cast<void*>(raw_obj)); return raw_obj; } diff --git a/src/core/function/basic/SingletonStorageCollection.cpp b/src/core/function/basic/SingletonStorageCollection.cpp index 9c0116cb..c22b5242 100644 --- a/src/core/function/basic/SingletonStorageCollection.cpp +++ b/src/core/function/basic/SingletonStorageCollection.cpp @@ -49,7 +49,7 @@ class SingletonStorageCollection::Impl { static auto GetInstance(bool force_refresh) -> SingletonStorageCollection* { if (force_refresh || global_instance == nullptr) { global_instance = SecureCreateUniqueObject<SingletonStorageCollection>(); - SPDLOG_TRACE( + GF_DEFAULT_LOG_TRACE( "a new global singleton storage collection created, address: {}", static_cast<void*>(global_instance.get())); } @@ -80,7 +80,7 @@ class SingletonStorageCollection::Impl { } if (ins_it == storages_map_.end()) { auto storage = SecureCreateUniqueObject<SingletonStorage>(); - SPDLOG_TRACE( + GF_DEFAULT_LOG_TRACE( "hash: {} created, singleton storage address: {} type_name: {}", hash, static_cast<void*>(storage.get()), type_id.name()); @@ -110,7 +110,7 @@ auto GpgFrontend::SingletonStorageCollection::GetInstance(bool force_refresh) } void SingletonStorageCollection::Destroy() { - SPDLOG_TRACE( + GF_DEFAULT_LOG_TRACE( "global singleton storage collection is about to destroy, address: {}", static_cast<void*>(global_instance.get())); return SingletonStorageCollection::Impl::Destroy(); diff --git a/src/core/function/gpg/GpgAdvancedOperator.cpp b/src/core/function/gpg/GpgAdvancedOperator.cpp index 0f8d1718..c96b35f7 100644 --- a/src/core/function/gpg/GpgAdvancedOperator.cpp +++ b/src/core/function/gpg/GpgAdvancedOperator.cpp @@ -40,10 +40,10 @@ auto GpgFrontend::GpgAdvancedOperator::ClearGpgPasswordCache() -> bool { const auto gpgconf_path = Module::RetrieveRTValueTypedOrDefault<>( "core", "gpgme.ctx.gpgconf_path", std::string{}); - SPDLOG_DEBUG("got gpgconf path from rt: {}", gpgconf_path); + GF_CORE_LOG_DEBUG("got gpgconf path from rt: {}", gpgconf_path); if (gpgconf_path.empty()) { - SPDLOG_ERROR("cannot get valid gpgconf path from rt, abort."); + GF_CORE_LOG_ERROR("cannot get valid gpgconf path from rt, abort."); return false; } @@ -53,7 +53,7 @@ auto GpgFrontend::GpgAdvancedOperator::ClearGpgPasswordCache() -> bool { [&](int exit_code, const std::string & /*p_out*/, const std::string & /*p_err*/) { if (exit_code == 0) { - SPDLOG_DEBUG("gpgconf reload exit code: {}", exit_code); + GF_CORE_LOG_DEBUG("gpgconf reload exit code: {}", exit_code); success = true; } }}); @@ -65,10 +65,10 @@ auto GpgFrontend::GpgAdvancedOperator::ReloadGpgComponents() -> bool { const auto gpgconf_path = Module::RetrieveRTValueTypedOrDefault<>( "core", "gpgme.ctx.gpgconf_path", std::string{}); - SPDLOG_DEBUG("got gpgconf path from rt: {}", gpgconf_path); + GF_CORE_LOG_DEBUG("got gpgconf path from rt: {}", gpgconf_path); if (gpgconf_path.empty()) { - SPDLOG_ERROR("cannot get valid gpgconf path from rt, abort."); + GF_CORE_LOG_ERROR("cannot get valid gpgconf path from rt, abort."); return false; } @@ -79,7 +79,7 @@ auto GpgFrontend::GpgAdvancedOperator::ReloadGpgComponents() -> bool { if (exit_code == 0) { success = true; } else { - SPDLOG_ERROR( + GF_CORE_LOG_ERROR( "gpgconf execute error, process stderr: {}, process stdout: {}", p_err, p_out); return; @@ -91,10 +91,10 @@ auto GpgFrontend::GpgAdvancedOperator::ReloadGpgComponents() -> bool { void GpgFrontend::GpgAdvancedOperator::RestartGpgComponents() { const auto gpgconf_path = Module::RetrieveRTValueTypedOrDefault<>( "core", "gpgme.ctx.gpgconf_path", std::string{}); - SPDLOG_DEBUG("got gpgconf path from rt: {}", gpgconf_path); + GF_CORE_LOG_DEBUG("got gpgconf path from rt: {}", gpgconf_path); if (gpgconf_path.empty()) { - SPDLOG_ERROR("cannot get valid gpgconf path from rt, abort."); + GF_CORE_LOG_ERROR("cannot get valid gpgconf path from rt, abort."); return; } @@ -102,19 +102,20 @@ void GpgFrontend::GpgAdvancedOperator::RestartGpgComponents() { {gpgconf_path, {"--verbose", "--kill", "all"}, [&](int exit_code, const std::string &p_out, const std::string &p_err) { - SPDLOG_DEBUG("gpgconf --kill all command got exit code: {}", - exit_code); + GF_CORE_LOG_DEBUG("gpgconf --kill all command got exit code: {}", + exit_code); bool success = true; if (exit_code != 0) { success = false; - SPDLOG_ERROR( + GF_CORE_LOG_ERROR( "gpgconf execute error, process stderr: {}, process stdout: {}", p_err, p_out); } - SPDLOG_DEBUG("gpgconf --kill --all execute result: {}", success); + GF_CORE_LOG_DEBUG("gpgconf --kill --all execute result: {}", success); if (!success) { - SPDLOG_ERROR("restart all component after core initilized failed"); + GF_CORE_LOG_ERROR( + "restart all component after core initilized failed"); Module::UpsertRTValue( "core", "gpg_advanced_operator.restart_gpg_components", false); return; @@ -123,19 +124,19 @@ void GpgFrontend::GpgAdvancedOperator::RestartGpgComponents() { success &= StartGpgAgent(); if (!success) { - SPDLOG_ERROR("start gpg agent after core initilized failed"); + GF_CORE_LOG_ERROR("start gpg agent after core initilized failed"); } success &= StartDirmngr(); if (!success) { - SPDLOG_ERROR("start dirmngr after core initilized failed"); + GF_CORE_LOG_ERROR("start dirmngr after core initilized failed"); } success &= StartKeyBoxd(); if (!success) { - SPDLOG_ERROR("start keyboxd after core initilized failed"); + GF_CORE_LOG_ERROR("start keyboxd after core initilized failed"); } Module::UpsertRTValue( @@ -148,10 +149,10 @@ auto GpgFrontend::GpgAdvancedOperator::ResetConfigures() -> bool { const auto gpgconf_path = Module::RetrieveRTValueTypedOrDefault<>( "core", "gpgme.ctx.gpgconf_path", std::string{}); - SPDLOG_DEBUG("got gpgconf path from rt: {}", gpgconf_path); + GF_CORE_LOG_DEBUG("got gpgconf path from rt: {}", gpgconf_path); if (gpgconf_path.empty()) { - SPDLOG_ERROR("cannot get valid gpgconf path from rt, abort."); + GF_CORE_LOG_ERROR("cannot get valid gpgconf path from rt, abort."); return false; } @@ -162,7 +163,7 @@ auto GpgFrontend::GpgAdvancedOperator::ResetConfigures() -> bool { if (exit_code == 0) { success = true; } else { - SPDLOG_ERROR( + GF_CORE_LOG_ERROR( "gpgconf execute error, process stderr: {}, process stdout: {}", p_err, p_out); return; @@ -178,15 +179,15 @@ auto GpgFrontend::GpgAdvancedOperator::StartGpgAgent() -> bool { const auto gpg_agent_path = Module::RetrieveRTValueTypedOrDefault<>( "com.bktus.gpgfrontend.module.integrated.gnupg-info-gathering", "gnupg.gpg_agent_path", std::string{}); - SPDLOG_DEBUG("got gnupg agent path from rt: {}", gpg_agent_path); + GF_CORE_LOG_DEBUG("got gnupg agent path from rt: {}", gpg_agent_path); const auto home_path = Module::RetrieveRTValueTypedOrDefault<>( "com.bktus.gpgfrontend.module.integrated.gnupg-info-gathering", "gnupg.home_path", std::string{}); - SPDLOG_DEBUG("got gnupg home path from rt: {}", home_path); + GF_CORE_LOG_DEBUG("got gnupg home path from rt: {}", home_path); if (gpg_agent_path.empty()) { - SPDLOG_ERROR("cannot get valid gpg agent path from rt, abort."); + GF_CORE_LOG_ERROR("cannot get valid gpg agent path from rt, abort."); return false; } @@ -196,12 +197,12 @@ auto GpgFrontend::GpgAdvancedOperator::StartGpgAgent() -> bool { [&](int exit_code, const std::string &p_out, const std::string &p_err) { if (exit_code == 0) { success = true; - SPDLOG_INFO("start gpg-agent successfully"); + GF_CORE_LOG_INFO("start gpg-agent successfully"); } else if (exit_code == 2) { success = true; - SPDLOG_INFO("gpg-agent already started"); + GF_CORE_LOG_INFO("gpg-agent already started"); } else { - SPDLOG_ERROR( + GF_CORE_LOG_ERROR( "gpg-agent execute error, process stderr: {}, process stdout: " "{}", p_err, p_out); @@ -218,15 +219,15 @@ auto GpgFrontend::GpgAdvancedOperator::StartDirmngr() -> bool { const auto dirmngr_path = Module::RetrieveRTValueTypedOrDefault<>( "com.bktus.gpgfrontend.module.integrated.gnupg-info-gathering", "gnupg.dirmngr_path", std::string{}); - SPDLOG_DEBUG("got gnupg dirmngr path from rt: {}", dirmngr_path); + GF_CORE_LOG_DEBUG("got gnupg dirmngr path from rt: {}", dirmngr_path); const auto home_path = Module::RetrieveRTValueTypedOrDefault<>( "com.bktus.gpgfrontend.module.integrated.gnupg-info-gathering", "gnupg.home_path", std::string{}); - SPDLOG_DEBUG("got gnupg home path from rt: {}", home_path); + GF_CORE_LOG_DEBUG("got gnupg home path from rt: {}", home_path); if (dirmngr_path.empty()) { - SPDLOG_ERROR("cannot get valid dirmngr path from rt, abort."); + GF_CORE_LOG_ERROR("cannot get valid dirmngr path from rt, abort."); return false; } @@ -236,12 +237,12 @@ auto GpgFrontend::GpgAdvancedOperator::StartDirmngr() -> bool { [&](int exit_code, const std::string &p_out, const std::string &p_err) { if (exit_code == 0) { success = true; - SPDLOG_INFO("start dirmngr successfully"); + GF_CORE_LOG_INFO("start dirmngr successfully"); } else if (exit_code == 2) { success = true; - SPDLOG_INFO("dirmngr already started"); + GF_CORE_LOG_INFO("dirmngr already started"); } else { - SPDLOG_ERROR( + GF_CORE_LOG_ERROR( "dirmngr execute error, process stderr: {}, process stdout: {}", p_err, p_out); return; @@ -257,15 +258,15 @@ auto GpgFrontend::GpgAdvancedOperator::StartKeyBoxd() -> bool { const auto keyboxd_path = Module::RetrieveRTValueTypedOrDefault<>( "com.bktus.gpgfrontend.module.integrated.gnupg-info-gathering", "gnupg.keyboxd_path", std::string{}); - SPDLOG_DEBUG("got gnupg keyboxd path from rt: {}", keyboxd_path); + GF_CORE_LOG_DEBUG("got gnupg keyboxd path from rt: {}", keyboxd_path); const auto home_path = Module::RetrieveRTValueTypedOrDefault<>( "com.bktus.gpgfrontend.module.integrated.gnupg-info-gathering", "gnupg.home_path", std::string{}); - SPDLOG_DEBUG("got gnupg home path from rt: {}", home_path); + GF_CORE_LOG_DEBUG("got gnupg home path from rt: {}", home_path); if (keyboxd_path.empty()) { - SPDLOG_ERROR("cannot get valid keyboxd path from rt, abort."); + GF_CORE_LOG_ERROR("cannot get valid keyboxd path from rt, abort."); return false; } @@ -275,12 +276,12 @@ auto GpgFrontend::GpgAdvancedOperator::StartKeyBoxd() -> bool { [&](int exit_code, const std::string &p_out, const std::string &p_err) { if (exit_code == 0) { success = true; - SPDLOG_INFO("start keyboxd successfully"); + GF_CORE_LOG_INFO("start keyboxd successfully"); } else if (exit_code == 2) { success = true; - SPDLOG_INFO("keyboxd already started"); + GF_CORE_LOG_INFO("keyboxd already started"); } else { - SPDLOG_ERROR( + GF_CORE_LOG_ERROR( "keyboxd execute error, process stderr: {}, process stdout: {}", p_err, p_out); return; diff --git a/src/core/function/gpg/GpgBasicOperator.cpp b/src/core/function/gpg/GpgBasicOperator.cpp index 36bd25f6..fd81c093 100644 --- a/src/core/function/gpg/GpgBasicOperator.cpp +++ b/src/core/function/gpg/GpgBasicOperator.cpp @@ -192,15 +192,15 @@ void GpgBasicOperator::SetSigners(const KeyArgsList& signers, bool ascii) { gpgme_signers_clear(ctx); for (const GpgKey& key : signers) { - SPDLOG_DEBUG("key fpr: {}", key.GetFingerprint()); + GF_CORE_LOG_DEBUG("key fpr: {}", key.GetFingerprint()); if (key.IsHasActualSigningCapability()) { - SPDLOG_DEBUG("signer"); + GF_CORE_LOG_DEBUG("signer"); auto error = gpgme_signers_add(ctx, gpgme_key_t(key)); CheckGpgError(error); } } if (signers.size() != gpgme_signers_count(ctx_.DefaultContext())) - SPDLOG_DEBUG("not all signers added"); + GF_CORE_LOG_DEBUG("not all signers added"); } auto GpgBasicOperator::GetSigners(bool ascii) -> std::unique_ptr<KeyArgsList> { diff --git a/src/core/function/gpg/GpgCommandExecutor.cpp b/src/core/function/gpg/GpgCommandExecutor.cpp index fbcb1e4d..fa4b7dbd 100644 --- a/src/core/function/gpg/GpgCommandExecutor.cpp +++ b/src/core/function/gpg/GpgCommandExecutor.cpp @@ -51,35 +51,36 @@ auto BuildTaskFromExecCtx(const GpgCommandExecutor::ExecuteContext &context) return a + (a.length() > 0 ? " " : "") + b; }); - SPDLOG_DEBUG("building task: called cmd {} arguments size: {}", cmd, - arguments.size()); - - Thread::Task::TaskCallback result_callback = [cmd, joined_argument]( - int /*rtn*/, - const DataObjectPtr - &data_object) { - SPDLOG_DEBUG("data object args count of cmd executor result callback: {}", - data_object->GetObjectSize()); - if (!data_object->Check<int, std::string, GpgCommandExecutorCallback>()) { - throw std::runtime_error("invalid data object size"); - } - - auto exit_code = ExtractParams<int>(data_object, 0); - auto process_stdout = ExtractParams<std::string>(data_object, 1); - auto callback = ExtractParams<GpgCommandExecutorCallback>(data_object, 2); - - // call callback - SPDLOG_DEBUG( - "calling custom callback from caller of cmd {} {}, " - "exit_code: {}", - cmd, joined_argument, exit_code); - callback(exit_code, process_stdout, {}); - }; + GF_CORE_LOG_DEBUG("building task: called cmd {} arguments size: {}", cmd, + arguments.size()); + + Thread::Task::TaskCallback result_callback = + [cmd, joined_argument](int /*rtn*/, const DataObjectPtr &data_object) { + GF_CORE_LOG_DEBUG( + "data object args count of cmd executor result callback: {}", + data_object->GetObjectSize()); + if (!data_object + ->Check<int, std::string, GpgCommandExecutorCallback>()) { + throw std::runtime_error("invalid data object size"); + } + + auto exit_code = ExtractParams<int>(data_object, 0); + auto process_stdout = ExtractParams<std::string>(data_object, 1); + auto callback = + ExtractParams<GpgCommandExecutorCallback>(data_object, 2); + + // call callback + GF_CORE_LOG_DEBUG( + "calling custom callback from caller of cmd {} {}, " + "exit_code: {}", + cmd, joined_argument, exit_code); + callback(exit_code, process_stdout, {}); + }; Thread::Task::TaskRunnable runner = [joined_argument](const DataObjectPtr &data_object) -> int { - SPDLOG_DEBUG("process runner called, data object size: {}", - data_object->GetObjectSize()); + GF_CORE_LOG_DEBUG("process runner called, data object size: {}", + data_object->GetObjectSize()); if (!data_object->Check<std::string, std::vector<std::string>, GpgCommandExecutorInteractor, @@ -113,7 +114,7 @@ auto BuildTaskFromExecCtx(const GpgCommandExecutor::ExecuteContext &context) QObject::connect( cmd_process, &QProcess::started, [cmd, joined_argument]() -> void { - SPDLOG_DEBUG( + GF_CORE_LOG_DEBUG( "\n== Process Execute Started ==\nCommand: {}\nArguments: " "{}\n========================", cmd, joined_argument); @@ -124,11 +125,12 @@ auto BuildTaskFromExecCtx(const GpgCommandExecutor::ExecuteContext &context) QObject::connect( cmd_process, &QProcess::errorOccurred, [=](QProcess::ProcessError error) { - SPDLOG_ERROR("caught error while executing command: {} {}, error: {}", - cmd, joined_argument, error); + GF_CORE_LOG_ERROR( + "caught error while executing command: {} {}, error: {}", cmd, + joined_argument, error); }); - SPDLOG_DEBUG( + GF_CORE_LOG_DEBUG( "\n== Process Execute Ready ==\nCommand: {}\nArguments: " "{}\n========================", cmd, joined_argument); @@ -140,7 +142,7 @@ auto BuildTaskFromExecCtx(const GpgCommandExecutor::ExecuteContext &context) cmd_process->readAllStandardOutput().toStdString(); int exit_code = cmd_process->exitCode(); - SPDLOG_DEBUG( + GF_CORE_LOG_DEBUG( "\n==== Process Execution Summary ====\n" "Command: {}\n" "Arguments: {}\n" @@ -198,7 +200,7 @@ void GpgCommandExecutor::ExecuteSync(ExecuteContext context) { // current thread. if (QThread::currentThread()->currentThreadId() != target_task_runner->GetThread()->currentThreadId()) { - SPDLOG_TRACE("blocking until gpg command finish..."); + GF_CORE_LOG_TRACE("blocking until gpg command finish..."); // block until task finished // this is to keep reference vaild until task finished looper.exec(); @@ -208,7 +210,7 @@ void GpgCommandExecutor::ExecuteSync(ExecuteContext context) { void GpgCommandExecutor::ExecuteConcurrentlyAsync(ExecuteContexts contexts) { for (auto &context : contexts) { const auto &cmd = context.cmd; - SPDLOG_INFO("gpg concurrently called cmd {}", cmd); + GF_CORE_LOG_INFO("gpg concurrently called cmd {}", cmd); Thread::Task *task = BuildTaskFromExecCtx(context); @@ -232,15 +234,15 @@ void GpgCommandExecutor::ExecuteConcurrentlySync(ExecuteContexts contexts) { for (auto &context : contexts) { const auto &cmd = context.cmd; - SPDLOG_INFO("gpg concurrently called cmd {}", cmd); + GF_CORE_LOG_DEBUG("gpg concurrently called cmd {}", cmd); Thread::Task *task = BuildTaskFromExecCtx(context); QObject::connect(task, &Thread::Task::SignalTaskEnd, [&]() { --remaining_tasks; - SPDLOG_DEBUG("remaining tasks: {}", remaining_tasks); + GF_CORE_LOG_DEBUG("remaining tasks: {}", remaining_tasks); if (remaining_tasks <= 0) { - SPDLOG_DEBUG("no remaining task, quit"); + GF_CORE_LOG_DEBUG("no remaining task, quit"); looper.quit(); } }); @@ -265,7 +267,7 @@ void GpgCommandExecutor::ExecuteConcurrentlySync(ExecuteContexts contexts) { } if (need_looper) { - SPDLOG_TRACE("blocking until concurrent gpg commands finish..."); + GF_CORE_LOG_TRACE("blocking until concurrent gpg commands finish..."); // block until task finished // this is to keep reference vaild until task finished looper.exec(); diff --git a/src/core/function/gpg/GpgContext.cpp b/src/core/function/gpg/GpgContext.cpp index 7cde439c..30134191 100644 --- a/src/core/function/gpg/GpgContext.cpp +++ b/src/core/function/gpg/GpgContext.cpp @@ -109,7 +109,7 @@ class GpgContext::Impl { int fd) -> gpgme_error_t { std::string passphrase; - SPDLOG_DEBUG( + GF_CORE_LOG_DEBUG( "custom passphrase cb called, uid: {}, info: {}, last_was_bad: {}", uid_hint == nullptr ? "<empty>" : std::string{uid_hint}, passphrase_info == nullptr ? "<empty>" : std::string{passphrase_info}, @@ -128,7 +128,8 @@ class GpgContext::Impl { looper.exec(); auto passpahrase_size = passphrase.size(); - SPDLOG_DEBUG("get passphrase from pinentry size: {}", passpahrase_size); + GF_CORE_LOG_DEBUG("get passphrase from pinentry size: {}", + passpahrase_size); size_t off = 0; size_t res = 0; @@ -139,7 +140,7 @@ class GpgContext::Impl { res += gpgme_io_write(fd, "\n", 1); - SPDLOG_DEBUG("custom passphrase cd is about to return, res: {}", res); + GF_CORE_LOG_DEBUG("custom passphrase cd is about to return, res: {}", res); return res == passpahrase_size + 1 ? 0 : gpgme_error_from_errno(GPG_ERR_CANCELED); @@ -147,7 +148,7 @@ class GpgContext::Impl { static auto TestStatusCb(void *hook, const char *keyword, const char *args) -> gpgme_error_t { - SPDLOG_DEBUG("keyword {}", keyword); + GF_CORE_LOG_DEBUG("keyword {}", keyword); return GPG_ERR_NO_ERROR; } @@ -165,10 +166,10 @@ class GpgContext::Impl { const auto gpgme_version = Module::RetrieveRTValueTypedOrDefault<>( "core", "gpgme.version", std::string{"0.0.0"}); - SPDLOG_DEBUG("got gpgme version version from rt: {}", gpgme_version); + GF_CORE_LOG_DEBUG("got gpgme version version from rt: {}", gpgme_version); if (gpgme_get_keylist_mode(ctx) == 0) { - SPDLOG_ERROR( + GF_CORE_LOG_ERROR( "ctx is not a valid pointer, reported by gpgme_get_keylist_mode"); return false; } @@ -187,8 +188,8 @@ class GpgContext::Impl { const auto database_path = Module::RetrieveRTValueTypedOrDefault<>( "core", "gpgme.ctx.database_path", std::string{}); - SPDLOG_DEBUG("ctx set engine info, db path: {}, app path: {}", - database_path, app_path); + GF_CORE_LOG_DEBUG("ctx set engine info, db path: {}, app path: {}", + database_path, app_path); const char *app_path_c_str = app_path.c_str(); const char *db_path_c_str = database_path.c_str(); @@ -215,7 +216,8 @@ class GpgContext::Impl { assert(ctx != nullptr); if (args.custom_gpgconf && !args.custom_gpgconf_path.empty()) { - SPDLOG_DEBUG("set custom gpgconf path: {}", args.custom_gpgconf_path); + GF_CORE_LOG_DEBUG("set custom gpgconf path: {}", + args.custom_gpgconf_path); auto err = gpgme_ctx_set_engine_info(ctx, GPGME_PROTOCOL_GPGCONF, args.custom_gpgconf_path.c_str(), nullptr); @@ -227,12 +229,13 @@ class GpgContext::Impl { } // set context offline mode - SPDLOG_DEBUG("gpg context offline mode: {}", args_.offline_mode); + GF_CORE_LOG_DEBUG("gpg context offline mode: {}", args_.offline_mode); gpgme_set_offline(ctx, args_.offline_mode ? 1 : 0); // set option auto import missing key // invalid at offline mode - SPDLOG_DEBUG("gpg context auto import missing key: {}", args_.offline_mode); + GF_CORE_LOG_DEBUG("gpg context auto import missing key: {}", + args_.offline_mode); if (!args.offline_mode && args.auto_import_missing_key) { if (CheckGpgError(gpgme_set_ctx_flag(ctx, "auto-key-import", "1")) != GPG_ERR_NO_ERROR) { @@ -241,19 +244,19 @@ class GpgContext::Impl { } if (!set_ctx_key_list_mode(ctx)) { - SPDLOG_DEBUG("set ctx key list mode failed"); + GF_CORE_LOG_DEBUG("set ctx key list mode failed"); return false; } // for unit test if (args_.test_mode) { if (!SetPassphraseCb(ctx, TestPassphraseCb)) { - SPDLOG_ERROR("set passphrase cb failed, test"); + GF_CORE_LOG_ERROR("set passphrase cb failed, test"); return false; }; } else if (!args_.use_pinentry) { if (!SetPassphraseCb(ctx, CustomPassphraseCb)) { - SPDLOG_DEBUG("set passphrase cb failed, custom"); + GF_CORE_LOG_DEBUG("set passphrase cb failed, custom"); return false; } } @@ -265,7 +268,7 @@ class GpgContext::Impl { } if (!set_ctx_openpgp_engine_info(ctx)) { - SPDLOG_ERROR("set gpgme context openpgp engine info failed"); + GF_CORE_LOG_ERROR("set gpgme context openpgp engine info failed"); return false; } @@ -281,7 +284,7 @@ class GpgContext::Impl { binary_ctx_ref_ = p_ctx; if (!common_ctx_initialize(binary_ctx_ref_, args)) { - SPDLOG_ERROR("get new ctx failed, binary"); + GF_CORE_LOG_ERROR("get new ctx failed, binary"); return false; } @@ -292,7 +295,7 @@ class GpgContext::Impl { auto default_ctx_initialize(const GpgContextInitArgs &args) -> bool { gpgme_ctx_t p_ctx; if (CheckGpgError(gpgme_new(&p_ctx)) != GPG_ERR_NO_ERROR) { - SPDLOG_ERROR("get new ctx failed, default"); + GF_CORE_LOG_ERROR("get new ctx failed, default"); return false; } assert(p_ctx != nullptr); diff --git a/src/core/function/gpg/GpgFileOpera.cpp b/src/core/function/gpg/GpgFileOpera.cpp index ecb292e0..53cc6099 100644 --- a/src/core/function/gpg/GpgFileOpera.cpp +++ b/src/core/function/gpg/GpgFileOpera.cpp @@ -89,7 +89,7 @@ void GpgFileOpera::EncryptDirectory(std::vector<GpgKey> keys, GpgData data_in(ex); GpgData data_out(out_path, false); - SPDLOG_DEBUG("encrypt directory start"); + GF_CORE_LOG_DEBUG("encrypt directory start"); auto* ctx = ascii ? ctx_.DefaultContext() : ctx_.BinaryContext(); auto err = CheckGpgError(gpgme_op_encrypt(ctx, recipients.data(), @@ -97,14 +97,14 @@ void GpgFileOpera::EncryptDirectory(std::vector<GpgKey> keys, data_in, data_out)); data_object->Swap({GpgEncryptResult(gpgme_op_encrypt_result(ctx))}); - SPDLOG_DEBUG("encrypt directory finished, err: {}", err); + GF_CORE_LOG_DEBUG("encrypt directory finished, err: {}", err); return err; }, cb, "gpgme_op_encrypt", "2.1.0"); ArchiveFileOperator::NewArchive2DataExchanger( in_path, ex, [=](GFError err, const DataObjectPtr&) { - SPDLOG_DEBUG("new archive 2 fd operation, err: {}", err); + GF_CORE_LOG_DEBUG("new archive 2 fd operation, err: {}", err); }); } @@ -133,7 +133,7 @@ void GpgFileOpera::DecryptArchive(const std::filesystem::path& in_path, ArchiveFileOperator::ExtractArchiveFromDataExchanger( ex, out_path, [](GFError err, const DataObjectPtr&) { - SPDLOG_DEBUG("extract archive from fd operation, err: {}", err); + GF_CORE_LOG_DEBUG("extract archive from fd operation, err: {}", err); }); RunGpgOperaAsync( @@ -272,7 +272,7 @@ void GpgFileOpera::EncryptSignDirectory(KeyArgsList keys, ArchiveFileOperator::NewArchive2DataExchanger( in_path, ex, [=](GFError err, const DataObjectPtr&) { - SPDLOG_DEBUG("new archive 2 fd operation, err: {}", err); + GF_CORE_LOG_DEBUG("new archive 2 fd operation, err: {}", err); }); } @@ -306,7 +306,7 @@ void GpgFileOpera::DecryptVerifyArchive(const std::filesystem::path& in_path, ArchiveFileOperator::ExtractArchiveFromDataExchanger( ex, out_path, [](GFError err, const DataObjectPtr&) { - SPDLOG_DEBUG("extract archive from ex operation, err: {}", err); + GF_CORE_LOG_DEBUG("extract archive from ex operation, err: {}", err); }); RunGpgOperaAsync( @@ -373,7 +373,7 @@ void GpgFileOpera::EncryptDerectorySymmetric( ArchiveFileOperator::NewArchive2DataExchanger( in_path, ex, [=](GFError err, const DataObjectPtr&) { - SPDLOG_DEBUG("new archive 2 fd operation, err: {}", err); + GF_CORE_LOG_DEBUG("new archive 2 fd operation, err: {}", err); }); } } // namespace GpgFrontend
\ No newline at end of file diff --git a/src/core/function/gpg/GpgKeyGetter.cpp b/src/core/function/gpg/GpgKeyGetter.cpp index de8895d9..5c5ed039 100644 --- a/src/core/function/gpg/GpgKeyGetter.cpp +++ b/src/core/function/gpg/GpgKeyGetter.cpp @@ -43,7 +43,7 @@ class GpgKeyGetter::Impl : public SingletonFunctionObject<GpgKeyGetter::Impl> { public: explicit Impl(int channel) : SingletonFunctionObject<GpgKeyGetter::Impl>(channel) { - SPDLOG_DEBUG("called channel: {}", channel); + GF_CORE_LOG_DEBUG("called channel: {}", channel); } auto GetKey(const std::string& fpr, bool use_cache) -> GpgKey { @@ -56,7 +56,7 @@ class GpgKeyGetter::Impl : public SingletonFunctionObject<GpgKeyGetter::Impl> { gpgme_key_t p_key = nullptr; gpgme_get_key(ctx_.DefaultContext(), fpr.c_str(), &p_key, 1); if (p_key == nullptr) { - SPDLOG_WARN("GpgKeyGetter GetKey Private _p_key Null fpr", fpr); + GF_CORE_LOG_WARN("GpgKeyGetter GetKey Private _p_key Null fpr", fpr); return GetPubkey(fpr, true); } return GpgKey(std::move(p_key)); @@ -71,7 +71,8 @@ class GpgKeyGetter::Impl : public SingletonFunctionObject<GpgKeyGetter::Impl> { gpgme_key_t p_key = nullptr; gpgme_get_key(ctx_.DefaultContext(), fpr.c_str(), &p_key, 0); - if (p_key == nullptr) SPDLOG_WARN("GpgKeyGetter GetKey _p_key Null", fpr); + if (p_key == nullptr) + GF_CORE_LOG_WARN("GpgKeyGetter GetKey _p_key Null", fpr); return GpgKey(std::move(p_key)); } @@ -93,7 +94,7 @@ class GpgKeyGetter::Impl : public SingletonFunctionObject<GpgKeyGetter::Impl> { } auto FlushKeyCache() -> bool { - SPDLOG_DEBUG("flush key channel called, channel: {}", GetChannel()); + GF_CORE_LOG_DEBUG("flush key channel called, channel: {}", GetChannel()); // clear the keys cache keys_cache_.clear(); @@ -126,8 +127,9 @@ class GpgKeyGetter::Impl : public SingletonFunctionObject<GpgKeyGetter::Impl> { } } - SPDLOG_DEBUG("flush key channel cache address: {} object address: {}", - static_cast<void*>(&keys_cache_), static_cast<void*>(this)); + GF_CORE_LOG_DEBUG("flush key channel cache address: {} object address: {}", + static_cast<void*>(&keys_cache_), + static_cast<void*>(this)); // for debug assert(CheckGpgError2ErrCode(err, GPG_ERR_EOF) == GPG_ERR_EOF); @@ -135,7 +137,7 @@ class GpgKeyGetter::Impl : public SingletonFunctionObject<GpgKeyGetter::Impl> { err = gpgme_op_keylist_end(ctx_.DefaultContext()); assert(CheckGpgError2ErrCode(err, GPG_ERR_EOF) == GPG_ERR_NO_ERROR); - SPDLOG_DEBUG("flush key channel done, channel: {}", GetChannel()); + GF_CORE_LOG_DEBUG("flush key channel done, channel: {}", GetChannel()); return true; } @@ -209,7 +211,7 @@ class GpgKeyGetter::Impl : public SingletonFunctionObject<GpgKeyGetter::Impl> { GpgKeyGetter::GpgKeyGetter(int channel) : SingletonFunctionObject<GpgKeyGetter>(channel), p_(SecureCreateUniqueObject<Impl>(channel)) { - SPDLOG_DEBUG("called channel: {}", channel); + GF_CORE_LOG_DEBUG("called channel: {}", channel); } GpgKeyGetter::~GpgKeyGetter() = default; diff --git a/src/core/function/gpg/GpgKeyImportExporter.cpp b/src/core/function/gpg/GpgKeyImportExporter.cpp index a2db25e1..e9ca3e84 100644 --- a/src/core/function/gpg/GpgKeyImportExporter.cpp +++ b/src/core/function/gpg/GpgKeyImportExporter.cpp @@ -96,8 +96,8 @@ auto GpgKeyImportExporter::ExportKeys(KeyIdArgsListPtr& uid_list, delete[] keys_array; - SPDLOG_DEBUG("export keys read_bytes: {}", - gpgme_data_seek(data_out, 0, SEEK_END)); + GF_CORE_LOG_DEBUG("export keys read_bytes: {}", + gpgme_data_seek(data_out, 0, SEEK_END)); auto temp_out_buffer = data_out.Read2Buffer(); @@ -151,7 +151,7 @@ auto GpgKeyImportExporter::ExportAllKeys(KeyIdArgsListPtr& uid_list, auto GpgKeyImportExporter::ExportSecretKey(const GpgKey& key, ByteArrayPtr& out_buffer) const -> bool { - SPDLOG_DEBUG("export secret key: {}", key.GetId().c_str()); + GF_CORE_LOG_DEBUG("export secret key: {}", key.GetId().c_str()); gpgme_key_t target_key[2] = {static_cast<gpgme_key_t>(key), nullptr}; @@ -172,8 +172,8 @@ auto GpgKeyImportExporter::ExportKey(const GpgKey& key, auto err = gpgme_op_export(ctx_.DefaultContext(), key.GetId().c_str(), 0, data_out); - SPDLOG_DEBUG("export keys read_bytes: {}", - gpgme_data_seek(data_out, 0, SEEK_END)); + GF_CORE_LOG_DEBUG("export keys read_bytes: {}", + gpgme_data_seek(data_out, 0, SEEK_END)); auto temp_out_buffer = data_out.Read2Buffer(); std::swap(out_buffer, temp_out_buffer); @@ -187,7 +187,7 @@ auto GpgKeyImportExporter::ExportKeyOpenSSH(const GpgKey& key, auto err = gpgme_op_export(ctx_.DefaultContext(), key.GetId().c_str(), GPGME_EXPORT_MODE_SSH, data_out); - SPDLOG_DEBUG("read_bytes: {}", gpgme_data_seek(data_out, 0, SEEK_END)); + GF_CORE_LOG_DEBUG("read_bytes: {}", gpgme_data_seek(data_out, 0, SEEK_END)); auto temp_out_buffer = data_out.Read2Buffer(); std::swap(out_buffer, temp_out_buffer); @@ -200,7 +200,7 @@ auto GpgKeyImportExporter::ExportSecretKeyShortest( auto err = gpgme_op_export(ctx_.DefaultContext(), key.GetId().c_str(), GPGME_EXPORT_MODE_MINIMAL, data_out); - SPDLOG_DEBUG("read_bytes: {}", gpgme_data_seek(data_out, 0, SEEK_END)); + GF_CORE_LOG_DEBUG("read_bytes: {}", gpgme_data_seek(data_out, 0, SEEK_END)); auto temp_out_buffer = data_out.Read2Buffer(); std::swap(out_buffer, temp_out_buffer); diff --git a/src/core/function/gpg/GpgKeyManager.cpp b/src/core/function/gpg/GpgKeyManager.cpp index b2de0ed7..38ebd040 100644 --- a/src/core/function/gpg/GpgKeyManager.cpp +++ b/src/core/function/gpg/GpgKeyManager.cpp @@ -100,58 +100,59 @@ auto GpgFrontend::GpgKeyManager::SetExpire( auto GpgFrontend::GpgKeyManager::SetOwnerTrustLevel(const GpgKey& key, int trust_level) -> bool { if (trust_level < 0 || trust_level > 5) { - SPDLOG_ERROR("illegal owner trust level: {}", trust_level); + GF_CORE_LOG_ERROR("illegal owner trust level: {}", trust_level); } - AutomatonNextStateHandler next_state_handler = - [](AutomatonState state, std::string status, std::string args) { - SPDLOG_DEBUG("next_state_handler state: {}, gpg_status: {}, args: {}", - state, status, args); - std::vector<std::string> tokens; - boost::split(tokens, args, boost::is_any_of(" ")); + AutomatonNextStateHandler next_state_handler = [](AutomatonState state, + std::string status, + std::string args) { + GF_CORE_LOG_DEBUG("next_state_handler state: {}, gpg_status: {}, args: {}", + state, status, args); + std::vector<std::string> tokens; + boost::split(tokens, args, boost::is_any_of(" ")); - switch (state) { - case AS_START: - if (status == "GET_LINE" && args == "keyedit.prompt") { - return AS_COMMAND; - } - return AS_ERROR; - case AS_COMMAND: - if (status == "GET_LINE" && args == "edit_ownertrust.value") { - return AS_VALUE; - } - return AS_ERROR; - case AS_VALUE: - if (status == "GET_LINE" && args == "keyedit.prompt") { - return AS_QUIT; - } else if (status == "GET_BOOL" && - args == "edit_ownertrust.set_ultimate.okay") { - return AS_REALLY_ULTIMATE; - } - return AS_ERROR; - case AS_REALLY_ULTIMATE: - if (status == "GET_LINE" && args == "keyedit.prompt") { - return AS_QUIT; - } - return AS_ERROR; - case AS_QUIT: - if (status == "GET_LINE" && args == "keyedit.save.okay") { - return AS_SAVE; - } - return AS_ERROR; - case AS_ERROR: - if (status == "GET_LINE" && args == "keyedit.prompt") { - return AS_QUIT; - } - return AS_ERROR; - default: - return AS_ERROR; - }; - }; + switch (state) { + case AS_START: + if (status == "GET_LINE" && args == "keyedit.prompt") { + return AS_COMMAND; + } + return AS_ERROR; + case AS_COMMAND: + if (status == "GET_LINE" && args == "edit_ownertrust.value") { + return AS_VALUE; + } + return AS_ERROR; + case AS_VALUE: + if (status == "GET_LINE" && args == "keyedit.prompt") { + return AS_QUIT; + } else if (status == "GET_BOOL" && + args == "edit_ownertrust.set_ultimate.okay") { + return AS_REALLY_ULTIMATE; + } + return AS_ERROR; + case AS_REALLY_ULTIMATE: + if (status == "GET_LINE" && args == "keyedit.prompt") { + return AS_QUIT; + } + return AS_ERROR; + case AS_QUIT: + if (status == "GET_LINE" && args == "keyedit.save.okay") { + return AS_SAVE; + } + return AS_ERROR; + case AS_ERROR: + if (status == "GET_LINE" && args == "keyedit.prompt") { + return AS_QUIT; + } + return AS_ERROR; + default: + return AS_ERROR; + }; + }; AutomatonActionHandler action_handler = [trust_level](AutomatonHandelStruct& handler, AutomatonState state) { - SPDLOG_DEBUG("action_handler state: {}", state); + GF_CORE_LOG_DEBUG("action_handler state: {}", state); switch (state) { case AS_COMMAND: return std::string("trust"); @@ -194,16 +195,17 @@ auto GpgFrontend::GpgKeyManager::interactor_cb_fnc(void* handle, auto handle_struct = static_cast<AutomatonHandelStruct*>(handle); std::string status_s = status; std::string args_s = args; - SPDLOG_DEBUG("cb start status: {}, args: {}, fd: {}, handle struct state: {}", - status_s, args_s, fd, handle_struct->CuurentStatus()); + GF_CORE_LOG_DEBUG( + "cb start status: {}, args: {}, fd: {}, handle struct state: {}", + status_s, args_s, fd, handle_struct->CuurentStatus()); if (status_s == "KEY_CONSIDERED") { std::vector<std::string> tokens; boost::split(tokens, args, boost::is_any_of(" ")); if (tokens.empty() || tokens[0] != handle_struct->KeyFpr()) { - SPDLOG_ERROR("handle struct key fpr {} mismatch token: {}, exit...", - handle_struct->KeyFpr(), tokens[0]); + GF_CORE_LOG_ERROR("handle struct key fpr {} mismatch token: {}, exit...", + handle_struct->KeyFpr(), tokens[0]); return -1; } @@ -211,13 +213,13 @@ auto GpgFrontend::GpgKeyManager::interactor_cb_fnc(void* handle, } if (status_s == "GOT_IT" || status_s.empty()) { - SPDLOG_DEBUG("status GOT_IT, continue..."); + GF_CORE_LOG_DEBUG("status GOT_IT, continue..."); return 0; } AutomatonState next_state = handle_struct->NextState(status_s, args_s); if (next_state == AS_ERROR) { - SPDLOG_DEBUG("handle struct next state caught error, skipping..."); + GF_CORE_LOG_DEBUG("handle struct next state caught error, skipping..."); return GPG_ERR_FALSE; } @@ -228,8 +230,8 @@ auto GpgFrontend::GpgKeyManager::interactor_cb_fnc(void* handle, // set state and preform action handle_struct->SetStatus(next_state); Command cmd = handle_struct->Action(); - SPDLOG_DEBUG("handle struct action done, next state: {}, action cmd: {}", - next_state, cmd); + GF_CORE_LOG_DEBUG("handle struct action done, next state: {}, action cmd: {}", + next_state, cmd); if (!cmd.empty()) { gpgme_io_write(fd, cmd.c_str(), cmd.size()); gpgme_io_write(fd, "\n", 1); diff --git a/src/core/function/gpg/GpgKeyOpera.cpp b/src/core/function/gpg/GpgKeyOpera.cpp index c48b75f3..49703781 100644 --- a/src/core/function/gpg/GpgKeyOpera.cpp +++ b/src/core/function/gpg/GpgKeyOpera.cpp @@ -68,7 +68,7 @@ void GpgKeyOpera::DeleteKeys(GpgFrontend::KeyIdArgsListPtr key_ids) { GPGME_DELETE_ALLOW_SECRET | GPGME_DELETE_FORCE)); assert(gpg_err_code(err) == GPG_ERR_NO_ERROR); } else { - SPDLOG_WARN("GpgKeyOpera DeleteKeys get key failed", tmp); + GF_CORE_LOG_WARN("GpgKeyOpera DeleteKeys get key failed", tmp); } } } @@ -91,7 +91,7 @@ auto GpgKeyOpera::SetExpire(const GpgKey& key, const SubkeyId& subkey_fpr, std::chrono::system_clock::now()); } - SPDLOG_DEBUG(key.GetId(), subkey_fpr, expires_time); + GF_CORE_LOG_DEBUG(key.GetId(), subkey_fpr, expires_time); GpgError err; if (key.GetFingerprint() == subkey_fpr || subkey_fpr.empty()) { @@ -124,12 +124,12 @@ void GpgKeyOpera::GenerateRevokeCert(const GpgKey& key, "--gen-revoke", key.GetFingerprint()}, [=](int exit_code, const std::string& p_out, const std::string& p_err) { if (exit_code != 0) { - SPDLOG_ERROR( + GF_CORE_LOG_ERROR( "gnupg gen revoke execute error, process stderr: {}, process " "stdout: {}", p_err, p_out); } else { - SPDLOG_DEBUG( + GF_CORE_LOG_DEBUG( "gnupg gen revoke exit_code: {}, process stdout size: {}", exit_code, p_out.size()); } @@ -139,7 +139,7 @@ void GpgKeyOpera::GenerateRevokeCert(const GpgKey& key, // Code From Gpg4Win while (proc->canReadLine()) { const QString line = QString::fromUtf8(proc->readLine()).trimmed(); - SPDLOG_DEBUG("line: {}", line.toStdString()); + GF_CORE_LOG_DEBUG("line: {}", line.toStdString()); if (line == QLatin1String("[GNUPG:] GET_BOOL gen_revoke.okay")) { proc->write("y\n"); } else if (line == QLatin1String("[GNUPG:] GET_LINE " @@ -174,8 +174,8 @@ void GpgKeyOpera::GenerateKey(const std::shared_ptr<GenKeyInfo>& params, const char* userid = userid_utf8.c_str(); auto algo_utf8 = params->GetAlgo() + params->GetKeySizeStr(); - SPDLOG_DEBUG("params: {} {}", params->GetAlgo(), - params->GetKeySizeStr()); + GF_CORE_LOG_DEBUG("params: {} {}", params->GetAlgo(), + params->GetKeySizeStr()); const char* algo = algo_utf8.c_str(); unsigned long expires = 0; @@ -193,7 +193,8 @@ void GpgKeyOpera::GenerateKey(const std::shared_ptr<GenKeyInfo>& params, if (params->IsNonExpired()) flags |= GPGME_CREATE_NOEXPIRE; if (params->IsNoPassPhrase()) flags |= GPGME_CREATE_NOPASSWD; - SPDLOG_DEBUG("key generation args: {}", userid, algo, expires, flags); + GF_CORE_LOG_DEBUG("key generation args: {}", userid, algo, expires, + flags); err = gpgme_op_createkey(ctx.DefaultContext(), userid, algo, 0, expires, nullptr, flags); @@ -222,8 +223,8 @@ void GpgKeyOpera::GenerateSubkey(const GpgKey& key, [key, &ctx = ctx_, params](const DataObjectPtr&) -> GpgError { if (!params->IsSubKey()) return GPG_ERR_CANCELED; - SPDLOG_DEBUG("generate subkey algo {} key size {}", params->GetAlgo(), - params->GetKeySizeStr()); + GF_CORE_LOG_DEBUG("generate subkey algo {} key size {}", + params->GetAlgo(), params->GetKeySizeStr()); auto algo_utf8 = (params->GetAlgo() + params->GetKeySizeStr()); const char* algo = algo_utf8.c_str(); @@ -242,7 +243,8 @@ void GpgKeyOpera::GenerateSubkey(const GpgKey& key, if (params->IsNonExpired()) flags |= GPGME_CREATE_NOEXPIRE; if (params->IsNoPassPhrase()) flags |= GPGME_CREATE_NOPASSWD; - SPDLOG_DEBUG("args: {} {} {} {}", key.GetId(), algo, expires, flags); + GF_CORE_LOG_DEBUG("args: {} {} {} {}", key.GetId(), algo, expires, + flags); auto err = gpgme_op_createsubkey(ctx.DefaultContext(), static_cast<gpgme_key_t>(key), algo, 0, @@ -267,10 +269,10 @@ auto GpgKeyOpera::ModifyTOFUPolicy(const GpgKey& key, -> GpgError { const auto gnupg_version = Module::RetrieveRTValueTypedOrDefault<>( "core", "gpgme.ctx.gnupg_version", std::string{"2.0.0"}); - SPDLOG_DEBUG("got gnupg version from rt: {}", gnupg_version); + GF_CORE_LOG_DEBUG("got gnupg version from rt: {}", gnupg_version); if (CompareSoftwareVersion(gnupg_version, "2.1.10") < 0) { - SPDLOG_ERROR("operator not support"); + GF_CORE_LOG_ERROR("operator not support"); return GPG_ERR_NOT_SUPPORTED; } diff --git a/src/core/function/gpg/GpgUIDOperator.cpp b/src/core/function/gpg/GpgUIDOperator.cpp index 4610c504..63afb40c 100644 --- a/src/core/function/gpg/GpgUIDOperator.cpp +++ b/src/core/function/gpg/GpgUIDOperator.cpp @@ -60,7 +60,7 @@ auto GpgUIDOperator::SetPrimaryUID(const GpgKey& key, const std::string& uid) auto GpgUIDOperator::AddUID(const GpgKey& key, const std::string& name, const std::string& comment, const std::string& email) -> bool { - SPDLOG_DEBUG("new uuid: {} {} {}", name, comment, email); + GF_CORE_LOG_DEBUG("new uuid: {} {} {}", name, comment, email); auto uid = boost::format("%1%(%2%)<%3%>") % name % comment % email; return AddUID(key, uid.str()); } diff --git a/src/core/function/result_analyse/GpgEncryptResultAnalyse.cpp b/src/core/function/result_analyse/GpgEncryptResultAnalyse.cpp index 80ec6233..4bb0a5a9 100644 --- a/src/core/function/result_analyse/GpgEncryptResultAnalyse.cpp +++ b/src/core/function/result_analyse/GpgEncryptResultAnalyse.cpp @@ -37,7 +37,7 @@ GpgFrontend::GpgEncryptResultAnalyse::GpgEncryptResultAnalyse( : error_(error), result_(result) {} void GpgFrontend::GpgEncryptResultAnalyse::doAnalyse() { - SPDLOG_DEBUG("start encrypt result analyse"); + GF_CORE_LOG_DEBUG("start encrypt result analyse"); stream_ << "[#] " << _("Encrypt Operation") << " "; diff --git a/src/core/function/result_analyse/GpgSignResultAnalyse.cpp b/src/core/function/result_analyse/GpgSignResultAnalyse.cpp index 53704528..2c53d329 100644 --- a/src/core/function/result_analyse/GpgSignResultAnalyse.cpp +++ b/src/core/function/result_analyse/GpgSignResultAnalyse.cpp @@ -39,7 +39,7 @@ GpgSignResultAnalyse::GpgSignResultAnalyse(GpgError error, GpgSignResult result) void GpgSignResultAnalyse::doAnalyse() { auto *result = this->result_.GetRaw(); - SPDLOG_DEBUG("start sign result analyse"); + GF_CORE_LOG_DEBUG("start sign result analyse"); stream_ << "[#] " << _("Sign Operation") << " "; @@ -53,14 +53,14 @@ void GpgSignResultAnalyse::doAnalyse() { if (result != nullptr && (result->signatures != nullptr || result->invalid_signers != nullptr)) { - SPDLOG_DEBUG("sign result analyse getting result"); + GF_CORE_LOG_DEBUG("sign result analyse getting result"); stream_ << "------------>" << std::endl; auto *new_sign = result->signatures; while (new_sign != nullptr) { stream_ << "[>]" << _("New Signature") << ": " << std::endl; - SPDLOG_DEBUG("signers fingerprint: ", new_sign->fpr); + GF_CORE_LOG_DEBUG("signers fingerprint: ", new_sign->fpr); stream_ << " " << _("Sign Mode") << ": "; if (new_sign->type == GPGME_SIG_MODE_NORMAL) { @@ -96,7 +96,7 @@ void GpgSignResultAnalyse::doAnalyse() { new_sign = new_sign->next; } - SPDLOG_DEBUG("sign result analyse getting invalid signer"); + GF_CORE_LOG_DEBUG("sign result analyse getting invalid signer"); auto *invalid_signer = result->invalid_signers; diff --git a/src/core/function/result_analyse/GpgVerifyResultAnalyse.cpp b/src/core/function/result_analyse/GpgVerifyResultAnalyse.cpp index 449306b7..064dc087 100644 --- a/src/core/function/result_analyse/GpgVerifyResultAnalyse.cpp +++ b/src/core/function/result_analyse/GpgVerifyResultAnalyse.cpp @@ -43,7 +43,7 @@ GpgFrontend::GpgVerifyResultAnalyse::GpgVerifyResultAnalyse( void GpgFrontend::GpgVerifyResultAnalyse::doAnalyse() { auto *result = this->result_.GetRaw(); - SPDLOG_DEBUG("started"); + GF_CORE_LOG_DEBUG("started"); stream_ << "[#] " << _("Verify Operation") << " "; diff --git a/src/core/model/DataObject.h b/src/core/model/DataObject.h index 56c86bf6..6b41a051 100644 --- a/src/core/model/DataObject.h +++ b/src/core/model/DataObject.h @@ -70,7 +70,7 @@ class GPGFRONTEND_CORE_EXPORT DataObject { for (size_t i = 0; i < type_list.size(); ++i) { if (std::type_index(*type_list[i]) != std::type_index((*this)[i].type())) { - SPDLOG_ERROR( + GF_CORE_LOG_ERROR( "value of index {} in data object is type: {}, " "not expected type: {}", i, ((*this)[i]).type().name(), type_list[i]->name()); diff --git a/src/core/model/GFDataExchanger.cpp b/src/core/model/GFDataExchanger.cpp index c2aca929..70a6498e 100644 --- a/src/core/model/GFDataExchanger.cpp +++ b/src/core/model/GFDataExchanger.cpp @@ -28,6 +28,8 @@ #include "GFDataExchanger.h" +#include "core/utils/LogUtils.h" + namespace GpgFrontend { auto GFDataExchanger::Write(const std::byte* buffer, size_t size) -> ssize_t { @@ -47,7 +49,7 @@ auto GFDataExchanger::Write(const std::byte* buffer, size_t size) -> ssize_t { write_bytes++; } } catch (...) { - SPDLOG_ERROR( + GF_CORE_LOG_ERROR( "gf data exchanger caught exception when it writes to queue, abort..."); } diff --git a/src/core/model/GpgDecryptResult.cpp b/src/core/model/GpgDecryptResult.cpp index a0719c0c..3568bfd9 100644 --- a/src/core/model/GpgDecryptResult.cpp +++ b/src/core/model/GpgDecryptResult.cpp @@ -55,7 +55,7 @@ auto GpgDecryptResult::Recipients() -> std::vector<GpgRecipient> { try { result.emplace_back(reci); } catch (...) { - SPDLOG_ERROR( + GF_CORE_LOG_ERROR( "caught exception when processing invalid_recipients, " "maybe nullptr of fpr"); } diff --git a/src/core/model/GpgEncryptResult.cpp b/src/core/model/GpgEncryptResult.cpp index 6f39ed68..f135dac9 100644 --- a/src/core/model/GpgEncryptResult.cpp +++ b/src/core/model/GpgEncryptResult.cpp @@ -55,7 +55,7 @@ auto GpgEncryptResult::InvalidRecipients() try { result.emplace_back(std::string{invalid_key->fpr}, invalid_key->reason); } catch (...) { - SPDLOG_ERROR( + GF_CORE_LOG_ERROR( "caught exception when processing invalid_recipients, " "maybe nullptr of fpr"); } diff --git a/src/core/model/GpgGenKeyInfo.cpp b/src/core/model/GpgGenKeyInfo.cpp index 1933a1db..15eb9b10 100644 --- a/src/core/model/GpgGenKeyInfo.cpp +++ b/src/core/model/GpgGenKeyInfo.cpp @@ -32,10 +32,12 @@ #include <boost/format.hpp> #include <cassert> +#include "core/utils/LogUtils.h" + namespace GpgFrontend { void GenKeyInfo::SetAlgo(const GenKeyInfo::KeyGenAlgo &m_algo) { - SPDLOG_DEBUG("set algo name: {}", m_algo.first); + GF_CORE_LOG_DEBUG("set algo name: {}", m_algo.first); // Check algo if supported std::string algo_args = m_algo.second; if (standalone_) { diff --git a/src/core/model/GpgSignResult.cpp b/src/core/model/GpgSignResult.cpp index aa35e57a..90d337b7 100644 --- a/src/core/model/GpgSignResult.cpp +++ b/src/core/model/GpgSignResult.cpp @@ -55,7 +55,7 @@ auto GpgSignResult::InvalidSigners() try { result.emplace_back(std::string{invalid_key->fpr}, invalid_key->reason); } catch (...) { - SPDLOG_ERROR( + GF_CORE_LOG_ERROR( "caught exception when processing invalid_signers, " "maybe nullptr of fpr"); } diff --git a/src/core/module/Event.cpp b/src/core/module/Event.cpp index 6bd6eae5..b2a4417a 100644 --- a/src/core/module/Event.cpp +++ b/src/core/module/Event.cpp @@ -42,7 +42,7 @@ class Event::Impl { for (const auto& param : params) { AddParameter(param); } - SPDLOG_DEBUG("create event {}", event_identifier_); + GF_CORE_LOG_DEBUG("create event {}", event_identifier_); } auto operator[](const std::string& key) const @@ -80,19 +80,20 @@ class Event::Impl { void ExecuteCallback(ListenerIdentifier listener_id, const DataObjectPtr& data_object) { - SPDLOG_DEBUG("try to execute callback for event {} with listener {}", - event_identifier_, listener_id); + GF_CORE_LOG_DEBUG("try to execute callback for event {} with listener {}", + event_identifier_, listener_id); if (callback_) { - SPDLOG_DEBUG("executing callback for event {} with listener {}", - event_identifier_, listener_id); + GF_CORE_LOG_DEBUG("executing callback for event {} with listener {}", + event_identifier_, listener_id); if (!QMetaObject::invokeMethod( callback_thread_, [callback = callback_, event_identifier = event_identifier_, listener_id, data_object]() { callback(event_identifier, listener_id, data_object); })) { - SPDLOG_ERROR("failed to invoke callback for event {} with listener {}", - event_identifier_, listener_id); + GF_CORE_LOG_ERROR( + "failed to invoke callback for event {} with listener {}", + event_identifier_, listener_id); } } } diff --git a/src/core/module/GlobalModuleContext.cpp b/src/core/module/GlobalModuleContext.cpp index e2f58c92..6222a97d 100644 --- a/src/core/module/GlobalModuleContext.cpp +++ b/src/core/module/GlobalModuleContext.cpp @@ -62,7 +62,7 @@ class GlobalModuleContext::Impl { auto module_info_opt = search_module_register_table(module->GetModuleIdentifier()); if (!module_info_opt.has_value()) { - SPDLOG_ERROR( + GF_CORE_LOG_ERROR( "cannot find module id {} at register table, fallbacking to " "default " "channel", @@ -94,18 +94,20 @@ class GlobalModuleContext::Impl { } auto RegisterModule(const ModulePtr& module) -> bool { - SPDLOG_DEBUG("attempting to register module: {}", - module->GetModuleIdentifier()); + GF_CORE_LOG_DEBUG("attempting to register module: {}", + module->GetModuleIdentifier()); // Check if the module is null or already registered. if (module == nullptr || module_register_table_.find(module->GetModuleIdentifier()) != module_register_table_.end()) { - SPDLOG_ERROR("module is null or have already registered this module"); + GF_CORE_LOG_ERROR( + "module is null or have already registered this module"); return false; } if (!module->Register()) { - SPDLOG_ERROR("register module {} failed", module->GetModuleIdentifier()); + GF_CORE_LOG_ERROR("register module {} failed", + module->GetModuleIdentifier()); return false; } @@ -124,18 +126,19 @@ class GlobalModuleContext::Impl { // Register the module with its identifier. module_register_table_[module->GetModuleIdentifier()] = register_info; - SPDLOG_DEBUG("successfully registered module: {}", - module->GetModuleIdentifier()); + GF_CORE_LOG_DEBUG("successfully registered module: {}", + module->GetModuleIdentifier()); return true; } auto ActiveModule(ModuleIdentifier module_id) -> bool { - SPDLOG_DEBUG("attempting to activate module: {}", module_id); + GF_CORE_LOG_DEBUG("attempting to activate module: {}", module_id); // Search for the module in the register table. auto module_info_opt = search_module_register_table(module_id); if (!module_info_opt.has_value()) { - SPDLOG_ERROR("cannot find module id {} at register table", module_id); + GF_CORE_LOG_ERROR("cannot find module id {} at register table", + module_id); return false; } @@ -144,7 +147,7 @@ class GlobalModuleContext::Impl { // try to get module from module info auto module = module_info->module; if (module == nullptr) { - SPDLOG_ERROR( + GF_CORE_LOG_ERROR( "module id {} at register table is releated to a null module", module_id); return false; @@ -156,19 +159,19 @@ class GlobalModuleContext::Impl { module_info->activate = true; } - SPDLOG_DEBUG("module activation status: {}", module_info->activate); + GF_CORE_LOG_DEBUG("module activation status: {}", module_info->activate); return module_info->activate; } auto ListenEvent(ModuleIdentifier module_id, EventIdentifier event) -> bool { - SPDLOG_DEBUG("module: {} is attempting to listen to event {}", module_id, - event); + GF_CORE_LOG_DEBUG("module: {} is attempting to listen to event {}", + module_id, event); // Check if the event exists, if not, create it. auto met_it = module_events_table_.find(event); if (met_it == module_events_table_.end()) { module_events_table_[event] = std::unordered_set<ModuleIdentifier>(); met_it = module_events_table_.find(event); - SPDLOG_INFO("new event {} of module system created", event); + GF_CORE_LOG_INFO("new event {} of module system created", event); } auto& listeners_set = met_it->second; @@ -184,7 +187,8 @@ class GlobalModuleContext::Impl { // Search for the module in the register table. auto module_info_opt = search_module_register_table(module_id); if (!module_info_opt.has_value()) { - SPDLOG_ERROR("cannot find module id {} at register table", module_id); + GF_CORE_LOG_ERROR("cannot find module id {} at register table", + module_id); return false; } @@ -199,13 +203,13 @@ class GlobalModuleContext::Impl { auto TriggerEvent(const EventRefrernce& event) -> bool { auto event_id = event->GetIdentifier(); - SPDLOG_DEBUG("attempting to trigger event: {}", event_id); + GF_CORE_LOG_DEBUG("attempting to trigger event: {}", event_id); // Find the set of listeners associated with the given event in the table auto met_it = module_events_table_.find(event_id); if (met_it == module_events_table_.end()) { // Log a warning if the event is not registered and nobody is listening - SPDLOG_WARN( + GF_CORE_LOG_WARN( "event {} is not listening by anyone and not registered as well", event_id); return false; @@ -217,14 +221,14 @@ class GlobalModuleContext::Impl { // Check if the set of listeners is empty if (listeners_set.empty()) { // Log a warning if nobody is listening to this event - SPDLOG_WARN("event {} is not listening by anyone", - event->GetIdentifier()); + GF_CORE_LOG_WARN("event {} is not listening by anyone", + event->GetIdentifier()); return false; } // Log the number of listeners for this event - SPDLOG_DEBUG("event {}'s current listeners size: {}", - event->GetIdentifier(), listeners_set.size()); + GF_CORE_LOG_DEBUG("event {}'s current listeners size: {}", + event->GetIdentifier(), listeners_set.size()); // Iterate through each listener and execute the corresponding module for (const auto& listener_module_id : listeners_set) { @@ -233,8 +237,8 @@ class GlobalModuleContext::Impl { // Log an error if the module is not found in the registration table if (!module_info_opt.has_value()) { - SPDLOG_ERROR("cannot find module id {} at register table", - listener_module_id); + GF_CORE_LOG_ERROR("cannot find module id {} at register table", + listener_module_id); continue; } @@ -242,9 +246,10 @@ class GlobalModuleContext::Impl { auto module_info = module_info_opt.value(); auto module = module_info->module; - SPDLOG_DEBUG("module {} is listening to event {}, activate state: {}", - module_info->module->GetModuleIdentifier(), - event->GetIdentifier(), module_info->activate); + GF_CORE_LOG_DEBUG( + "module {} is listening to event {}, activate state: {}", + module_info->module->GetModuleIdentifier(), event->GetIdentifier(), + module_info->activate); // Check if the module is activated if (!module_info->activate) continue; @@ -256,7 +261,7 @@ class GlobalModuleContext::Impl { int code, DataObjectPtr) { if (code < 0) { // Log an error if the module execution fails - SPDLOG_ERROR( + GF_CORE_LOG_ERROR( "module {} execution failed of event {}: exec return code {}", listener_module_id, event_id, code); } diff --git a/src/core/thread/FileReadTask.cpp b/src/core/thread/FileReadTask.cpp index 906ea188..98dbf718 100644 --- a/src/core/thread/FileReadTask.cpp +++ b/src/core/thread/FileReadTask.cpp @@ -49,18 +49,18 @@ FileReadTask::FileReadTask(std::string path) : Task("file_read_task") { void FileReadTask::Run() { if (is_regular_file(read_file_path_)) { - SPDLOG_DEBUG("read open file: {}", read_file_path_.u8string()); + GF_CORE_LOG_DEBUG("read open file: {}", read_file_path_.u8string()); target_file_.setFileName( QString::fromStdString(read_file_path_.u8string())); target_file_.open(QIODevice::ReadOnly); if (!(target_file_.isOpen() && target_file_.isReadable())) { - SPDLOG_ERROR("file not open or not readable"); + GF_CORE_LOG_ERROR("file not open or not readable"); if (target_file_.isOpen()) target_file_.close(); return; } - SPDLOG_DEBUG("started reading: {}", read_file_path_.u8string()); + GF_CORE_LOG_DEBUG("started reading: {}", read_file_path_.u8string()); read_bytes(); } else { emit SignalFileBytesReadEnd(); @@ -71,10 +71,10 @@ void FileReadTask::read_bytes() { QByteArray read_buffer; if (!target_file_.atEnd() && (read_buffer = target_file_.read(kBufferSize)).size() > 0) { - SPDLOG_DEBUG("io thread read bytes: {}", read_buffer.size()); + GF_CORE_LOG_DEBUG("io thread read bytes: {}", read_buffer.size()); emit SignalFileBytesRead(std::move(read_buffer)); } else { - SPDLOG_DEBUG("io read bytes end"); + GF_CORE_LOG_DEBUG("io read bytes end"); emit SignalFileBytesReadEnd(); // announce finish task emit SignalTaskShouldEnd(0); @@ -82,7 +82,7 @@ void FileReadTask::read_bytes() { } FileReadTask::~FileReadTask() { - SPDLOG_DEBUG("close file: {}", read_file_path_.u8string()); + GF_CORE_LOG_DEBUG("close file: {}", read_file_path_.u8string()); if (target_file_.isOpen()) target_file_.close(); } diff --git a/src/core/thread/Task.cpp b/src/core/thread/Task.cpp index 3b27e52f..86799b9f 100644 --- a/src/core/thread/Task.cpp +++ b/src/core/thread/Task.cpp @@ -44,7 +44,7 @@ class Task::Impl { public: Impl(Task *parent, std::string name) : parent_(parent), uuid_(generate_uuid()), name_(name) { - SPDLOG_TRACE("task {} created", GetFullID()); + GF_CORE_LOG_TRACE("task {} created", GetFullID()); init(); } @@ -57,8 +57,8 @@ class Task::Impl { callback_([](int, const DataObjectPtr &) {}), callback_thread_(QThread::currentThread()), data_object_(std::move(data_object)) { - SPDLOG_TRACE("task {} created with runnable, callback_thread_: {}", - GetFullID(), static_cast<void *>(callback_thread_)); + GF_CORE_LOG_TRACE("task {} created with runnable, callback_thread_: {}", + GetFullID(), static_cast<void *>(callback_thread_)); init(); } @@ -71,13 +71,13 @@ class Task::Impl { callback_(std::move(callback)), callback_thread_(QThread::currentThread()), data_object_(std::move(data_object)) { - SPDLOG_TRACE( + GF_CORE_LOG_TRACE( "task {} created with runnable and callback, callback_thread_: {}", GetFullID(), static_cast<void *>(callback_thread_)); init(); } - ~Impl() { SPDLOG_TRACE("task {} destroyed", GetFullID()); } + ~Impl() { GF_CORE_LOG_TRACE("task {} destroyed", GetFullID()); } /** * @brief @@ -89,12 +89,12 @@ class Task::Impl { std::string GetUUID() const { return uuid_; } void Run() { - SPDLOG_TRACE("task {} is using default runnable and callback mode", - GetFullID()); + GF_CORE_LOG_TRACE("task {} is using default runnable and callback mode", + GetFullID()); if (runnable_) { SetRTN(runnable_(data_object_)); } else { - SPDLOG_WARN("no runnable in task, do callback operation"); + GF_CORE_LOG_WARN("no runnable in task, do callback operation"); } } @@ -123,8 +123,8 @@ class Task::Impl { DataObjectPtr data_object_ = nullptr; ///< void init() { - SPDLOG_TRACE("task {} created, parent: {}, impl: {}", name_, - (void *)parent_, (void *)this); + GF_CORE_LOG_TRACE("task {} created, parent: {}, impl: {}", name_, + (void *)parent_, (void *)this); // HoldOnLifeCycle(false); @@ -146,13 +146,13 @@ class Task::Impl { */ void inner_run() { try { - SPDLOG_TRACE("task {} is starting...", GetFullID()); + GF_CORE_LOG_TRACE("task {} is starting...", GetFullID()); // Run() will set rtn by itself parent_->Run(); - SPDLOG_TRACE("task {} was end.", GetFullID()); + GF_CORE_LOG_TRACE("task {} was end.", GetFullID()); } catch (std::exception &e) { - SPDLOG_ERROR("exception was caught at task: {}", e.what()); - SPDLOG_ERROR( + GF_CORE_LOG_ERROR("exception was caught at task: {}", e.what()); + GF_CORE_LOG_ERROR( "stacktrace of the exception: {}", boost::stacktrace::to_string(boost::stacktrace::stacktrace())); } @@ -174,55 +174,57 @@ class Task::Impl { * */ void slot_task_should_end(int rtn) { - SPDLOG_TRACE("task runnable {} finished, rtn: {}", GetFullID(), rtn); + GF_CORE_LOG_TRACE("task runnable {} finished, rtn: {}", GetFullID(), rtn); // set return value this->SetRTN(rtn); #ifdef RELEASE try { #endif if (callback_) { - SPDLOG_TRACE("task {} has a callback function", GetFullID()); + GF_CORE_LOG_TRACE("task {} has a callback function", GetFullID()); if (callback_thread_ == QThread::currentThread()) { - SPDLOG_TRACE("for task {}, the callback thread is the same thread", - GetFullID(), callback_thread_->currentThreadId()); + GF_CORE_LOG_TRACE( + "for task {}, the callback thread is the same thread", + GetFullID(), callback_thread_->currentThreadId()); callback_(rtn, data_object_); // raise signal, announcing this task comes to an end - SPDLOG_TRACE( + GF_CORE_LOG_TRACE( "for task {}, its life comes to an end in the same thread after " "its callback executed.", parent_->GetFullID()); emit parent_->SignalTaskEnd(); } else { - SPDLOG_TRACE("for task {}, callback thread is a different thread: {}", - GetFullID(), callback_thread_->currentThreadId()); + GF_CORE_LOG_TRACE( + "for task {}, callback thread is a different thread: {}", + GetFullID(), callback_thread_->currentThreadId()); if (!QMetaObject::invokeMethod( callback_thread_, [callback = callback_, rtn = rtn_, data_object = data_object_, parent_ = this->parent_]() { - SPDLOG_TRACE("calling callback of task {}", - parent_->GetFullID()); + GF_CORE_LOG_TRACE("calling callback of task {}", + parent_->GetFullID()); try { callback(rtn, data_object); } catch (...) { - SPDLOG_ERROR( + GF_CORE_LOG_ERROR( "unknown exception was caught when execute " "callback of task {}", parent_->GetFullID()); } // raise signal, announcing this task comes to an end - SPDLOG_TRACE( + GF_CORE_LOG_TRACE( "for task {}, its life comes to an end whether its " "callback function fails or not.", parent_->GetFullID()); emit parent_->SignalTaskEnd(); })) { - SPDLOG_ERROR( + GF_CORE_LOG_ERROR( "task {} had failed to invoke the callback function to target " "thread", GetFullID()); - SPDLOG_TRACE( + GF_CORE_LOG_TRACE( "for task {}, its life must come to an end now, although it " "has something not done yet.", GetFullID()); @@ -231,7 +233,7 @@ class Task::Impl { } } else { // raise signal, announcing this task comes to an end - SPDLOG_TRACE( + GF_CORE_LOG_TRACE( "for task {}, its life comes to an end without callback " "peacefully.", GetFullID()); @@ -239,22 +241,23 @@ class Task::Impl { } #ifdef RELEASE } catch (std::exception &e) { - SPDLOG_ERROR("exception was caught at task callback: {}", e.what()); - SPDLOG_ERROR( + GF_CORE_LOG_ERROR("exception was caught at task callback: {}", e.what()); + GF_CORE_LOG_ERROR( "stacktrace of the exception: {}", boost::stacktrace::to_string(boost::stacktrace::stacktrace())); // raise signal, announcing this task comes to an end - SPDLOG_TRACE("for task {}, its life comes to an end at chaos.", - GetFullID()); + GF_CORE_LOG_TRACE("for task {}, its life comes to an end at chaos.", + GetFullID()); emit parent_->SignalTaskEnd(); } catch (...) { - SPDLOG_ERROR("unknown exception was caught"); - SPDLOG_ERROR( + GF_CORE_LOG_ERROR("unknown exception was caught"); + GF_CORE_LOG_ERROR( "stacktrace of the exception: {}", boost::stacktrace::to_string(boost::stacktrace::stacktrace())); // raise signal, announcing this task comes to an end - SPDLOG_TRACE("for task {}, its life comes to an end at unknown chaos.", - GetFullID()); + GF_CORE_LOG_TRACE( + "for task {}, its life comes to an end at unknown chaos.", + GetFullID()); emit parent_->SignalTaskEnd(); } #endif @@ -291,8 +294,8 @@ void Task::SafelyRun() { emit SignalRun(); } void Task::Run() { p_->Run(); } void Task::run() { - SPDLOG_TRACE("interface run() of task {} was called by thread: {}", - GetFullID(), QThread::currentThread()->currentThreadId()); + GF_CORE_LOG_TRACE("interface run() of task {} was called by thread: {}", + GetFullID(), QThread::currentThread()->currentThreadId()); this->SafelyRun(); } diff --git a/src/core/thread/TaskRunner.cpp b/src/core/thread/TaskRunner.cpp index 72266d20..0e9c9098 100644 --- a/src/core/thread/TaskRunner.cpp +++ b/src/core/thread/TaskRunner.cpp @@ -44,15 +44,15 @@ class TaskRunner::Impl : public QThread { void PostTask(Task* task) { if (task == nullptr) { - SPDLOG_ERROR("task posted is null"); + GF_CORE_LOG_ERROR("task posted is null"); return; } task->setParent(nullptr); task->moveToThread(this); - SPDLOG_TRACE("runner starts task: {} at thread: {}", task->GetFullID(), - this->currentThreadId()); + GF_CORE_LOG_TRACE("runner starts task: {} at thread: {}", task->GetFullID(), + this->currentThreadId()); task->SafelyRun(); } @@ -64,45 +64,48 @@ class TaskRunner::Impl : public QThread { QtConcurrent::run(runner, data_object).then([=](int rtn) { if (!cb) { - SPDLOG_TRACE("task {} doesn't have a callback function", task_uuid); + GF_CORE_LOG_TRACE("task {} doesn't have a callback function", + task_uuid); return; } if (callback_thread == QThread::currentThread()) { - SPDLOG_TRACE("for task {}, the callback thread is the same thread: {}", - task_uuid, static_cast<void*>(callback_thread)); + GF_CORE_LOG_TRACE( + "for task {}, the callback thread is the same thread: {}", + task_uuid, static_cast<void*>(callback_thread)); cb(rtn, data_object); // raise signal, announcing this task comes to an end - SPDLOG_TRACE( + GF_CORE_LOG_TRACE( "for task {}, its life comes to an end in the same thread " "after its callback executed.", task_uuid); } else { - SPDLOG_TRACE("for task {}, callback thread is a different thread: {}", - task_uuid, static_cast<void*>(callback_thread)); + GF_CORE_LOG_TRACE( + "for task {}, callback thread is a different thread: {}", task_uuid, + static_cast<void*>(callback_thread)); if (!QMetaObject::invokeMethod(callback_thread, [=]() { - SPDLOG_TRACE("calling callback of task {}", task_uuid); + GF_CORE_LOG_TRACE("calling callback of task {}", task_uuid); try { cb(rtn, data_object); } catch (...) { - SPDLOG_ERROR( + GF_CORE_LOG_ERROR( "unknown exception was caught when execute " "callback of task {}", task_uuid); } // raise signal, announcing this task comes to an end - SPDLOG_TRACE( + GF_CORE_LOG_TRACE( "for task {}, its life comes to an end whether its " "callback function fails or not.", task_uuid); })) { - SPDLOG_ERROR( + GF_CORE_LOG_ERROR( "task {} had failed to invoke the callback function to " "target thread", task_uuid); - SPDLOG_TRACE( + GF_CORE_LOG_TRACE( "for task {}, its life must come to an end now, although it " "has something not done yet.", task_uuid); @@ -113,7 +116,7 @@ class TaskRunner::Impl : public QThread { void PostConcurrentTask(Task* task) { if (task == nullptr) { - SPDLOG_ERROR("task posted is null"); + GF_CORE_LOG_ERROR("task posted is null"); return; } @@ -128,7 +131,8 @@ class TaskRunner::Impl : public QThread { concurrent_thread->start(); - SPDLOG_TRACE("runner starts task concurrenctly: {}", task->GetFullID()); + GF_CORE_LOG_TRACE("runner starts task concurrenctly: {}", + task->GetFullID()); task->SafelyRun(); } diff --git a/src/core/utils/AsyncUtils.cpp b/src/core/utils/AsyncUtils.cpp index d414ac99..385a8d56 100644 --- a/src/core/utils/AsyncUtils.cpp +++ b/src/core/utils/AsyncUtils.cpp @@ -41,10 +41,10 @@ void RunGpgOperaAsync(GpgOperaRunnable runnable, GpgOperationCallback callback, const std::string& minial_version) { const auto gnupg_version = Module::RetrieveRTValueTypedOrDefault<>( "core", "gpgme.ctx.gnupg_version", minial_version); - SPDLOG_DEBUG("got gnupg version from rt: {}", gnupg_version); + GF_CORE_LOG_DEBUG("got gnupg version from rt: {}", gnupg_version); if (CompareSoftwareVersion(gnupg_version, "2.0.15") < 0) { - SPDLOG_ERROR("operator not support"); + GF_CORE_LOG_ERROR("operator not support"); callback(GPG_ERR_NOT_SUPPORTED, TransferParams()); return; } diff --git a/src/core/utils/GpgUtils.cpp b/src/core/utils/GpgUtils.cpp index 98e4c749..d6dd6e04 100644 --- a/src/core/utils/GpgUtils.cpp +++ b/src/core/utils/GpgUtils.cpp @@ -69,7 +69,7 @@ auto GetGpgmeErrorString(gpgme_error_t err) -> std::string { auto CheckGpgError(GpgError err) -> GpgError { auto err_code = gpg_err_code(err); if (err_code != GPG_ERR_NO_ERROR) { - SPDLOG_ERROR( + GF_CORE_LOG_ERROR( "gpg operation failed [error code: {}], source: {} description: {}", err_code, gpgme_strsource(err), GetGpgmeErrorString(err)); } @@ -80,13 +80,13 @@ auto CheckGpgError2ErrCode(GpgError err, GpgError predict) -> GpgErrorCode { auto err_code = gpg_err_code(err); if (err_code != gpg_err_code(predict)) { if (err_code == GPG_ERR_NO_ERROR) { - SPDLOG_WARN("[Warning {}] Source: {} description: {} predict: {}", - gpg_err_code(err), gpgme_strsource(err), - GetGpgmeErrorString(err), GetGpgmeErrorString(predict)); + GF_CORE_LOG_WARN("[Warning {}] Source: {} description: {} predict: {}", + gpg_err_code(err), gpgme_strsource(err), + GetGpgmeErrorString(err), GetGpgmeErrorString(predict)); } else { - SPDLOG_ERROR("[Error {}] Source: {} description: {} predict: {}", - gpg_err_code(err), gpgme_strsource(err), - GetGpgmeErrorString(err), GetGpgmeErrorString(predict)); + GF_CORE_LOG_ERROR("[Error {}] Source: {} description: {} predict: {}", + gpg_err_code(err), gpgme_strsource(err), + GetGpgmeErrorString(err), GetGpgmeErrorString(predict)); } } return err_code; @@ -98,8 +98,8 @@ auto DescribeGpgErrCode(GpgError err) -> GpgErrorDesc { auto CheckGpgError(GpgError err, const std::string& /*comment*/) -> GpgError { if (gpg_err_code(err) != GPG_ERR_NO_ERROR) { - SPDLOG_WARN("[Error {}] Source: {} description: {}", gpg_err_code(err), - gpgme_strsource(err), GetGpgmeErrorString(err)); + GF_CORE_LOG_WARN("[Error {}] Source: {} description: {}", gpg_err_code(err), + gpgme_strsource(err), GetGpgmeErrorString(err)); } return err; } diff --git a/src/core/utils/IOUtils.cpp b/src/core/utils/IOUtils.cpp index a11baf92..0a67a69b 100644 --- a/src/core/utils/IOUtils.cpp +++ b/src/core/utils/IOUtils.cpp @@ -40,7 +40,7 @@ namespace GpgFrontend { auto ReadFile(const QString& file_name, QByteArray& data) -> bool { QFile file(file_name); if (!file.open(QIODevice::ReadOnly)) { - SPDLOG_ERROR("failed to open file: {}", file_name.toStdString()); + GF_CORE_LOG_ERROR("failed to open file: {}", file_name.toStdString()); return false; } data = file.readAll(); @@ -51,7 +51,7 @@ auto ReadFile(const QString& file_name, QByteArray& data) -> bool { auto WriteFile(const QString& file_name, const QByteArray& data) -> bool { QFile file(file_name); if (!file.open(QIODevice::WriteOnly)) { - SPDLOG_ERROR("failed to open file: {}", file_name.toStdString()); + GF_CORE_LOG_ERROR("failed to open file: {}", file_name.toStdString()); return false; } file.write(data); @@ -122,7 +122,7 @@ auto CalculateHash(const std::filesystem::path& file_path) -> std::string { auto hash_md5 = QCryptographicHash(QCryptographicHash::Md5); hash_md5.addData(buffer); auto md5 = hash_md5.result().toHex().toStdString(); - SPDLOG_DEBUG("md5 {}", md5); + GF_CORE_LOG_DEBUG("md5 {}", md5); ss << " " << "md5" << _(": ") << md5 << std::endl; @@ -130,7 +130,7 @@ auto CalculateHash(const std::filesystem::path& file_path) -> std::string { auto hash_sha1 = QCryptographicHash(QCryptographicHash::Sha1); hash_sha1.addData(buffer); auto sha1 = hash_sha1.result().toHex().toStdString(); - SPDLOG_DEBUG("sha1 {}", sha1); + GF_CORE_LOG_DEBUG("sha1 {}", sha1); ss << " " << "sha1" << _(": ") << sha1 << std::endl; @@ -138,7 +138,7 @@ auto CalculateHash(const std::filesystem::path& file_path) -> std::string { auto hash_sha256 = QCryptographicHash(QCryptographicHash::Sha256); hash_sha256.addData(buffer); auto sha256 = hash_sha256.result().toHex().toStdString(); - SPDLOG_DEBUG("sha256 {}", sha256); + GF_CORE_LOG_DEBUG("sha256 {}", sha256); ss << " " << "sha256" << _(": ") << sha256 << std::endl; diff --git a/src/core/utils/LogUtils.cpp b/src/core/utils/LogUtils.cpp index d7d13579..f95ade9a 100644 --- a/src/core/utils/LogUtils.cpp +++ b/src/core/utils/LogUtils.cpp @@ -28,6 +28,34 @@ #include "LogUtils.h" +#include "core/function/LoggerManager.h" + +namespace GpgFrontend { + +auto GetDefaultLogger() -> std::shared_ptr<spdlog::logger> { + return LoggerManager::GetDefaultLogger(); +} + auto GetCoreLogger() -> std::shared_ptr<spdlog::logger> { - return spdlog::get("core"); -}
\ No newline at end of file + return LoggerManager::GetInstance().GetLogger("core"); +} + +auto GetLogger(const std::string& id) -> std::shared_ptr<spdlog::logger> { + return LoggerManager::GetInstance().GetLogger(id); +} + +void SetDefaultLogLevel(spdlog::level::level_enum level) { + return LoggerManager::SetDefaultLogLevel(level); +} + +void RegisterAsyncLogger(const std::string& id, + spdlog::level::level_enum level) { + LoggerManager::GetInstance().RegisterAsyncLogger(id, level); +} + +void RegisterSyncLogger(const std::string& id, + spdlog::level::level_enum level) { + LoggerManager::GetInstance().RegisterSyncLogger(id, level); +} + +} // namespace GpgFrontend
\ No newline at end of file diff --git a/src/core/utils/LogUtils.h b/src/core/utils/LogUtils.h index a4d29dd8..0ed618f9 100644 --- a/src/core/utils/LogUtils.h +++ b/src/core/utils/LogUtils.h @@ -28,4 +28,85 @@ #pragma once -auto GPGFRONTEND_CORE_EXPORT GetCoreLogger() -> std::shared_ptr<spdlog::logger>;
\ No newline at end of file +namespace GpgFrontend { + +/** + * @brief + * + * @return std::shared_ptr<spdlog::logger> + */ +auto GPGFRONTEND_CORE_EXPORT GetDefaultLogger() + -> std::shared_ptr<spdlog::logger>; + +/** + * @brief + * + * @return std::shared_ptr<spdlog::logger> + */ +auto GPGFRONTEND_CORE_EXPORT GetCoreLogger() -> std::shared_ptr<spdlog::logger>; + +/** + * @brief + * + * @return std::shared_ptr<spdlog::logger> + */ +auto GPGFRONTEND_CORE_EXPORT GetLogger(const std::string &) + -> std::shared_ptr<spdlog::logger>; + +/** + * @brief Set the Default Log Level object + * + * @return auto + */ +void GPGFRONTEND_CORE_EXPORT SetDefaultLogLevel(spdlog::level::level_enum); + +/** + * @brief + * + * @return auto + */ +void GPGFRONTEND_CORE_EXPORT RegisterAsyncLogger(const std::string &, + spdlog::level::level_enum); + +/** + * @brief + * + * @return auto + */ +void GPGFRONTEND_CORE_EXPORT RegisterSyncLogger(const std::string &, + spdlog::level::level_enum); + +} // namespace GpgFrontend + +#define GF_DEFAULT_LOG_TRACE(...) \ + SPDLOG_LOGGER_TRACE(GpgFrontend::GetDefaultLogger(), __VA_ARGS__) +#define GF_DEFAULT_LOG_DEBUG(...) \ + SPDLOG_LOGGER_DEBUG(GpgFrontend::GetDefaultLogger(), __VA_ARGS__) +#define GF_DEFAULT_LOG_INFO(...) \ + SPDLOG_LOGGER_INFO(GpgFrontend::GetDefaultLogger(), __VA_ARGS__) +#define GF_DEFAULT_LOG_WARN(...) \ + SPDLOG_LOGGER_WARN(GpgFrontend::GetDefaultLogger(), __VA_ARGS__) +#define GF_DEFAULT_LOG_ERROR(...) \ + SPDLOG_LOGGER_ERROR(GpgFrontend::GetDefaultLogger(), __VA_ARGS__) + +#define GF_CORE_LOG_TRACE(...) \ + SPDLOG_LOGGER_TRACE(GpgFrontend::GetCoreLogger(), __VA_ARGS__) +#define GF_CORE_LOG_DEBUG(...) \ + SPDLOG_LOGGER_DEBUG(GpgFrontend::GetCoreLogger(), __VA_ARGS__) +#define GF_CORE_LOG_INFO(...) \ + SPDLOG_LOGGER_INFO(GpgFrontend::GetCoreLogger(), __VA_ARGS__) +#define GF_CORE_LOG_WARN(...) \ + SPDLOG_LOGGER_WARN(GpgFrontend::GetCoreLogger(), __VA_ARGS__) +#define GF_CORE_LOG_ERROR(...) \ + SPDLOG_LOGGER_ERROR(GpgFrontend::GetCoreLogger(), __VA_ARGS__) + +#define GF_LOG_TRACE(ID, ...) \ + SPDLOG_LOGGER_TRACE(GpgFrontend::GetLogger(ID), __VA_ARGS__) +#define GF_LOG_DEBUG(ID, ...) \ + SPDLOG_LOGGER_DEBUG(GpgFrontend::GetLogger(ID), __VA_ARGS__) +#define GF_LOG_INFO(ID, ...) \ + SPDLOG_LOGGER_INFO(GpgFrontend::GetLogger(ID), __VA_ARGS__) +#define GF_LOG_WARN(ID, ...) \ + SPDLOG_LOGGER_WARN(GpgFrontend::GetLogger(ID), __VA_ARGS__) +#define GF_LOG_ERROR(ID, ...) \ + SPDLOG_LOGGER_ERROR(GpgFrontend::GetLogger(ID), __VA_ARGS__)
\ No newline at end of file diff --git a/src/core/utils/MemoryUtils.h b/src/core/utils/MemoryUtils.h index 5f4283b2..800f2163 100644 --- a/src/core/utils/MemoryUtils.h +++ b/src/core/utils/MemoryUtils.h @@ -112,9 +112,6 @@ static auto SecureCreateObject(Args &&...args) -> T * { void *mem = SecureMemoryAllocator::Allocate(sizeof(T)); if (!mem) return nullptr; - SPDLOG_TRACE("alloc secure memnory success, type: {}, size: {}, addr: {}", - typeid(T).name(), sizeof(T), mem); - try { return new (mem) T(std::forward<Args>(args)...); } catch (...) { @@ -136,11 +133,6 @@ static auto SecureCreateUniqueObject(Args &&...args) void *mem = SecureMemoryAllocator::Allocate(sizeof(T)); if (!mem) throw std::bad_alloc(); - SPDLOG_TRACE( - "alloc secure memnory success, unique ptr, " - "type: {}, size: {}, addr: {}", - typeid(T).name(), sizeof(T), mem); - try { return std::unique_ptr<T, SecureObjectDeleter<T>>( new (mem) T(std::forward<Args>(args)...)); @@ -155,11 +147,6 @@ auto SecureCreateSharedObject(Args &&...args) -> std::shared_ptr<T> { void *mem = SecureMemoryAllocator::Allocate(sizeof(T)); if (!mem) throw std::bad_alloc(); - SPDLOG_TRACE( - "alloc secure memnory success, shared ptr, " - "type: {}, size: {}, addr: {}", - typeid(T).name(), sizeof(T), mem); - try { T *obj = new (mem) T(std::forward<Args>(args)...); return std::shared_ptr<T>(obj, [](T *ptr) { diff --git a/src/init.cpp b/src/init.cpp index f6d90d83..cc91c538 100644 --- a/src/init.cpp +++ b/src/init.cpp @@ -41,14 +41,13 @@ #include "core/GpgCoreInit.h" #include "core/function/GlobalSettingStation.h" #include "core/thread/TaskRunnerGetter.h" -#include "core/utils/MemoryUtils.h" +#include "core/utils/LogUtils.h" #include "module/GpgFrontendModuleInit.h" -#include "module/sdk/Log.h" -#include "test/GpgFrontendTest.h" #include "ui/GpgFrontendUIInit.h" // main #include "GpgFrontendContext.h" +#include "main.h" namespace GpgFrontend { @@ -64,77 +63,21 @@ int setenv(const char *name, const char *value, int overwrite) { } #endif -void InitMainLoggingSystem(spdlog::level::level_enum level) { - // sinks - std::vector<spdlog::sink_ptr> sinks; - sinks.push_back( - SecureCreateSharedObject<spdlog::sinks::stderr_color_sink_mt>()); - - // logger - auto main_logger = SecureCreateSharedObject<spdlog::logger>( - "main", begin(sinks), end(sinks)); - main_logger->set_pattern( - "[%H:%M:%S.%e] [T:%t] [%=6n] %^[%=8l]%$ [%s:%#] [%!] -> %v (+%ius)"); - - // set the level of logger - main_logger->set_level(level); - -#ifdef DEBUG - // flush policy - main_logger->flush_on(spdlog::level::trace); -#else - // flush policy - main_logger->flush_on(spdlog::level::err); -#endif - - spdlog::flush_every(std::chrono::seconds(3)); - - // register it as default logger - spdlog::set_default_logger(main_logger); -} - void InitLoggingSystem(const GFCxtSPtr &ctx) { - // init the logging system for main - InitMainLoggingSystem(ctx->log_level); + RegisterSyncLogger("core", ctx->log_level); - // init the logging system for core - InitCoreLoggingSystem(ctx->log_level); + RegisterSyncLogger("main", ctx->log_level); - // shutdown the logging system for modules - Module::LoadGpgFrontendModulesLoggingSystem(ctx->log_level); - - // init the logging system for test - Test::InitTestLoggingSystem(ctx->log_level); + RegisterSyncLogger("module", ctx->log_level); if (ctx->load_ui_env) { // init the logging system for ui - UI::InitUILoggingSystem(ctx->log_level); + RegisterSyncLogger("ui", ctx->log_level); + } else { + RegisterSyncLogger("test", ctx->log_level); } } -void ShutdownLoggingSystem(const GFCxtSPtr &ctx) { - if (ctx->load_ui_env) { - // shutdown the logging system for ui - UI::ShutdownUILoggingSystem(); - } - - // shutdown the logging system for test - Test::ShutdownTestLoggingSystem(); - - // shutdown the logging system for modules - Module::ShutdownGpgFrontendModulesLoggingSystem(); - - // shutdown the logging system for core - ShutdownCoreLoggingSystem(); - -#ifdef WINDOWS - // Under VisualStudio, this must be called before main finishes to workaround - // a known VS issue - spdlog::drop_all(); - spdlog::shutdown(); -#endif -} - void InitGlobalPathEnv() { // read settings bool use_custom_gnupg_install_path = @@ -148,14 +91,14 @@ void InitGlobalPathEnv() { // add custom gnupg install path into env $PATH if (use_custom_gnupg_install_path && !custom_gnupg_install_path.empty()) { std::string path_value = getenv("PATH"); - SPDLOG_DEBUG("Current System PATH: {}", path_value); + GF_MAIN_LOG_DEBUG("Current System PATH: {}", path_value); setenv("PATH", ((std::filesystem::path{custom_gnupg_install_path}).u8string() + ":" + path_value) .c_str(), 1); std::string modified_path_value = getenv("PATH"); - SPDLOG_DEBUG("Modified System PATH: {}", modified_path_value); + GF_MAIN_LOG_DEBUG("Modified System PATH: {}", modified_path_value); } } @@ -166,6 +109,7 @@ void InitGlobalBasicalEnv(const GFCxtWPtr &p_ctx, bool gui_mode) { } // initialize logging system + SetDefaultLogLevel(ctx->log_level); InitLoggingSystem(ctx); // change path to search for related @@ -200,8 +144,6 @@ void ShutdownGlobalBasicalEnv(const GFCxtWPtr &p_ctx) { Thread::TaskRunnerGetter::GetInstance().StopAllTeakRunner(); DestroyGpgFrontendCore(); - - ShutdownLoggingSystem(ctx); } } // namespace GpgFrontend @@ -47,12 +47,6 @@ void HandleSignal(int sig); void InitLoggingSystem(const GFCxtSPtr &); /** - * @brief initialize the logging system. - * - */ -void ShutdownLoggingSystem(const GFCxtSPtr &); - -/** * @brief init global PATH env * */ @@ -66,9 +60,9 @@ void InitGlobalPathEnv(); void InitGlobalBasicalEnv(const GFCxtWPtr &, bool); /** - * @brief - * - * @param p_ctx + * @brief + * + * @param p_ctx */ void ShutdownGlobalBasicalEnv(const GFCxtWPtr &p_ctx); diff --git a/src/main.h b/src/main.h new file mode 100644 index 00000000..d22b2acf --- /dev/null +++ b/src/main.h @@ -0,0 +1,37 @@ +/** + * Copyright (C) 2021 Saturneric <[email protected]> + * + * This file is part of GpgFrontend. + * + * GpgFrontend is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * GpgFrontend is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with GpgFrontend. If not, see <https://www.gnu.org/licenses/>. + * + * The initial version of the source code is inherited from + * the gpg4usb project, which is under GPL-3.0-or-later. + * + * All the source code of GpgFrontend was modified and released by + * Saturneric <[email protected]> starting on May 12, 2021. + * + * SPDX-License-Identifier: GPL-3.0-or-later + * + */ + +#pragma once + +#include "core/utils/LogUtils.h" + +#define GF_MAIN_LOG_TRACE(...) GF_LOG_TRACE("main", __VA_ARGS__) +#define GF_MAIN_LOG_DEBUG(...) GF_LOG_DEBUG("main", __VA_ARGS__) +#define GF_MAIN_LOG_INFO(...) GF_LOG_INFO("main", __VA_ARGS__) +#define GF_MAIN_LOG_WARN(...) GF_LOG_WARN("main", __VA_ARGS__) +#define GF_MAIN_LOG_ERROR(...) GF_LOG_ERROR("main", __VA_ARGS__)
\ No newline at end of file diff --git a/src/module/GpgFrontendModuleInit.cpp b/src/module/GpgFrontendModuleInit.cpp index 5db3b0b6..b2d29c71 100644 --- a/src/module/GpgFrontendModuleInit.cpp +++ b/src/module/GpgFrontendModuleInit.cpp @@ -40,14 +40,6 @@ namespace GpgFrontend::Module { -void LoadGpgFrontendModulesLoggingSystem(spdlog::level::level_enum log_level) { - GpgFrontend::Module::SDK::InitModuleLoggingSystem(log_level); -} - -void ShutdownGpgFrontendModulesLoggingSystem() { - GpgFrontend::Module::SDK::ShutdownModuleLoggingSystem(); -} - void LoadGpgFrontendModules(ModuleInitArgs args) { // must init at default thread before core Thread::TaskRunnerGetter::GetInstance().GetTaskRunner()->PostTask( diff --git a/src/module/GpgFrontendModuleInit.h b/src/module/GpgFrontendModuleInit.h index c7071856..a3a8bbd3 100644 --- a/src/module/GpgFrontendModuleInit.h +++ b/src/module/GpgFrontendModuleInit.h @@ -37,20 +37,6 @@ struct ModuleInitArgs { }; /** - * @brief - * - * @param args - */ -void GPGFRONTEND_MODULE_EXPORT -LoadGpgFrontendModulesLoggingSystem(spdlog::level::level_enum log_level); - -/** - * @brief - * - */ -void GPGFRONTEND_MODULE_EXPORT ShutdownGpgFrontendModulesLoggingSystem(); - -/** * @brief init the module library * */ diff --git a/src/module/integrated/gnupg_info_gathering_module/GnuPGInfoGatheringModule.cpp b/src/module/integrated/gnupg_info_gathering_module/GnuPGInfoGatheringModule.cpp index 9477848b..84dd49cb 100644 --- a/src/module/integrated/gnupg_info_gathering_module/GnuPGInfoGatheringModule.cpp +++ b/src/module/integrated/gnupg_info_gathering_module/GnuPGInfoGatheringModule.cpp @@ -392,8 +392,7 @@ int GnuPGInfoGatheringModule::Exec(EventRefrernce event) { UpsertRTValue(GetModuleIdentifier(), "gnupg.gathering_done", true); event->ExecuteCallback(GetModuleIdentifier(), TransferParams(true)); - SPDLOG_INFO("gnupg external info gathering done"); - + MODULE_LOG_DEBUG("gnupg external info gathering done"); return 0; } diff --git a/src/module/integrated/version_checking_module/VersionCheckTask.cpp b/src/module/integrated/version_checking_module/VersionCheckTask.cpp index 85eb07c4..bacce396 100644 --- a/src/module/integrated/version_checking_module/VersionCheckTask.cpp +++ b/src/module/integrated/version_checking_module/VersionCheckTask.cpp @@ -93,7 +93,7 @@ void VersionCheckTask::slot_parse_latest_version_info() { MODULE_LOG_DEBUG("latest version matched: {}", latest_version); } else { latest_version = current_version_; - SPDLOG_WARN("latest version unknown"); + MODULE_LOG_WARN("latest version unknown"); } bool prerelease = latest_reply_json["prerelease"]; diff --git a/src/module/sdk/Log.cpp b/src/module/sdk/Log.cpp index b70f5bbb..7b0e4cca 100644 --- a/src/module/sdk/Log.cpp +++ b/src/module/sdk/Log.cpp @@ -37,60 +37,4 @@ #include "core/function/GlobalSettingStation.h" -namespace GpgFrontend::Module::SDK { - -void InitModuleLoggingSystem(spdlog::level::level_enum level) { - // get the log directory - auto log_file_path = - (GpgFrontend::GlobalSettingStation::GetInstance().GetLogDir() / "module"); - log_file_path.replace_extension(".log"); - - // sinks - std::vector<spdlog::sink_ptr> sinks; - sinks.push_back(GpgFrontend::SecureCreateSharedObject< - spdlog::sinks::stderr_color_sink_mt>()); - sinks.push_back(GpgFrontend::SecureCreateSharedObject< - spdlog::sinks::rotating_file_sink_mt>( - log_file_path.u8string(), 1048576 * 32, 32)); - - // thread pool - spdlog::init_thread_pool(1024, 2); - - // logger - auto module_logger = - GpgFrontend::SecureCreateSharedObject<spdlog::async_logger>( - "module", begin(sinks), end(sinks), spdlog::thread_pool()); - module_logger->set_pattern( - "[%H:%M:%S.%e] [T:%t] [%=6n] %^[%=8l]%$ [%s:%#] [%!] -> %v (+%ius)"); - - // set the level of logger - module_logger->set_level(level); - - // flush policy - module_logger->flush_on(spdlog::level::err); - spdlog::flush_every(std::chrono::seconds(5)); - - // register it as default logger - spdlog::set_default_logger(module_logger); -} - -void ShutdownModuleLoggingSystem() { -#ifdef WINDOWS - // Under VisualStudio, this must be called before main finishes to workaround - // a known VS issue - spdlog::drop_all(); - spdlog::shutdown(); -#endif -} - -auto GetModuleLogger() -> std::shared_ptr<spdlog::logger> { - // check if logging system is initalized - auto ptr = spdlog::get("module"); - if (ptr == nullptr) { - throw std::runtime_error("logging system of modules is not initialized"); - } - - return spdlog::get("module"); -} - -} // namespace GpgFrontend::Module::SDK +namespace GpgFrontend::Module::SDK {} // namespace GpgFrontend::Module::SDK diff --git a/src/module/sdk/Log.h b/src/module/sdk/Log.h index bff9893e..0c40a097 100644 --- a/src/module/sdk/Log.h +++ b/src/module/sdk/Log.h @@ -28,18 +28,14 @@ #pragma once +#include "core/utils/LogUtils.h" #include "module/sdk/GpgFrontendModuleSDK.h" -#define MODULE_LOG_TRACE(...) \ - SPDLOG_LOGGER_TRACE(GpgFrontend::Module::SDK::GetModuleLogger(), __VA_ARGS__) -#define MODULE_LOG_DEBUG(...) \ - SPDLOG_LOGGER_DEBUG(GpgFrontend::Module::SDK::GetModuleLogger(), __VA_ARGS__) -#define MODULE_LOG_INFO(...) \ - SPDLOG_LOGGER_INFO(GpgFrontend::Module::SDK::GetModuleLogger(), __VA_ARGS__) -#define MODULE_LOG_WARN(...) \ - SPDLOG_LOGGER_WARN(GpgFrontend::Module::SDK::GetModuleLogger(), __VA_ARGS__) -#define MODULE_LOG_ERROR(...) \ - SPDLOG_LOGGER_ERROR(GpgFrontend::Module::SDK::GetModuleLogger(), __VA_ARGS__) +#define MODULE_LOG_TRACE(...) GF_LOG_TRACE("module", __VA_ARGS__) +#define MODULE_LOG_DEBUG(...) GF_LOG_DEBUG("module", __VA_ARGS__) +#define MODULE_LOG_INFO(...) GF_LOG_INFO("module", __VA_ARGS__) +#define MODULE_LOG_WARN(...) GF_LOG_WARN("module", __VA_ARGS__) +#define MODULE_LOG_ERROR(...) GF_LOG_ERROR("module", __VA_ARGS__) namespace spdlog { class logger; @@ -47,49 +43,29 @@ class logger; namespace GpgFrontend::Module::SDK { -/** - * @brief - * - */ -void GPGFRONTEND_MODULE_SDK_EXPORT - InitModuleLoggingSystem(spdlog::level::level_enum); - -/** - * @brief - * - */ -void GPGFRONTEND_MODULE_SDK_EXPORT ShutdownModuleLoggingSystem(); - -/** - * @brief - * - */ -auto GPGFRONTEND_MODULE_SDK_EXPORT GetModuleLogger() - -> std::shared_ptr<spdlog::logger>; - template <typename... Args> void ModuleLogTrace(const char* fmt, const Args&... args) { - SPDLOG_LOGGER_TRACE(GetModuleLogger(), fmt, args...); + MODULE_LOG_TRACE(fmt, args...); } template <typename... Args> void ModuleLogDebug(const char* fmt, const Args&... args) { - SPDLOG_LOGGER_DEBUG(GetModuleLogger(), fmt, args...); + MODULE_LOG_DEBUG(fmt, args...); } template <typename... Args> void ModuleLogInfo(const char* fmt, const Args&... args) { - SPDLOG_LOGGER_INFO(GetModuleLogger(), fmt, args...); + MODULE_LOG_INFO(fmt, args...); } template <typename... Args> void ModuleLogWarn(const char* fmt, const Args&... args) { - SPDLOG_LOGGER_WARN(GetModuleLogger(), fmt, args...); + MODULE_LOG_WARN(fmt, args...); } template <typename... Args> void ModuleLogError(const char* fmt, const Args&... args) { - SPDLOG_LOGGER_ERROR(GetModuleLogger(), fmt, args...); + MODULE_LOG_ERROR(fmt, args...); } } // namespace GpgFrontend::Module::SDK diff --git a/src/signal.cpp b/src/signal.cpp index b7a9cef3..8c934166 100644 --- a/src/signal.cpp +++ b/src/signal.cpp @@ -44,7 +44,7 @@ extern jmp_buf recover_env; */ void HandleSignal(int sig) { static int _repeat_handle_num = 1, last_sig = sig; - // SPDLOG_DEBUG("signal caught {}", sig); + // GF_MAIN_LOG_DEBUG("signal caught {}", sig); std::cout << "signal caught" << sig; if (last_sig == sig) diff --git a/src/test/GpgFrontendTest.cpp b/src/test/GpgFrontendTest.cpp index 29903c39..f030ed12 100644 --- a/src/test/GpgFrontendTest.cpp +++ b/src/test/GpgFrontendTest.cpp @@ -29,8 +29,6 @@ #include "GpgFrontendTest.h" #include <gtest/gtest.h> -#include <spdlog/sinks/rotating_file_sink.h> -#include <spdlog/sinks/stdout_color_sinks.h> #include <boost/date_time.hpp> #include <boost/dll.hpp> @@ -46,42 +44,6 @@ namespace GpgFrontend::Test { -void InitTestLoggingSystem(spdlog::level::level_enum level) { - // get the log directory - auto logfile_path = - (GlobalSettingStation::GetInstance().GetLogDir() / "test"); - logfile_path.replace_extension(".log"); - - // sinks - std::vector<spdlog::sink_ptr> sinks; - sinks.push_back( - SecureCreateSharedObject<spdlog::sinks::stderr_color_sink_mt>()); - sinks.push_back( - SecureCreateSharedObject<spdlog::sinks::rotating_file_sink_mt>( - logfile_path.u8string(), 1048576 * 32, 8)); - - // logger - auto test_logger = SecureCreateSharedObject<spdlog::logger>( - "test", begin(sinks), end(sinks)); - test_logger->set_pattern( - "[%H:%M:%S.%e] [T:%t] [%=6n] %^[%=8l]%$ [%s:%#] [%!] -> %v (+%ius)"); - - // set the level of logger - test_logger->set_level(level); - - // register it as default logger - spdlog::set_default_logger(test_logger); -} - -void ShutdownTestLoggingSystem() { -#ifdef WINDOWS - // Under VisualStudio, this must be called before main finishes to workaround - // a known VS issue - spdlog::drop_all(); - spdlog::shutdown(); -#endif -} - auto GenerateRandomString(size_t length) -> std::string { const std::string characters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; @@ -100,8 +62,8 @@ auto GenerateRandomString(size_t length) -> std::string { void ConfigureGpgContext() { auto db_path = std::filesystem::temp_directory_path() / GenerateRandomString(12); - SPDLOG_DEBUG("setting up new database path for test case: {}", - db_path.string()); + GF_TEST_LOG_DEBUG("setting up new database path for test case: {}", + db_path.string()); if (!std::filesystem::exists(db_path)) { std::filesystem::create_directory(db_path); @@ -146,8 +108,8 @@ void SetupGlobalTestEnv() { auto test_config_path = test_path / "conf" / "test.cfg"; auto test_data_path = test_path / "data"; - SPDLOG_INFO("test config file path: {}", test_config_path.string()); - SPDLOG_INFO("test data file path: {}", test_data_path.string()); + GF_TEST_LOG_INFO("test config file path: {}", test_config_path.string()); + GF_TEST_LOG_INFO("test data file path: {}", test_data_path.string()); libconfig::Config cfg; ASSERT_NO_THROW(cfg.readFile(test_config_path.c_str())); diff --git a/src/test/GpgFrontendTest.h b/src/test/GpgFrontendTest.h index 897a8a05..405eee90 100644 --- a/src/test/GpgFrontendTest.h +++ b/src/test/GpgFrontendTest.h @@ -28,23 +28,24 @@ #pragma once -#include <spdlog/spdlog.h> - #include "GpgFrontendTestExport.h" +// Core +#include "core/utils/LogUtils.h" + namespace GpgFrontend::Test { struct GpgFrontendContext { int argc; char **argv; - spdlog::level::level_enum log_level; }; -void GPGFRONTEND_TEST_EXPORT -InitTestLoggingSystem(spdlog::level::level_enum level); - -void GPGFRONTEND_TEST_EXPORT ShutdownTestLoggingSystem(); - auto GPGFRONTEND_TEST_EXPORT ExecuteAllTestCase(GpgFrontendContext args) -> int; +#define GF_TEST_LOG_TRACE(...) GF_LOG_TRACE("test", __VA_ARGS__) +#define GF_TEST_LOG_DEBUG(...) GF_LOG_DEBUG("test", __VA_ARGS__) +#define GF_TEST_LOG_INFO(...) GF_LOG_INFO("test", __VA_ARGS__) +#define GF_TEST_LOG_WARN(...) GF_LOG_WARN("test", __VA_ARGS__) +#define GF_TEST_LOG_ERROR(...) GF_LOG_ERROR("test", __VA_ARGS__) + } // namespace GpgFrontend::Test diff --git a/src/ui/GpgFrontendApplication.cpp b/src/ui/GpgFrontendApplication.cpp index a9e4efd2..a4c4e2db 100644 --- a/src/ui/GpgFrontendApplication.cpp +++ b/src/ui/GpgFrontendApplication.cpp @@ -58,9 +58,10 @@ bool GpgFrontendApplication::notify(QObject *receiver, QEvent *event) { try { return QApplication::notify(receiver, event); } catch (const std::exception &ex) { - SPDLOG_ERROR("exception was caught in notify: {}", ex.what()); - SPDLOG_ERROR("stacktrace of the exception: {}", - boost::stacktrace::to_string(boost::stacktrace::stacktrace())); + GF_UI_LOG_ERROR("exception was caught in notify: {}", ex.what()); + GF_UI_LOG_ERROR( + "stacktrace of the exception: {}", + boost::stacktrace::to_string(boost::stacktrace::stacktrace())); QMessageBox::information(nullptr, _("Standard Exception Thrown"), _("Oops, an standard exception was thrown " "during the running of the " @@ -68,9 +69,10 @@ bool GpgFrontendApplication::notify(QObject *receiver, QEvent *event) { "be the negligence of the programmer, " "please report this problem if you can.")); } catch (...) { - SPDLOG_ERROR("unknown exception was caught in notify"); - SPDLOG_ERROR("stacktrace of the exception: {}", - boost::stacktrace::to_string(boost::stacktrace::stacktrace())); + GF_UI_LOG_ERROR("unknown exception was caught in notify"); + GF_UI_LOG_ERROR( + "stacktrace of the exception: {}", + boost::stacktrace::to_string(boost::stacktrace::stacktrace())); QMessageBox::information( nullptr, _("Unhandled Exception Thrown"), _("Oops, an unhandled exception was thrown " diff --git a/src/ui/GpgFrontendUI.h b/src/ui/GpgFrontendUI.h index f67da43e..b3115795 100644 --- a/src/ui/GpgFrontendUI.h +++ b/src/ui/GpgFrontendUI.h @@ -33,9 +33,16 @@ */ #include <QtWidgets> -/** - * Project internal dependencies - */ +// Core #include "GpgFrontend.h" #include "core/GpgFrontendCore.h" +#include "core/utils/LogUtils.h" + +// UI #include "ui/GpgFrontendUIExport.h" + +#define GF_UI_LOG_TRACE(...) GF_LOG_TRACE("ui", __VA_ARGS__) +#define GF_UI_LOG_DEBUG(...) GF_LOG_DEBUG("ui", __VA_ARGS__) +#define GF_UI_LOG_INFO(...) GF_LOG_INFO("ui", __VA_ARGS__) +#define GF_UI_LOG_WARN(...) GF_LOG_WARN("ui", __VA_ARGS__) +#define GF_UI_LOG_ERROR(...) GF_LOG_ERROR("ui", __VA_ARGS__) diff --git a/src/ui/GpgFrontendUIInit.cpp b/src/ui/GpgFrontendUIInit.cpp index 99a9541f..e896229f 100644 --- a/src/ui/GpgFrontendUIInit.cpp +++ b/src/ui/GpgFrontendUIInit.cpp @@ -30,10 +30,6 @@ #include <qapplication.h> #include <qcoreapplication.h> -#include <spdlog/async.h> -#include <spdlog/common.h> -#include <spdlog/sinks/rotating_file_sink.h> -#include <spdlog/sinks/stdout_color_sinks.h> #include <QtNetwork> #include <string> @@ -42,22 +38,16 @@ #include "core/function/CoreSignalStation.h" #include "core/function/GlobalSettingStation.h" #include "core/module/ModuleManager.h" -#include "core/thread/TaskRunnerGetter.h" #include "ui/UISignalStation.h" #include "ui/UserInterfaceUtils.h" -#include "ui/dialog/gnupg/GnuPGControllerDialog.h" #include "ui/main_window/MainWindow.h" -#if !defined(RELEASE) && defined(WINDOWS) -#include "core/function/GlobalSettingStation.h" -#endif - namespace GpgFrontend::UI { extern void InitLocale(); void WaitEnvCheckingProcess() { - SPDLOG_DEBUG("need to waiting for env checking process"); + GF_UI_LOG_DEBUG("need to waiting for env checking process"); // create and show loading window before starting the main window auto* waiting_dialog = new QProgressDialog(); @@ -75,7 +65,7 @@ void WaitEnvCheckingProcess() { QApplication::connect(CoreSignalStation::GetInstance(), &CoreSignalStation::SignalGoodGnupgEnv, waiting_dialog, [=]() { - SPDLOG_DEBUG("gpg env loaded successfuly"); + GF_UI_LOG_DEBUG("gpg env loaded successfuly"); waiting_dialog->finished(0); waiting_dialog->deleteLater(); }); @@ -87,7 +77,7 @@ void WaitEnvCheckingProcess() { &QEventLoop::quit); QApplication::connect(waiting_dialog, &QProgressDialog::canceled, [=]() { - SPDLOG_DEBUG("cancel clicked on wairing dialog"); + GF_UI_LOG_DEBUG("cancel clicked on wairing dialog"); QApplication::quit(); exit(0); }); @@ -95,12 +85,12 @@ void WaitEnvCheckingProcess() { auto env_state = Module::RetrieveRTValueTypedOrDefault<>("core", "env.state.basic", 0); - SPDLOG_DEBUG("ui is ready to wating for env initialized, env_state: {}", - env_state); + GF_UI_LOG_DEBUG("ui is ready to wating for env initialized, env_state: {}", + env_state); // check twice to avoid some unlucky sitations if (env_state == 1) { - SPDLOG_DEBUG("env state turned initialized before the looper start"); + GF_UI_LOG_DEBUG("env state turned initialized before the looper start"); waiting_dialog->finished(0); waiting_dialog->deleteLater(); return; @@ -160,8 +150,8 @@ void InitGpgFrontendUI(QApplication* /*app*/) { std::string proxy_password = GlobalSettingStation::GetInstance().LookupSettings("proxy.password", std::string{}); - SPDLOG_DEBUG("proxy settings: type {}, host {}, port: {}", proxy_type, - proxy_host, proxy_port); + GF_UI_LOG_DEBUG("proxy settings: type {}, host {}, port: {}", proxy_type, + proxy_host, proxy_port); QNetworkProxy::ProxyType proxy_type_qt = QNetworkProxy::NoProxy; if (proxy_type == "HTTP") { @@ -190,7 +180,7 @@ void InitGpgFrontendUI(QApplication* /*app*/) { QNetworkProxy::setApplicationProxy(proxy); } catch (...) { - SPDLOG_ERROR("setting operation error: proxy setings"); + GF_UI_LOG_ERROR("setting operation error: proxy setings"); // no proxy by default QNetworkProxy::setApplicationProxy(QNetworkProxy::NoProxy); } @@ -211,7 +201,7 @@ auto RunGpgFrontendUI(QApplication* app) -> int { // pre-check, if application need to restart if (CommonUtils::GetInstance()->isApplicationNeedRestart()) { - SPDLOG_DEBUG("application need to restart, before mian window init"); + GF_UI_LOG_DEBUG("application need to restart, before mian window init"); return kDeepRestartCode; } @@ -219,56 +209,14 @@ auto RunGpgFrontendUI(QApplication* app) -> int { main_window->Init(); // show main windows - SPDLOG_DEBUG("main window is ready to show"); + GF_UI_LOG_DEBUG("main window is ready to show"); main_window->show(); // start the main event loop return app->exec(); } -void InitUILoggingSystem(spdlog::level::level_enum level) { - // get the log directory - auto logfile_path = (GlobalSettingStation::GetInstance().GetLogDir() / "ui"); - logfile_path.replace_extension(".log"); - - // sinks - std::vector<spdlog::sink_ptr> sinks; - sinks.push_back(GpgFrontend::SecureCreateSharedObject< - spdlog::sinks::stderr_color_sink_mt>()); - sinks.push_back(GpgFrontend::SecureCreateSharedObject< - spdlog::sinks::rotating_file_sink_mt>(logfile_path.u8string(), - 1048576 * 32, 32)); - - // thread pool - spdlog::init_thread_pool(1024, 2); - - // logger - auto ui_logger = GpgFrontend::SecureCreateSharedObject<spdlog::async_logger>( - "ui", begin(sinks), end(sinks), spdlog::thread_pool()); - ui_logger->set_pattern( - "[%H:%M:%S.%e] [T:%t] [%=6n] %^[%=8l]%$ [%s:%#] [%!] -> %v (+%ius)"); - - // set the level of logger - ui_logger->set_level(level); - - // flush policy - ui_logger->flush_on(spdlog::level::err); - spdlog::flush_every(std::chrono::seconds(5)); - - // register it as default logger - spdlog::set_default_logger(ui_logger); -} - -void ShutdownUILoggingSystem() { -#ifdef WINDOWS - // Under VisualStudio, this must be called before main finishes to workaround - // a known VS issue - spdlog::drop_all(); - spdlog::shutdown(); -#endif -} - -void GPGFRONTEND_UI_EXPORT DestroyGpgFrontendUI() { ShutdownUILoggingSystem(); } +void GPGFRONTEND_UI_EXPORT DestroyGpgFrontendUI() {} /** * @brief setup the locale and load the translations @@ -294,20 +242,20 @@ void InitLocale() { // sync the settings to the file GpgFrontend::GlobalSettingStation::GetInstance().SyncSettings(); - SPDLOG_DEBUG("current system locale: {}", setlocale(LC_ALL, nullptr)); + GF_UI_LOG_DEBUG("current system locale: {}", setlocale(LC_ALL, nullptr)); // read from settings file std::string lang; if (!general.lookupValue("lang", lang)) { - SPDLOG_ERROR(_("could not read properly from configure file")); + GF_UI_LOG_ERROR(_("could not read properly from configure file")); }; - SPDLOG_DEBUG("lang from settings: {}", lang); - SPDLOG_DEBUG("project name: {}", PROJECT_NAME); - SPDLOG_DEBUG("locales path: {}", - GpgFrontend::GlobalSettingStation::GetInstance() - .GetLocaleDir() - .u8string()); + GF_UI_LOG_DEBUG("lang from settings: {}", lang); + GF_UI_LOG_DEBUG("project name: {}", PROJECT_NAME); + GF_UI_LOG_DEBUG("locales path: {}", + GpgFrontend::GlobalSettingStation::GetInstance() + .GetLocaleDir() + .u8string()); #ifndef WINDOWS if (!lang.empty()) { @@ -315,14 +263,14 @@ void InitLocale() { // set LC_ALL auto* locale_name = setlocale(LC_ALL, lc.c_str()); - if (locale_name == nullptr) SPDLOG_WARN("set LC_ALL failed, lc: {}", lc); + if (locale_name == nullptr) GF_UI_LOG_WARN("set LC_ALL failed, lc: {}", lc); auto* language = getenv("LANGUAGE"); // set LANGUAGE std::string language_env = language == nullptr ? "en" : language; language_env.insert(0, lang + ":"); - SPDLOG_DEBUG("language env: {}", language_env); + GF_UI_LOG_DEBUG("language env: {}", language_env); if (setenv("LANGUAGE", language_env.c_str(), 1) != 0) { - SPDLOG_WARN("set LANGUAGE {} failed", language_env); + GF_UI_LOG_WARN("set LANGUAGE {} failed", language_env); }; } #else @@ -331,16 +279,16 @@ void InitLocale() { // set LC_ALL auto* locale_name = setlocale(LC_ALL, lc.c_str()); - if (locale_name == nullptr) SPDLOG_WARN("set LC_ALL failed, lc: {}", lc); + if (locale_name == nullptr) GF_UI_LOG_WARN("set LC_ALL failed, lc: {}", lc); auto language = getenv("LANGUAGE"); // set LANGUAGE std::string language_env = language == nullptr ? "en" : language; language_env.insert(0, lang + ":"); language_env.insert(0, "LANGUAGE="); - SPDLOG_DEBUG("language env: {}", language_env); + GF_UI_LOG_DEBUG("language env: {}", language_env); if (putenv(language_env.c_str())) { - SPDLOG_WARN("set LANGUAGE {} failed", language_env); + GF_UI_LOG_WARN("set LANGUAGE {} failed", language_env); }; } #endif diff --git a/src/ui/GpgFrontendUIInit.h b/src/ui/GpgFrontendUIInit.h index 42c00c5a..fd62f3f6 100644 --- a/src/ui/GpgFrontendUIInit.h +++ b/src/ui/GpgFrontendUIInit.h @@ -45,24 +45,12 @@ void GPGFRONTEND_UI_EXPORT PreInitGpgFrontendUI(); void GPGFRONTEND_UI_EXPORT InitGpgFrontendUI(QApplication *); /** - * @brief - * - */ -void GPGFRONTEND_UI_EXPORT InitUILoggingSystem(spdlog::level::level_enum level); - -/** * @brief init the UI library * */ void GPGFRONTEND_UI_EXPORT DestroyGpgFrontendUI(); /** - * @brief - * - */ -void GPGFRONTEND_UI_EXPORT ShutdownUILoggingSystem(); - -/** * @brief run main window */ auto GPGFRONTEND_UI_EXPORT RunGpgFrontendUI(QApplication *) -> int; diff --git a/src/ui/UserInterfaceUtils.cpp b/src/ui/UserInterfaceUtils.cpp index 81627ee8..bed7fcf2 100644 --- a/src/ui/UserInterfaceUtils.cpp +++ b/src/ui/UserInterfaceUtils.cpp @@ -83,7 +83,7 @@ void import_unknown_key_from_keyserver( auto key_ids = std::make_unique<KeyIdArgsList>(); auto *signature = verify_res.GetSignatures(); while (signature != nullptr) { - SPDLOG_DEBUG("signature fpr: {}", signature->fpr); + GF_UI_LOG_DEBUG("signature fpr: {}", signature->fpr); key_ids->push_back(signature->fpr); signature = signature->next; } @@ -236,8 +236,8 @@ void CommonUtils::WaitForOpera(QWidget *parent, QTimer::singleShot(64, parent, [=]() { opera([dialog]() { - SPDLOG_DEBUG("called operating waiting cb, dialog: {}", - static_cast<void *>(dialog)); + GF_UI_LOG_DEBUG("called operating waiting cb, dialog: {}", + static_cast<void *>(dialog)); dialog->close(); dialog->accept(); }); @@ -319,18 +319,18 @@ void CommonUtils::SlotExecuteCommand( &QEventLoop::quit); connect(cmd_process, &QProcess::errorOccurred, &looper, &QEventLoop::quit); connect(cmd_process, &QProcess::started, - []() -> void { SPDLOG_DEBUG("process started"); }); + []() -> void { GF_UI_LOG_DEBUG("process started"); }); connect(cmd_process, &QProcess::readyReadStandardOutput, [interact_func, cmd_process]() { interact_func(cmd_process); }); connect(cmd_process, &QProcess::errorOccurred, this, - [=]() -> void { SPDLOG_ERROR("error in process"); }); + [=]() -> void { GF_UI_LOG_ERROR("error in process"); }); connect(cmd_process, qOverload<int, QProcess::ExitStatus>(&QProcess::finished), this, [=](int, QProcess::ExitStatus status) { if (status == QProcess::NormalExit) - SPDLOG_DEBUG("succeed in executing command: {}", cmd); + GF_UI_LOG_DEBUG("succeed in executing command: {}", cmd); else - SPDLOG_WARN("error in executing command: {}", cmd); + GF_UI_LOG_WARN("error in executing command: {}", cmd); }); cmd_process->setProgram(QString::fromStdString(cmd)); @@ -356,11 +356,11 @@ void CommonUtils::SlotExecuteGpgCommand( &WaitingDialog::deleteLater); connect(gpg_process, &QProcess::errorOccurred, &looper, &QEventLoop::quit); connect(gpg_process, &QProcess::started, - []() -> void { SPDLOG_DEBUG("gpg process started"); }); + []() -> void { GF_UI_LOG_DEBUG("gpg process started"); }); connect(gpg_process, &QProcess::readyReadStandardOutput, [interact_func, gpg_process]() { interact_func(gpg_process); }); connect(gpg_process, &QProcess::errorOccurred, this, [=]() -> void { - SPDLOG_ERROR("Error in Process"); + GF_UI_LOG_ERROR("Error in Process"); dialog->close(); QMessageBox::critical(nullptr, _("Failure"), _("Failed to execute command.")); @@ -379,7 +379,7 @@ void CommonUtils::SlotExecuteGpgCommand( const auto app_path = Module::RetrieveRTValueTypedOrDefault<>( "core", "gpgme.ctx.app_path", std::string{}); - SPDLOG_DEBUG("got gnupg app path from rt: {}", app_path); + GF_UI_LOG_DEBUG("got gnupg app path from rt: {}", app_path); gpg_process->setProgram(app_path.c_str()); gpg_process->setArguments(arguments); @@ -412,10 +412,10 @@ void CommonUtils::SlotImportKeyFromKeyServer( target_keyserver = key_server_list[target_key_server_index].get<std::string>(); - SPDLOG_DEBUG("set target key server to default Key Server: {}", - target_keyserver); + GF_UI_LOG_DEBUG("set target key server to default Key Server: {}", + target_keyserver); } catch (...) { - SPDLOG_ERROR(_("Cannot read default_keyserver From Settings")); + GF_UI_LOG_ERROR(_("Cannot read default_keyserver From Settings")); QMessageBox::critical(nullptr, _("Default Keyserver Not Found"), _("Cannot read default keyserver from your settings, " "please set a default keyserver first")); @@ -436,7 +436,7 @@ void CommonUtils::SlotImportKeyFromKeyServer( target_keyserver_url.scheme() + "://" + target_keyserver_url.host() + "/pks/lookup?op=get&search=0x" + key_id.c_str() + "&options=mr"); - SPDLOG_DEBUG("request url: {}", req_url.toString().toStdString()); + GF_UI_LOG_DEBUG("request url: {}", req_url.toString().toStdString()); // Waiting for reply QNetworkReply *reply = network_manager->get(QNetworkRequest(req_url)); @@ -523,7 +523,7 @@ void CommonUtils::slot_popup_passphrase_input_dialog() { } void CommonUtils::SlotRestartApplication(int code) { - SPDLOG_DEBUG("application need restart, code: {}", code); + GF_UI_LOG_DEBUG("application need restart, code: {}", code); if (code == 0) { std::exit(0); diff --git a/src/ui/dialog/GeneralDialog.cpp b/src/ui/dialog/GeneralDialog.cpp index 3556c403..d48e878d 100644 --- a/src/ui/dialog/GeneralDialog.cpp +++ b/src/ui/dialog/GeneralDialog.cpp @@ -49,21 +49,22 @@ void GpgFrontend::UI::GeneralDialog::slot_restore_settings() noexcept { if (window_save) { int x = general_windows_state.Check("window_pos").Check("x", 0), y = general_windows_state.Check("window_pos").Check("y", 0); - SPDLOG_DEBUG("stored dialog pos, x: {}, y: {}", x, y); + GF_UI_LOG_DEBUG("stored dialog pos, x: {}, y: {}", x, y); QPoint relative_pos = {x, y}; QPoint pos = parent_rect_.topLeft() + relative_pos; - SPDLOG_DEBUG("relative dialog pos, x: {}, y: {}", relative_pos.x(), - relative_pos.y()); + GF_UI_LOG_DEBUG("relative dialog pos, x: {}, y: {}", relative_pos.x(), + relative_pos.y()); int width = general_windows_state.Check("window_size").Check("width", 0), height = general_windows_state.Check("window_size").Check("height", 0); - SPDLOG_DEBUG("stored dialog size, width: {}, height: {}", width, height); + GF_UI_LOG_DEBUG("stored dialog size, width: {}, height: {}", width, + height); QRect target_rect_ = {pos.x(), pos.y(), width, height}; - SPDLOG_DEBUG("dialog stored target rect, width: {}, height: {}", width, - height); + GF_UI_LOG_DEBUG("dialog stored target rect, width: {}, height: {}", width, + height); // check for valid if (width > 0 && height > 0 && screen_rect_.contains(target_rect_)) { @@ -73,7 +74,7 @@ void GpgFrontend::UI::GeneralDialog::slot_restore_settings() noexcept { } } catch (...) { - SPDLOG_ERROR("error at restoring settings"); + GF_UI_LOG_ERROR("error at restoring settings"); } } @@ -83,14 +84,14 @@ void GpgFrontend::UI::GeneralDialog::slot_save_settings() noexcept { update_rect_cache(); - SPDLOG_DEBUG("dialog pos, x: {}, y: {}", rect_.x(), rect_.y()); - SPDLOG_DEBUG("dialog size, width: {}, height: {}", rect_.width(), - rect_.height()); + GF_UI_LOG_DEBUG("dialog pos, x: {}, y: {}", rect_.x(), rect_.y()); + GF_UI_LOG_DEBUG("dialog size, width: {}, height: {}", rect_.width(), + rect_.height()); // window position relative to parent auto relative_pos = rect_.topLeft() - parent_rect_.topLeft(); - SPDLOG_DEBUG("store dialog pos, x: {}, y: {}", relative_pos.x(), - relative_pos.y()); + GF_UI_LOG_DEBUG("store dialog pos, x: {}, y: {}", relative_pos.x(), + relative_pos.y()); general_windows_state["window_pos"]["x"] = relative_pos.x(); general_windows_state["window_pos"]["y"] = relative_pos.y(); @@ -100,7 +101,7 @@ void GpgFrontend::UI::GeneralDialog::slot_save_settings() noexcept { general_windows_state["window_save"] = true; } catch (...) { - SPDLOG_ERROR(name_, "error"); + GF_UI_LOG_ERROR(name_, "error"); } } @@ -109,8 +110,8 @@ void GpgFrontend::UI::GeneralDialog::setPosCenterOfScreen() { int screen_width = screen_rect_.width(); int screen_height = screen_rect_.height(); - SPDLOG_DEBUG("dialog current screen available geometry", screen_width, - screen_height); + GF_UI_LOG_DEBUG("dialog current screen available geometry", screen_width, + screen_height); // update rect of current dialog rect_ = this->geometry(); @@ -127,14 +128,14 @@ void GpgFrontend::UI::GeneralDialog::movePosition2CenterOfParent() { update_rect_cache(); // log for debug - SPDLOG_DEBUG("parent pos x: {} y: {}", parent_rect_.x(), parent_rect_.y()); - SPDLOG_DEBUG("parent size width: {}, height: {}", parent_rect_.width(), - parent_rect_.height()); - SPDLOG_DEBUG("parent center pos x: {}, y: {}", parent_rect_.center().x(), - parent_rect_.center().y()); - SPDLOG_DEBUG("dialog pos x: {} y: {}", rect_.x(), rect_.y()); - SPDLOG_DEBUG("dialog size width: {} height: {}", rect_.width(), - rect_.height()); + GF_UI_LOG_DEBUG("parent pos x: {} y: {}", parent_rect_.x(), parent_rect_.y()); + GF_UI_LOG_DEBUG("parent size width: {}, height: {}", parent_rect_.width(), + parent_rect_.height()); + GF_UI_LOG_DEBUG("parent center pos x: {}, y: {}", parent_rect_.center().x(), + parent_rect_.center().y()); + GF_UI_LOG_DEBUG("dialog pos x: {} y: {}", rect_.x(), rect_.y()); + GF_UI_LOG_DEBUG("dialog size width: {} height: {}", rect_.width(), + rect_.height()); if (parent_rect_.topLeft() != QPoint{0, 0} && parent_rect_.size() != QSize{0, 0}) { @@ -144,8 +145,9 @@ void GpgFrontend::UI::GeneralDialog::movePosition2CenterOfParent() { QPoint target_position = parent_rect_.center() - QPoint(rect_.width() / 2, rect_.height() / 2); - SPDLOG_DEBUG("update position to parent's center, target pos, x:{}, y: {}", - target_position.x(), target_position.y()); + GF_UI_LOG_DEBUG( + "update position to parent's center, target pos, x:{}, y: {}", + target_position.x(), target_position.y()); this->move(target_position); } else { @@ -199,8 +201,8 @@ bool GpgFrontend::UI::GeneralDialog::isRectRestored() { return rect_restored_; } * */ void GpgFrontend::UI::GeneralDialog::showEvent(QShowEvent *event) { - SPDLOG_DEBUG("General Dialog named {} is about to show, caught show event", - name_); + GF_UI_LOG_DEBUG("General Dialog named {} is about to show, caught show event", + name_); // default position strategy if (!isRectRestored()) movePosition2CenterOfParent(); diff --git a/src/ui/dialog/Wizard.cpp b/src/ui/dialog/Wizard.cpp index f379ffb0..bdb7a669 100644 --- a/src/ui/dialog/Wizard.cpp +++ b/src/ui/dialog/Wizard.cpp @@ -70,7 +70,7 @@ void Wizard::slot_wizard_accepted() { } GlobalSettingStation::GetInstance().SyncSettings(); } catch (...) { - SPDLOG_ERROR("setting operation error"); + GF_UI_LOG_ERROR("setting operation error"); } if (field("openHelp").toBool()) { emit SignalOpenHelp("docu.html#content"); diff --git a/src/ui/dialog/gnupg/GnuPGControllerDialog.cpp b/src/ui/dialog/gnupg/GnuPGControllerDialog.cpp index 57e972cd..d2bbf07b 100644 --- a/src/ui/dialog/gnupg/GnuPGControllerDialog.cpp +++ b/src/ui/dialog/gnupg/GnuPGControllerDialog.cpp @@ -95,8 +95,8 @@ GnuPGControllerDialog::GnuPGControllerDialog(QWidget* parent) this, _("Open Directory"), {}, QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks); - SPDLOG_DEBUG("key databse path selected: {}", - selected_custom_key_database_path.toStdString()); + GF_UI_LOG_DEBUG("key databse path selected: {}", + selected_custom_key_database_path.toStdString()); if (!check_custom_gnupg_key_database_path( selected_custom_key_database_path.toStdString())) { @@ -131,8 +131,8 @@ GnuPGControllerDialog::GnuPGControllerDialog(QWidget* parent) this, _("Open Directory"), {}, QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks); - SPDLOG_DEBUG("gnupg install path selected: {}", - selected_custom_gnupg_install_path.toStdString()); + GF_UI_LOG_DEBUG("gnupg install path selected: {}", + selected_custom_gnupg_install_path.toStdString()); // notify the user and precheck if (!check_custom_gnupg_path( @@ -189,12 +189,12 @@ GnuPGControllerDialog::GnuPGControllerDialog(QWidget* parent) void GnuPGControllerDialog::SlotAccept() { apply_settings(); - SPDLOG_DEBUG("gnupg controller apply done"); + GF_UI_LOG_DEBUG("gnupg controller apply done"); // write settings to filesystem GlobalSettingStation::GetInstance().SyncSettings(); - SPDLOG_DEBUG("restart needed: {}", get_restart_needed()); + GF_UI_LOG_DEBUG("restart needed: {}", get_restart_needed()); if (get_restart_needed()) { emit SignalRestartNeeded(get_restart_needed()); } @@ -208,7 +208,7 @@ void GnuPGControllerDialog::slot_update_custom_key_database_path_label( const auto database_path = Module::RetrieveRTValueTypedOrDefault<>( "core", "gpgme.ctx.database_path", std::string{}); - SPDLOG_DEBUG("got gpgme.ctx.database_path from rt: {}", database_path); + GF_UI_LOG_DEBUG("got gpgme.ctx.database_path from rt: {}", database_path); if (state != Qt::CheckState::Checked) { ui_->currentKeyDatabasePathLabel->setText( @@ -222,8 +222,8 @@ void GnuPGControllerDialog::slot_update_custom_key_database_path_label( GlobalSettingStation::GetInstance().LookupSettings( "general.custom_key_database_path", std::string{}); - SPDLOG_DEBUG("selected_custom_key_database_path from settings: {}", - custom_key_database_path); + GF_UI_LOG_DEBUG("selected_custom_key_database_path from settings: {}", + custom_key_database_path); // notify the user check_custom_gnupg_key_database_path(custom_key_database_path); @@ -247,7 +247,7 @@ void GnuPGControllerDialog::slot_update_custom_gnupg_install_path_label( const auto home_path = Module::RetrieveRTValueTypedOrDefault<>( "com.bktus.gpgfrontend.module.integrated.gnupg-info-gathering", "gnupg.home_path", std::string{}); - SPDLOG_DEBUG("got gnupg home path from rt: {}", home_path); + GF_UI_LOG_DEBUG("got gnupg home path from rt: {}", home_path); if (state != Qt::CheckState::Checked) { ui_->currentCustomGnuPGInstallPathLabel->setText( @@ -261,8 +261,8 @@ void GnuPGControllerDialog::slot_update_custom_gnupg_install_path_label( GlobalSettingStation::GetInstance().LookupSettings( "general.custom_gnupg_install_path", std::string{}); - SPDLOG_DEBUG("custom_gnupg_install_path from settings: {}", - custom_gnupg_install_path); + GF_UI_LOG_DEBUG("custom_gnupg_install_path from settings: {}", + custom_gnupg_install_path); // notify the user check_custom_gnupg_path(custom_gnupg_install_path); @@ -284,11 +284,11 @@ void GnuPGControllerDialog::set_settings() { try { bool non_ascii_when_export = settings.lookup("general.non_ascii_when_export"); - SPDLOG_DEBUG("non_ascii_when_export: {}", non_ascii_when_export); + GF_UI_LOG_DEBUG("non_ascii_when_export: {}", non_ascii_when_export); if (non_ascii_when_export) ui_->asciiModeCheckBox->setCheckState(Qt::Checked); } catch (...) { - SPDLOG_ERROR("setting operation error: non_ascii_when_export"); + GF_UI_LOG_ERROR("setting operation error: non_ascii_when_export"); } try { @@ -297,7 +297,7 @@ void GnuPGControllerDialog::set_settings() { if (use_custom_key_database_path) ui_->keyDatabseUseCustomCheckBox->setCheckState(Qt::Checked); } catch (...) { - SPDLOG_ERROR("setting operation error: use_custom_key_database_path"); + GF_UI_LOG_ERROR("setting operation error: use_custom_key_database_path"); } this->slot_update_custom_key_database_path_label( @@ -309,7 +309,7 @@ void GnuPGControllerDialog::set_settings() { if (use_custom_gnupg_install_path) ui_->useCustomGnuPGInstallPathCheckBox->setCheckState(Qt::Checked); } catch (...) { - SPDLOG_ERROR("setting operation error: use_custom_gnupg_install_path"); + GF_UI_LOG_ERROR("setting operation error: use_custom_gnupg_install_path"); } try { @@ -318,7 +318,7 @@ void GnuPGControllerDialog::set_settings() { if (use_pinentry_as_password_input_dialog) ui_->usePinentryAsPasswordInputDialogCheckBox->setCheckState(Qt::Checked); } catch (...) { - SPDLOG_ERROR( + GF_UI_LOG_ERROR( "setting operation error: use_pinentry_as_password_input_dialog"); } diff --git a/src/ui/dialog/help/AboutDialog.cpp b/src/ui/dialog/help/AboutDialog.cpp index 8d5ad896..7c534cbf 100644 --- a/src/ui/dialog/help/AboutDialog.cpp +++ b/src/ui/dialog/help/AboutDialog.cpp @@ -57,7 +57,7 @@ AboutDialog::AboutDialog(int defaultIndex, QWidget* parent) tab_widget->addTab(update_tab_, _("Update")); connect(tab_widget, &QTabWidget::currentChanged, this, - [&](int index) { SPDLOG_DEBUG("current index: {}", index); }); + [&](int index) { GF_UI_LOG_DEBUG("current index: {}", index); }); if (defaultIndex < tab_widget->count() && defaultIndex >= 0) { tab_widget->setCurrentIndex(defaultIndex); @@ -81,7 +81,7 @@ void AboutDialog::showEvent(QShowEvent* ev) { QDialog::showEvent(ev); } InfoTab::InfoTab(QWidget* parent) : QWidget(parent) { const auto gpgme_version = Module::RetrieveRTValueTypedOrDefault<>( "core", "gpgme.version", std::string{"2.0.0"}); - SPDLOG_DEBUG("got gpgme version from rt: {}", gpgme_version); + GF_UI_LOG_DEBUG("got gpgme version from rt: {}", gpgme_version); auto* pixmap = new QPixmap(":gpgfrontend-logo.png"); auto* text = new QString( @@ -205,7 +205,7 @@ UpdateTab::UpdateTab(QWidget* parent) : QWidget(parent) { void UpdateTab::showEvent(QShowEvent* event) { QWidget::showEvent(event); - SPDLOG_DEBUG("loading version loading info from rt"); + GF_UI_LOG_DEBUG("loading version loading info from rt"); auto is_loading_done = Module::RetrieveRTValueTypedOrDefault<>( "com.bktus.gpgfrontend.module.integrated.version-checking", @@ -216,7 +216,7 @@ void UpdateTab::showEvent(QShowEvent* event) { this, "com.bktus.gpgfrontend.module.integrated.version-checking", "version.loading_done", [=](Module::Namespace, Module::Key, int, std::any) { - SPDLOG_DEBUG( + GF_UI_LOG_DEBUG( "versionchecking version.loading_done changed, calling slot " "version upgrade"); this->slot_show_version_status(); @@ -228,7 +228,7 @@ void UpdateTab::showEvent(QShowEvent* event) { } void UpdateTab::slot_show_version_status() { - SPDLOG_DEBUG("loading version info from rt"); + GF_UI_LOG_DEBUG("loading version info from rt"); this->pb_->setHidden(true); auto is_loading_done = Module::RetrieveRTValueTypedOrDefault<>( @@ -236,7 +236,7 @@ void UpdateTab::slot_show_version_status() { "version.loading_done", false); if (!is_loading_done) { - SPDLOG_DEBUG("version info loading havn't been done yet."); + GF_UI_LOG_DEBUG("version info loading havn't been done yet."); return; } diff --git a/src/ui/dialog/help/GnupgTab.cpp b/src/ui/dialog/help/GnupgTab.cpp index cd48d2a8..ba5e464a 100644 --- a/src/ui/dialog/help/GnupgTab.cpp +++ b/src/ui/dialog/help/GnupgTab.cpp @@ -88,7 +88,7 @@ GpgFrontend::UI::GnupgTab::GnupgTab(QWidget* parent) void GpgFrontend::UI::GnupgTab::process_software_info() { const auto gnupg_version = Module::RetrieveRTValueTypedOrDefault<>( "core", "gpgme.ctx.gnupg_version", std::string{"2.0.0"}); - SPDLOG_DEBUG("got gnupg version from rt: {}", gnupg_version); + GF_UI_LOG_DEBUG("got gnupg version from rt: {}", gnupg_version); ui_->gnupgVersionLabel->setText( QString::fromStdString(fmt::format("Version: {}", gnupg_version))); @@ -96,7 +96,7 @@ void GpgFrontend::UI::GnupgTab::process_software_info() { auto components = Module::ListRTChildKeys( "com.bktus.gpgfrontend.module.integrated.gnupg-info-gathering", "gnupg.components"); - SPDLOG_DEBUG("got gnupg components from rt, size: {}", components.size()); + GF_UI_LOG_DEBUG("got gnupg components from rt, size: {}", components.size()); ui_->componentDetailsTable->setRowCount(components.size()); @@ -106,14 +106,14 @@ void GpgFrontend::UI::GnupgTab::process_software_info() { "com.bktus.gpgfrontend.module.integrated.gnupg-info-gathering", (boost::format("gnupg.components.%1%") % component).str(), std::string{}); - SPDLOG_DEBUG("got gnupg component {} info from rt, info: {}", component, - component_info_json); + GF_UI_LOG_DEBUG("got gnupg component {} info from rt, info: {}", component, + component_info_json); auto component_info = nlohmann::json::parse(component_info_json); if (!component_info.contains("name")) { - SPDLOG_WARN("illegal gnupg component info, json: {}", - component_info_json); + GF_UI_LOG_WARN("illegal gnupg component info, json: {}", + component_info_json); continue; } @@ -184,14 +184,14 @@ void GpgFrontend::UI::GnupgTab::process_software_info() { option) .str(), std::string{}); - SPDLOG_DEBUG("got gnupg component's option {} info from rt, info: {}", - component, option_info_json); + GF_UI_LOG_DEBUG("got gnupg component's option {} info from rt, info: {}", + component, option_info_json); auto option_info = nlohmann::json::parse(option_info_json); if (!option_info.contains("name")) { - SPDLOG_WARN("illegal gnupg configuation info, json: {}", - option_info_json); + GF_UI_LOG_WARN("illegal gnupg configuation info, json: {}", + option_info_json); continue; } diff --git a/src/ui/dialog/import_export/KeyServerImportDialog.cpp b/src/ui/dialog/import_export/KeyServerImportDialog.cpp index e8b9eb95..3a23b0df 100644 --- a/src/ui/dialog/import_export/KeyServerImportDialog.cpp +++ b/src/ui/dialog/import_export/KeyServerImportDialog.cpp @@ -191,7 +191,7 @@ auto KeyServerImportDialog::create_comboBox() -> QComboBox* { combo_box->setCurrentText(default_key_server.c_str()); } catch (...) { - SPDLOG_ERROR("setting operation error", "server_list", "default_server"); + GF_UI_LOG_ERROR("setting operation error", "server_list", "default_server"); } return combo_box; @@ -270,7 +270,7 @@ void KeyServerImportDialog::slot_search() { void KeyServerImportDialog::slot_search_finished( QNetworkReply::NetworkError error, QByteArray buffer) { - SPDLOG_DEBUG("search result {} {}", error, buffer.size()); + GF_UI_LOG_DEBUG("search result {} {}", error, buffer.size()); keys_table_->clearContents(); keys_table_->setRowCount(0); @@ -278,7 +278,7 @@ void KeyServerImportDialog::slot_search_finished( auto stream = QTextStream(buffer); if (error != QNetworkReply::NoError) { - SPDLOG_DEBUG("error from reply: {}", error); + GF_UI_LOG_DEBUG("error from reply: {}", error); switch (error) { case QNetworkReply::ContentNotFoundError: @@ -463,7 +463,8 @@ void KeyServerImportDialog::SlotImport(const KeyIdArgsListPtr& keys) { target_keyserver = default_key_server; } catch (...) { - SPDLOG_ERROR("setting operation error", "server_list", "default_server"); + GF_UI_LOG_ERROR("setting operation error", "server_list", + "default_server"); QMessageBox::critical( nullptr, _("Default Keyserver Not Found"), _("Cannot read default keyserver from your settings, " @@ -494,7 +495,7 @@ void KeyServerImportDialog::SlotImport(std::vector<std::string> key_ids, void KeyServerImportDialog::slot_import_finished( QNetworkReply::NetworkError error, QByteArray buffer) { if (error != QNetworkReply::NoError) { - SPDLOG_ERROR("Error From Reply", buffer.toStdString()); + GF_UI_LOG_ERROR("Error From Reply", buffer.toStdString()); if (!m_automatic_) { switch (error) { case QNetworkReply::ContentNotFoundError: diff --git a/src/ui/dialog/import_export/KeyUploadDialog.cpp b/src/ui/dialog/import_export/KeyUploadDialog.cpp index cc438364..f12149d8 100644 --- a/src/ui/dialog/import_export/KeyUploadDialog.cpp +++ b/src/ui/dialog/import_export/KeyUploadDialog.cpp @@ -89,11 +89,11 @@ void KeyUploadDialog::slot_upload_key_to_server( target_keyserver = key_server_list[default_key_server_index].get<std::string>(); - SPDLOG_DEBUG("set target key server to default key server: {}", - target_keyserver); + GF_UI_LOG_DEBUG("set target key server to default key server: {}", + target_keyserver); } catch (...) { - SPDLOG_ERROR(_("Cannot read default_keyserver From Settings")); + GF_UI_LOG_ERROR(_("Cannot read default_keyserver From Settings")); QMessageBox::critical(nullptr, _("Default Keyserver Not Found"), _("Cannot read default keyserver from your settings, " "please set a default keyserver first")); @@ -140,11 +140,11 @@ void KeyUploadDialog::slot_upload_finished() { auto* reply = qobject_cast<QNetworkReply*>(sender()); QByteArray response = reply->readAll(); - SPDLOG_DEBUG("response: {}", response.toStdString()); + GF_UI_LOG_DEBUG("response: {}", response.toStdString()); auto error = reply->error(); if (error != QNetworkReply::NoError) { - SPDLOG_DEBUG("error from reply: {}", reply->errorString().toStdString()); + GF_UI_LOG_DEBUG("error from reply: {}", reply->errorString().toStdString()); QString message; switch (error) { case QNetworkReply::ContentNotFoundError: @@ -164,7 +164,7 @@ void KeyUploadDialog::slot_upload_finished() { } else { QMessageBox::information(this, _("Upload Success"), _("Upload Public Key Successfully")); - SPDLOG_DEBUG("success while contacting keyserver!"); + GF_UI_LOG_DEBUG("success while contacting keyserver!"); } reply->deleteLater(); } diff --git a/src/ui/dialog/key_generate/KeygenDialog.cpp b/src/ui/dialog/key_generate/KeygenDialog.cpp index 61d07189..94cedc7f 100644 --- a/src/ui/dialog/key_generate/KeygenDialog.cpp +++ b/src/ui/dialog/key_generate/KeygenDialog.cpp @@ -151,7 +151,7 @@ void KeyGenDialog::slot_key_gen_accept() { }); }); - SPDLOG_DEBUG("key generation done"); + GF_UI_LOG_DEBUG("key generation done"); this->done(0); } else { @@ -242,7 +242,7 @@ void KeyGenDialog::slot_authentication_box_changed(int state) { } void KeyGenDialog::slot_activated_key_type(int index) { - SPDLOG_DEBUG("key type index changed: {}", index); + GF_UI_LOG_DEBUG("key type index changed: {}", index); // check assert(gen_key_info_->GetSupportedKeyAlgo().size() > diff --git a/src/ui/dialog/key_generate/SubkeyGenerateDialog.cpp b/src/ui/dialog/key_generate/SubkeyGenerateDialog.cpp index c0e8b240..4724344c 100644 --- a/src/ui/dialog/key_generate/SubkeyGenerateDialog.cpp +++ b/src/ui/dialog/key_generate/SubkeyGenerateDialog.cpp @@ -344,7 +344,7 @@ void SubkeyGenerateDialog::slot_authentication_box_changed(int state) { } void SubkeyGenerateDialog::slot_activated_key_type(int index) { - SPDLOG_DEBUG("key type index changed: {}", index); + GF_UI_LOG_DEBUG("key type index changed: {}", index); // check assert(gen_key_info_->GetSupportedSubkeyAlgo().size() > diff --git a/src/ui/dialog/keypair_details/KeyPairDetailTab.cpp b/src/ui/dialog/keypair_details/KeyPairDetailTab.cpp index 286192f2..673ff889 100644 --- a/src/ui/dialog/keypair_details/KeyPairDetailTab.cpp +++ b/src/ui/dialog/keypair_details/KeyPairDetailTab.cpp @@ -39,8 +39,8 @@ namespace GpgFrontend::UI { KeyPairDetailTab::KeyPairDetailTab(const std::string& key_id, QWidget* parent) : QWidget(parent), key_(GpgKeyGetter::GetInstance().GetKey(key_id)) { - SPDLOG_DEBUG(key_.GetEmail(), key_.IsPrivateKey(), key_.IsHasMasterKey(), - key_.GetSubKeys()->front().IsPrivateKey()); + GF_UI_LOG_DEBUG(key_.GetEmail(), key_.IsPrivateKey(), key_.IsHasMasterKey(), + key_.GetSubKeys()->front().IsPrivateKey()); owner_box_ = new QGroupBox(_("Owner")); key_box_ = new QGroupBox(_("Primary Key")); diff --git a/src/ui/dialog/keypair_details/KeyPairOperaTab.cpp b/src/ui/dialog/keypair_details/KeyPairOperaTab.cpp index 8fa7eb9c..9513c3c4 100644 --- a/src/ui/dialog/keypair_details/KeyPairOperaTab.cpp +++ b/src/ui/dialog/keypair_details/KeyPairOperaTab.cpp @@ -89,7 +89,7 @@ KeyPairOperaTab::KeyPairOperaTab(const std::string& key_id, QWidget* parent) forbid_all_gnupg_connection = settings.lookup("network.forbid_all_gnupg_connection"); } catch (...) { - SPDLOG_ERROR("setting operation error: forbid_all_gnupg_connection"); + GF_UI_LOG_ERROR("setting operation error: forbid_all_gnupg_connection"); } auto* key_server_opera_button = @@ -369,7 +369,7 @@ void KeyPairOperaTab::slot_modify_tofu_policy() { this, _("Modify TOFU Policy(Default is Auto)"), _("Policy for the Key Pair:"), items, 0, false, &ok); if (ok && !item.isEmpty()) { - SPDLOG_DEBUG("selected policy: {}", item.toStdString()); + GF_UI_LOG_DEBUG("selected policy: {}", item.toStdString()); gpgme_tofu_policy_t tofu_policy = GPGME_TOFU_POLICY_AUTO; if (item == _("Policy Auto")) { tofu_policy = GPGME_TOFU_POLICY_AUTO; diff --git a/src/ui/dialog/keypair_details/KeyPairSubkeyTab.cpp b/src/ui/dialog/keypair_details/KeyPairSubkeyTab.cpp index d7b4e47b..f6a5410e 100644 --- a/src/ui/dialog/keypair_details/KeyPairSubkeyTab.cpp +++ b/src/ui/dialog/keypair_details/KeyPairSubkeyTab.cpp @@ -37,8 +37,8 @@ namespace GpgFrontend::UI { KeyPairSubkeyTab::KeyPairSubkeyTab(const std::string& key_id, QWidget* parent) : QWidget(parent), key_(GpgKeyGetter::GetInstance().GetKey(key_id)) { - SPDLOG_DEBUG(key_.GetEmail(), key_.IsPrivateKey(), key_.IsHasMasterKey(), - key_.GetSubKeys()->front().IsPrivateKey()); + GF_UI_LOG_DEBUG(key_.GetEmail(), key_.IsPrivateKey(), key_.IsHasMasterKey(), + key_.GetSubKeys()->front().IsPrivateKey()); create_subkey_list(); create_subkey_opera_menu(); @@ -178,8 +178,8 @@ void KeyPairSubkeyTab::slot_refresh_subkey_list() { this->buffered_subkeys_.push_back(std::move(sub_key)); } - SPDLOG_DEBUG("buffered_subkeys_ refreshed size", - this->buffered_subkeys_.size()); + GF_UI_LOG_DEBUG("buffered_subkeys_ refreshed size", + this->buffered_subkeys_.size()); subkey_list_->setRowCount(buffered_subkeys_.size()); @@ -216,12 +216,12 @@ void KeyPairSubkeyTab::slot_refresh_subkey_list() { } } - SPDLOG_DEBUG("subkey_list_ item {} refreshed", row); + GF_UI_LOG_DEBUG("subkey_list_ item {} refreshed", row); row++; } - SPDLOG_DEBUG("subkey_list_ refreshed"); + GF_UI_LOG_DEBUG("subkey_list_ refreshed"); if (subkey_list_->rowCount() > 0) { subkey_list_->selectRow(0); @@ -327,7 +327,7 @@ void KeyPairSubkeyTab::create_subkey_opera_menu() { } void KeyPairSubkeyTab::slot_edit_subkey() { - SPDLOG_DEBUG("fpr {}", get_selected_subkey().GetFingerprint()); + GF_UI_LOG_DEBUG("fpr {}", get_selected_subkey().GetFingerprint()); auto dialog = new KeySetExpireDateDialog( key_.GetId(), get_selected_subkey().GetFingerprint(), this); diff --git a/src/ui/dialog/keypair_details/KeyPairUIDTab.cpp b/src/ui/dialog/keypair_details/KeyPairUIDTab.cpp index 1738be7a..20d47137 100644 --- a/src/ui/dialog/keypair_details/KeyPairUIDTab.cpp +++ b/src/ui/dialog/keypair_details/KeyPairUIDTab.cpp @@ -228,7 +228,7 @@ void KeyPairUIDTab::slot_refresh_tofu_info() { continue; } auto tofu_infos = uid.GetTofuInfos(); - SPDLOG_DEBUG("tofu info size: {}", tofu_infos->size()); + GF_UI_LOG_DEBUG("tofu info size: {}", tofu_infos->size()); if (tofu_infos->empty()) { tofu_tabs_->hide(); } else { @@ -400,7 +400,7 @@ void KeyPairUIDTab::slot_del_uid() { if (ret == QMessageBox::Yes) { for (const auto& uid : *selected_uids) { - SPDLOG_DEBUG("uid: {}", uid); + GF_UI_LOG_DEBUG("uid: {}", uid); if (!GpgUIDOperator::GetInstance().RevUID(m_key_, uid)) { QMessageBox::critical( nullptr, _("Operation Failed"), diff --git a/src/ui/dialog/keypair_details/KeySetExpireDateDialog.cpp b/src/ui/dialog/keypair_details/KeySetExpireDateDialog.cpp index 7730b25b..f81b85e9 100644 --- a/src/ui/dialog/keypair_details/KeySetExpireDateDialog.cpp +++ b/src/ui/dialog/keypair_details/KeySetExpireDateDialog.cpp @@ -60,8 +60,9 @@ KeySetExpireDateDialog::KeySetExpireDateDialog(const KeyId& key_id, } void KeySetExpireDateDialog::slot_confirm() { - SPDLOG_DEBUG("called: {} {}", ui_->dateEdit->date().toString().toStdString(), - ui_->timeEdit->time().toString().toStdString()); + GF_UI_LOG_DEBUG("called: {} {}", + ui_->dateEdit->date().toString().toStdString(), + ui_->timeEdit->time().toString().toStdString()); auto datetime = QDateTime(ui_->dateEdit->date(), ui_->timeEdit->time()); std::unique_ptr<boost::posix_time::ptime> expires = nullptr; if (ui_->noExpirationCheckBox->checkState() == Qt::Unchecked) { @@ -73,10 +74,10 @@ void KeySetExpireDateDialog::slot_confirm() { expires = std::make_unique<boost::posix_time::ptime>( boost::posix_time::from_time_t(datetime.toLocalTime().toTime_t())); #endif - SPDLOG_DEBUG("keyid: {}", m_key_.GetId(), m_subkey_, - to_iso_string(*expires)); + GF_UI_LOG_DEBUG("keyid: {}", m_key_.GetId(), m_subkey_, + to_iso_string(*expires)); } else { - SPDLOG_DEBUG("keyid: {}", m_key_.GetId(), m_subkey_, "Non Expired"); + GF_UI_LOG_DEBUG("keyid: {}", m_key_.GetId(), m_subkey_, "Non Expired"); } auto err = GpgKeyOpera::GetInstance().SetExpire(m_key_, m_subkey_, expires); @@ -108,10 +109,10 @@ void KeySetExpireDateDialog::init() { bool longer_expiration_date = false; try { longer_expiration_date = settings.lookup("general.longer_expiration_date"); - SPDLOG_DEBUG("longer_expiration_date: {}", longer_expiration_date); + GF_UI_LOG_DEBUG("longer_expiration_date: {}", longer_expiration_date); } catch (...) { - SPDLOG_ERROR("setting operation error: longer_expiration_date"); + GF_UI_LOG_ERROR("setting operation error: longer_expiration_date"); } auto max_date_time = diff --git a/src/ui/dialog/keypair_details/KeyUIDSignDialog.cpp b/src/ui/dialog/keypair_details/KeyUIDSignDialog.cpp index 54b6298a..97f20289 100644 --- a/src/ui/dialog/keypair_details/KeyUIDSignDialog.cpp +++ b/src/ui/dialog/keypair_details/KeyUIDSignDialog.cpp @@ -108,7 +108,7 @@ void KeyUIDSignDialog::slot_sign_key(bool clicked) { auto key_ids = m_key_list_->GetChecked(); auto keys = GpgKeyGetter::GetInstance().GetKeys(key_ids); - SPDLOG_DEBUG("key info got"); + GF_UI_LOG_DEBUG("key info got"); #ifdef GPGFRONTEND_GUI_QT6 auto expires = std::make_unique<boost::posix_time::ptime>(boost::posix_time::from_time_t( @@ -118,9 +118,9 @@ void KeyUIDSignDialog::slot_sign_key(bool clicked) { boost::posix_time::from_time_t(expires_edit_->dateTime().toTime_t())); #endif - SPDLOG_DEBUG("sign start"); + GF_UI_LOG_DEBUG("sign start"); for (const auto& uid : *m_uids_) { - SPDLOG_DEBUG("sign uid: {}", uid); + GF_UI_LOG_DEBUG("sign uid: {}", uid); // Sign For mKey if (!GpgKeyManager::GetInstance().SignKey(m_key_, *keys, uid, expires)) { QMessageBox::critical( diff --git a/src/ui/dialog/settings/SettingsDialog.cpp b/src/ui/dialog/settings/SettingsDialog.cpp index 5f083408..9815ba76 100644 --- a/src/ui/dialog/settings/SettingsDialog.cpp +++ b/src/ui/dialog/settings/SettingsDialog.cpp @@ -114,12 +114,12 @@ void SettingsDialog::SlotAccept() { key_server_tab_->ApplySettings(); network_tab_->ApplySettings(); - SPDLOG_DEBUG("apply done"); + GF_UI_LOG_DEBUG("apply done"); // write settings to filesystem GlobalSettingStation::GetInstance().SyncSettings(); - SPDLOG_DEBUG("restart needed: {}", get_restart_needed()); + GF_UI_LOG_DEBUG("restart needed: {}", get_restart_needed()); if (get_restart_needed()) { emit SignalRestartNeeded(get_restart_needed()); } @@ -138,7 +138,7 @@ QHash<QString, QString> SettingsDialog::ListLanguages() { for (int i = 0; i < file_names.size(); ++i) { QString locale = file_names[i]; - SPDLOG_DEBUG("locale: {}", locale.toStdString()); + GF_UI_LOG_DEBUG("locale: {}", locale.toStdString()); if (locale == "." || locale == "..") continue; // this works in qt 4.8 diff --git a/src/ui/dialog/settings/SettingsGeneral.cpp b/src/ui/dialog/settings/SettingsGeneral.cpp index eb698468..da5b4d05 100644 --- a/src/ui/dialog/settings/SettingsGeneral.cpp +++ b/src/ui/dialog/settings/SettingsGeneral.cpp @@ -127,7 +127,7 @@ void GeneralTab::SetSettings() { if (save_key_checked) ui_->saveCheckedKeysCheckBox->setCheckState(Qt::Checked); } catch (...) { - SPDLOG_ERROR("setting operation error: save_key_checked"); + GF_UI_LOG_ERROR("setting operation error: save_key_checked"); } try { @@ -136,7 +136,7 @@ void GeneralTab::SetSettings() { if (clear_gpg_password_cache) ui_->clearGpgPasswordCacheCheckBox->setCheckState(Qt::Checked); } catch (...) { - SPDLOG_ERROR("setting operation error: clear_gpg_password_cache"); + GF_UI_LOG_ERROR("setting operation error: clear_gpg_password_cache"); } try { @@ -145,24 +145,24 @@ void GeneralTab::SetSettings() { if (restore_text_editor_page) ui_->restoreTextEditorPageCheckBox->setCheckState(Qt::Checked); } catch (...) { - SPDLOG_ERROR("setting operation error: restore_text_editor_page"); + GF_UI_LOG_ERROR("setting operation error: restore_text_editor_page"); } try { bool longer_expiration_date = settings.lookup("general.longer_expiration_date"); - SPDLOG_DEBUG("longer_expiration_date: {}", longer_expiration_date); + GF_UI_LOG_DEBUG("longer_expiration_date: {}", longer_expiration_date); if (longer_expiration_date) ui_->longerKeyExpirationDateCheckBox->setCheckState(Qt::Checked); } catch (...) { - SPDLOG_ERROR("setting operation error: longer_expiration_date"); + GF_UI_LOG_ERROR("setting operation error: longer_expiration_date"); } #ifdef SUPPORT_MULTI_LANG try { std::string lang_key = settings.lookup("general.lang"); QString lang_value = lang_.value(lang_key.c_str()); - SPDLOG_DEBUG("lang settings current: {}", lang_value.toStdString()); + GF_UI_LOG_DEBUG("lang settings current: {}", lang_value.toStdString()); if (!lang_.empty()) { ui_->langSelectBox->setCurrentIndex( ui_->langSelectBox->findText(lang_value)); @@ -170,17 +170,17 @@ void GeneralTab::SetSettings() { ui_->langSelectBox->setCurrentIndex(0); } } catch (...) { - SPDLOG_ERROR("setting operation error: lang"); + GF_UI_LOG_ERROR("setting operation error: lang"); } #endif try { bool confirm_import_keys = settings.lookup("general.confirm_import_keys"); - SPDLOG_DEBUG("confirm_import_keys: {}", confirm_import_keys); + GF_UI_LOG_DEBUG("confirm_import_keys: {}", confirm_import_keys); if (confirm_import_keys) ui_->importConfirmationCheckBox->setCheckState(Qt::Checked); } catch (...) { - SPDLOG_ERROR("setting operation error: confirm_import_keys"); + GF_UI_LOG_ERROR("setting operation error: confirm_import_keys"); } } diff --git a/src/ui/dialog/settings/SettingsKeyServer.cpp b/src/ui/dialog/settings/SettingsKeyServer.cpp index 784721bf..617955f7 100644 --- a/src/ui/dialog/settings/SettingsKeyServer.cpp +++ b/src/ui/dialog/settings/SettingsKeyServer.cpp @@ -77,7 +77,7 @@ KeyserverTab::KeyserverTab(QWidget* parent) connect(ui_->keyServerListTable, &QTableWidget::itemChanged, [=](QTableWidgetItem* item) { - SPDLOG_DEBUG("item edited: {}", item->column()); + GF_UI_LOG_DEBUG("item edited: {}", item->column()); if (item->column() != 1) return; const auto row_size = ui_->keyServerListTable->rowCount(); // Update Actions @@ -141,7 +141,7 @@ void KeyserverTab::SetSettings() { key_server_str_list_.append(default_key_server.c_str()); default_key_server_ = QString::fromStdString(default_key_server); } catch (const std::exception& e) { - SPDLOG_ERROR("Error reading key-server settings: ", e.what()); + GF_UI_LOG_ERROR("Error reading key-server settings: ", e.what()); } } @@ -192,7 +192,7 @@ void KeyserverTab::ApplySettings() { } void KeyserverTab::slot_refresh_table() { - SPDLOG_INFO("start refreshing key server table"); + GF_UI_LOG_INFO("start refreshing key server table"); ui_->keyServerListTable->blockSignals(true); ui_->keyServerListTable->setRowCount(key_server_str_list_.size()); diff --git a/src/ui/dialog/settings/SettingsNetwork.cpp b/src/ui/dialog/settings/SettingsNetwork.cpp index 46941062..f6b96300 100644 --- a/src/ui/dialog/settings/SettingsNetwork.cpp +++ b/src/ui/dialog/settings/SettingsNetwork.cpp @@ -104,28 +104,28 @@ void GpgFrontend::UI::NetworkTab::SetSettings() { std::string proxy_host = settings.lookup("proxy.proxy_host"); ui_->proxyServerAddressEdit->setText(proxy_host.c_str()); } catch (...) { - SPDLOG_ERROR("setting operation error: proxy_host"); + GF_UI_LOG_ERROR("setting operation error: proxy_host"); } try { std::string std_username = settings.lookup("proxy.username"); ui_->usernameEdit->setText(std_username.c_str()); } catch (...) { - SPDLOG_ERROR("setting operation error: username"); + GF_UI_LOG_ERROR("setting operation error: username"); } try { std::string std_password = settings.lookup("proxy.password"); ui_->passwordEdit->setText(std_password.c_str()); } catch (...) { - SPDLOG_ERROR("setting operation error: password"); + GF_UI_LOG_ERROR("setting operation error: password"); } try { int port = settings.lookup("proxy.port"); ui_->portSpin->setValue(port); } catch (...) { - SPDLOG_ERROR("setting operation error: port"); + GF_UI_LOG_ERROR("setting operation error: port"); } ui_->proxyTypeComboBox->setCurrentText("HTTP"); @@ -133,7 +133,7 @@ void GpgFrontend::UI::NetworkTab::SetSettings() { std::string proxy_type = settings.lookup("proxy.proxy_type"); ui_->proxyTypeComboBox->setCurrentText(proxy_type.c_str()); } catch (...) { - SPDLOG_ERROR("setting operation error: proxy_type"); + GF_UI_LOG_ERROR("setting operation error: proxy_type"); } switch_ui_proxy_type(ui_->proxyTypeComboBox->currentText()); @@ -145,7 +145,7 @@ void GpgFrontend::UI::NetworkTab::SetSettings() { else ui_->enableProxyCheckBox->setCheckState(Qt::Unchecked); } catch (...) { - SPDLOG_ERROR("setting operation error: proxy_enable"); + GF_UI_LOG_ERROR("setting operation error: proxy_enable"); } ui_->forbidALLGnuPGNetworkConnectionCheckBox->setCheckState(Qt::Unchecked); @@ -158,7 +158,7 @@ void GpgFrontend::UI::NetworkTab::SetSettings() { ui_->forbidALLGnuPGNetworkConnectionCheckBox->setCheckState( Qt::Unchecked); } catch (...) { - SPDLOG_ERROR("setting operation error: forbid_all_gnupg_connection"); + GF_UI_LOG_ERROR("setting operation error: forbid_all_gnupg_connection"); } ui_->prohibitUpdateCheck->setCheckState(Qt::Unchecked); @@ -170,7 +170,7 @@ void GpgFrontend::UI::NetworkTab::SetSettings() { else ui_->prohibitUpdateCheck->setCheckState(Qt::Unchecked); } catch (...) { - SPDLOG_ERROR("setting operation error: prohibit_update_checking"); + GF_UI_LOG_ERROR("setting operation error: prohibit_update_checking"); } ui_->autoImportMissingKeyCheckBox->setCheckState(Qt::Unchecked); @@ -182,7 +182,7 @@ void GpgFrontend::UI::NetworkTab::SetSettings() { else ui_->autoImportMissingKeyCheckBox->setCheckState(Qt::Unchecked); } catch (...) { - SPDLOG_ERROR("setting operation error: auto_import_missing_key"); + GF_UI_LOG_ERROR("setting operation error: auto_import_missing_key"); } switch_ui_enabled(ui_->enableProxyCheckBox->isChecked()); diff --git a/src/ui/function/ArchiveDirectory.cpp b/src/ui/function/ArchiveDirectory.cpp index 9cbfc41e..89bb7ff2 100644 --- a/src/ui/function/ArchiveDirectory.cpp +++ b/src/ui/function/ArchiveDirectory.cpp @@ -71,13 +71,13 @@ auto ArchiveDirectory::Exec(const std::filesystem::path& target_directory) auto target_path = target_directory; target_path = target_path.replace_extension(""); - SPDLOG_DEBUG("archive directory, base path: {}, target path: {}", - base_path.string(), target_path.string()); + GF_UI_LOG_DEBUG("archive directory, base path: {}, target path: {}", + base_path.string(), target_path.string()); // ArchiveFileOperator::CreateArchive(base_path, target_path, 0, ); } catch (...) { - SPDLOG_ERROR("archive caught exception error"); + GF_UI_LOG_ERROR("archive caught exception error"); return {false, {}}; } } diff --git a/src/ui/function/GenerateRevokeCertification.cpp b/src/ui/function/GenerateRevokeCertification.cpp index a1c99d95..5d5b1702 100644 --- a/src/ui/function/GenerateRevokeCertification.cpp +++ b/src/ui/function/GenerateRevokeCertification.cpp @@ -48,12 +48,12 @@ auto GenerateRevokeCertification::Exec(const GpgKey& key, std::move(output_path), "--gen-revoke", key.GetFingerprint()}, [=](int exit_code, const std::string& p_out, const std::string& p_err) { if (exit_code != 0) { - SPDLOG_ERROR( + GF_UI_LOG_ERROR( "gnupg gen revoke execute error, process stderr: {}, process " "stdout: {}", p_err, p_out); } else { - SPDLOG_DEBUG( + GF_UI_LOG_DEBUG( "gnupg gen revoke exit_code: {}, process stdout size: {}", exit_code, p_out.size()); } @@ -63,7 +63,7 @@ auto GenerateRevokeCertification::Exec(const GpgKey& key, // Code From Gpg4Win while (proc->canReadLine()) { const QString line = QString::fromUtf8(proc->readLine()).trimmed(); - SPDLOG_DEBUG("line: {}", line.toStdString()); + GF_UI_LOG_DEBUG("line: {}", line.toStdString()); if (line == QLatin1String("[GNUPG:] GET_BOOL gen_revoke.okay")) { proc->write("y\n"); } else if (line == QLatin1String("[GNUPG:] GET_LINE " diff --git a/src/ui/function/RaisePinentry.cpp b/src/ui/function/RaisePinentry.cpp index 31804fa8..1e48e984 100644 --- a/src/ui/function/RaisePinentry.cpp +++ b/src/ui/function/RaisePinentry.cpp @@ -39,8 +39,8 @@ auto FindTopMostWindow(QWidget* fallback) -> QWidget* { QList<QWidget*> top_widgets = QApplication::topLevelWidgets(); foreach (QWidget* widget, top_widgets) { if (widget->isActiveWindow()) { - SPDLOG_TRACE("find a topmost widget, address: {}", - static_cast<void*>(widget)); + GF_UI_LOG_TRACE("find a topmost widget, address: {}", + static_cast<void*>(widget)); return widget; } } @@ -55,7 +55,7 @@ auto RaisePinentry::Exec() -> int { QString::fromStdString(_("Show passphrase")), QString::fromStdString(_("Hide passphrase"))); - SPDLOG_DEBUG("setting pinetry's arguments"); + GF_UI_LOG_DEBUG("setting pinetry's arguments"); pinentry->setPrompt(QString::fromStdString(_("PIN:"))); pinentry->setDescription(QString()); @@ -74,11 +74,11 @@ auto RaisePinentry::Exec() -> int { pinentry->setOkText(_("Confirm")); pinentry->setCancelText(_("Cancel")); - SPDLOG_DEBUG("pinentry is ready to start"); + GF_UI_LOG_DEBUG("pinentry is ready to start"); connect(pinentry, &PinEntryDialog::finished, this, [pinentry](int result) { bool ret = result != 0; - SPDLOG_DEBUG("pinentry finished, ret: {}", ret); + GF_UI_LOG_DEBUG("pinentry finished, ret: {}", ret); if (!ret) { emit CoreSignalStation::GetInstance()->SignalUserInputPassphraseCallback( diff --git a/src/ui/function/SetOwnerTrustLevel.cpp b/src/ui/function/SetOwnerTrustLevel.cpp index 4154b5ff..290b1436 100644 --- a/src/ui/function/SetOwnerTrustLevel.cpp +++ b/src/ui/function/SetOwnerTrustLevel.cpp @@ -54,7 +54,7 @@ auto SetOwnerTrustLevel::Exec(const std::string& key_id) -> bool { key.GetOwnerTrustLevel(), false, &ok); if (ok && !item.isEmpty()) { - SPDLOG_DEBUG("selected owner trust policy: {}", item.toStdString()); + GF_UI_LOG_DEBUG("selected owner trust policy: {}", item.toStdString()); int trust_level = 0; // Unknown Level if (item == _("Ultimate")) { trust_level = 5; diff --git a/src/ui/main_window/GeneralMainWindow.cpp b/src/ui/main_window/GeneralMainWindow.cpp index a62d862c..93c5ca4a 100644 --- a/src/ui/main_window/GeneralMainWindow.cpp +++ b/src/ui/main_window/GeneralMainWindow.cpp @@ -41,7 +41,8 @@ GpgFrontend::UI::GeneralMainWindow::GeneralMainWindow(std::string name, GpgFrontend::UI::GeneralMainWindow::~GeneralMainWindow() = default; void GpgFrontend::UI::GeneralMainWindow::closeEvent(QCloseEvent *event) { - SPDLOG_DEBUG("main window close event caught, event type: {}", event->type()); + GF_UI_LOG_DEBUG("main window close event caught, event type: {}", + event->type()); slot_save_settings(); QMainWindow::closeEvent(event); @@ -53,7 +54,7 @@ void GpgFrontend::UI::GeneralMainWindow::slot_restore_settings() noexcept { std::string window_state = general_windows_state.Check( "window_state", saveState().toBase64().toStdString()); - SPDLOG_DEBUG("restore main window state: {}", window_state); + GF_UI_LOG_DEBUG("restore main window state: {}", window_state); // state sets pos & size of dock-widgets this->restoreState( @@ -76,7 +77,8 @@ void GpgFrontend::UI::GeneralMainWindow::slot_restore_settings() noexcept { size_ = {width, height}; if (this->parent() != nullptr) { - SPDLOG_DEBUG("parent address: {}", static_cast<void *>(this->parent())); + GF_UI_LOG_DEBUG("parent address: {}", + static_cast<void *>(this->parent())); QPoint parent_pos = {0, 0}; QSize parent_size = {0, 0}; @@ -93,10 +95,11 @@ void GpgFrontend::UI::GeneralMainWindow::slot_restore_settings() noexcept { parent_size = parent_window->size(); } - SPDLOG_DEBUG("parent pos x: {} y: {}", parent_pos.x(), parent_pos.y()); + GF_UI_LOG_DEBUG("parent pos x: {} y: {}", parent_pos.x(), + parent_pos.y()); - SPDLOG_DEBUG("parent size width: {} height: {}", parent_size.width(), - parent_size.height()); + GF_UI_LOG_DEBUG("parent size width: {} height: {}", parent_size.width(), + parent_size.height()); if (parent_pos != QPoint{0, 0}) { QPoint parent_center{parent_pos.x() + parent_size.width() / 2, @@ -116,7 +119,7 @@ void GpgFrontend::UI::GeneralMainWindow::slot_restore_settings() noexcept { int width = general_settings_state.Check("icon_size").Check("width", 24), height = general_settings_state.Check("icon_size").Check("height", 24); - SPDLOG_DEBUG("icon size: {} {}", width, height); + GF_UI_LOG_DEBUG("icon size: {} {}", width, height); icon_size_ = {width, height}; font_size_ = general_settings_state.Check("font_size", 10); @@ -130,13 +133,13 @@ void GpgFrontend::UI::GeneralMainWindow::slot_restore_settings() noexcept { icon_style_ = toolButtonStyle(); } catch (...) { - SPDLOG_ERROR(name_, "error"); + GF_UI_LOG_ERROR(name_, "error"); } } void GpgFrontend::UI::GeneralMainWindow::slot_save_settings() noexcept { try { - SPDLOG_DEBUG("save main window state, name: {}", name_); + GF_UI_LOG_DEBUG("save main window state, name: {}", name_); SettingsObject general_windows_state(name_ + "_state"); // window position and size @@ -165,6 +168,6 @@ void GpgFrontend::UI::GeneralMainWindow::slot_save_settings() noexcept { general_settings_state["icon_style"] = this->toolButtonStyle(); } catch (...) { - SPDLOG_ERROR(name_, "error"); + GF_UI_LOG_ERROR(name_, "error"); } } diff --git a/src/ui/main_window/KeyMgmt.cpp b/src/ui/main_window/KeyMgmt.cpp index 81bd2f03..4462011a 100644 --- a/src/ui/main_window/KeyMgmt.cpp +++ b/src/ui/main_window/KeyMgmt.cpp @@ -451,7 +451,7 @@ void KeyMgmt::SlotExportAsOpenSSHFormat() { } void KeyMgmt::SlotImportKeyPackage() { - SPDLOG_INFO("Importing key package..."); + GF_UI_LOG_INFO("Importing key package..."); auto key_package_file_name = QFileDialog::getOpenFileName( this, _("Import Key Package"), {}, @@ -465,7 +465,8 @@ void KeyMgmt::SlotImportKeyPackage() { GpgImportInformation info; - SPDLOG_INFO("importing key package: {}", key_package_file_name.toStdString()); + GF_UI_LOG_INFO("importing key package: {}", + key_package_file_name.toStdString()); if (KeyPackageOperator::ImportKeyPackage(key_package_file_name.toStdString(), key_file_name.toStdString(), info)) { diff --git a/src/ui/main_window/MainWindow.cpp b/src/ui/main_window/MainWindow.cpp index 8cc76d65..d5d8db63 100644 --- a/src/ui/main_window/MainWindow.cpp +++ b/src/ui/main_window/MainWindow.cpp @@ -124,14 +124,14 @@ void MainWindow::Init() noexcept { // before application exit connect(qApp, &QCoreApplication::aboutToQuit, this, []() { - SPDLOG_DEBUG("about to quit process started"); + GF_UI_LOG_DEBUG("about to quit process started"); if (GlobalSettingStation::GetInstance().LookupSettings( "general.clear_gpg_password_cache", false)) { if (GpgFrontend::GpgAdvancedOperator::ClearGpgPasswordCache()) { - SPDLOG_DEBUG("clear gpg password cache done"); + GF_UI_LOG_DEBUG("clear gpg password cache done"); } else { - SPDLOG_ERROR("clear gpg password cache error"); + GF_UI_LOG_ERROR("clear gpg password cache error"); } } }); @@ -140,7 +140,7 @@ void MainWindow::Init() noexcept { this, "com.bktus.gpgfrontend.module.integrated.version-checking", "version.loading_done", [=](Module::Namespace, Module::Key, int, std::any) { - SPDLOG_DEBUG( + GF_UI_LOG_DEBUG( "versionchecking version.loading_done changed, calling slot " "version upgrade"); this->slot_version_upgrade_nofity(); @@ -171,14 +171,14 @@ void MainWindow::Init() noexcept { bool show_wizard = true; wizard.lookupValue("show_wizard", show_wizard); - SPDLOG_DEBUG("wizard show_wizard: {}", show_wizard); + GF_UI_LOG_DEBUG("wizard show_wizard: {}", show_wizard); if (show_wizard) { slot_start_wizard(); } } catch (...) { - SPDLOG_ERROR(_("Critical error occur while loading GpgFrontend.")); + GF_UI_LOG_ERROR(_("Critical error occur while loading GpgFrontend.")); QMessageBox::critical(nullptr, _("Loading Failed"), _("Critical error occur while loading GpgFrontend.")); QCoreApplication::quit(); @@ -188,7 +188,7 @@ void MainWindow::Init() noexcept { void MainWindow::restore_settings() { try { - SPDLOG_DEBUG("restore settings key_server"); + GF_UI_LOG_DEBUG("restore settings key_server"); SettingsObject key_server_json("key_server"); if (!key_server_json.contains("server_list") || @@ -224,7 +224,7 @@ void MainWindow::restore_settings() { import_button_->setToolButtonStyle(icon_style_); try { - SPDLOG_DEBUG("restore settings default_key_checked"); + GF_UI_LOG_DEBUG("restore settings default_key_checked"); // Checked Keys SettingsObject default_key_checked("default_key_checked"); @@ -232,13 +232,13 @@ void MainWindow::restore_settings() { auto key_ids_ptr = std::make_unique<KeyIdArgsList>(); for (auto &it : default_key_checked) { std::string key_id = it; - SPDLOG_DEBUG("get checked key id: {}", key_id); + GF_UI_LOG_DEBUG("get checked key id: {}", key_id); key_ids_ptr->push_back(key_id); } m_key_list_->SetChecked(std::move(key_ids_ptr)); } } catch (...) { - SPDLOG_ERROR("restore default_key_checked failed"); + GF_UI_LOG_ERROR("restore default_key_checked failed"); } prohibit_update_checking_ = false; @@ -246,15 +246,15 @@ void MainWindow::restore_settings() { prohibit_update_checking_ = settings.lookup("network.prohibit_update_checking"); } catch (...) { - SPDLOG_ERROR("setting operation error: prohibit_update_checking"); + GF_UI_LOG_ERROR("setting operation error: prohibit_update_checking"); } } catch (...) { - SPDLOG_ERROR("cannot resolve settings"); + GF_UI_LOG_ERROR("cannot resolve settings"); } GlobalSettingStation::GetInstance().SyncSettings(); - SPDLOG_DEBUG("settings restored"); + GF_UI_LOG_DEBUG("settings restored"); } void MainWindow::recover_editor_unsaved_pages_from_cache() { @@ -265,8 +265,8 @@ void MainWindow::recover_editor_unsaved_pages_from_cache() { return; } - SPDLOG_DEBUG("plan ot recover unsaved page from cache, page array: {}", - unsaved_page_array.dump()); + GF_UI_LOG_DEBUG("plan ot recover unsaved page from cache, page array: {}", + unsaved_page_array.dump()); bool first = true; @@ -278,7 +278,7 @@ void MainWindow::recover_editor_unsaved_pages_from_cache() { std::string title = unsaved_page_json["title"]; std::string content = unsaved_page_json["content"]; - SPDLOG_DEBUG( + GF_UI_LOG_DEBUG( "recovering unsaved page from cache, page title: {}, content size", title, content.size()); diff --git a/src/ui/main_window/MainWindowFileSlotFunction.cpp b/src/ui/main_window/MainWindowFileSlotFunction.cpp index 43e96fcf..69da6678 100644 --- a/src/ui/main_window/MainWindowFileSlotFunction.cpp +++ b/src/ui/main_window/MainWindowFileSlotFunction.cpp @@ -471,9 +471,9 @@ void MainWindow::SlotFileVerify(std::filesystem::path path) { return; } - SPDLOG_DEBUG("verification data file path: {}", data_file_path.u8string()); - SPDLOG_DEBUG("verification signature file path: {}", - sign_file_path.u8string()); + GF_UI_LOG_DEBUG("verification data file path: {}", data_file_path.u8string()); + GF_UI_LOG_DEBUG("verification signature file path: {}", + sign_file_path.u8string()); CommonUtils::WaitForOpera( this, _("Verifying"), [=](const OperaWaitingHd& op_hd) { diff --git a/src/ui/main_window/MainWindowGpgOperaFunction.cpp b/src/ui/main_window/MainWindowGpgOperaFunction.cpp index bdad2809..1efff3df 100644 --- a/src/ui/main_window/MainWindowGpgOperaFunction.cpp +++ b/src/ui/main_window/MainWindowGpgOperaFunction.cpp @@ -284,11 +284,11 @@ void MainWindow::SlotEncryptSign() { auto signer_keys = GpgKeyGetter::GetInstance().GetKeys(signer_key_ids); for (const auto& key : *keys) { - SPDLOG_DEBUG("keys {}", key.GetEmail()); + GF_UI_LOG_DEBUG("keys {}", key.GetEmail()); } for (const auto& signer : *signer_keys) { - SPDLOG_DEBUG("signers {}", signer.GetEmail()); + GF_UI_LOG_DEBUG("signers {}", signer.GetEmail()); } // data to transfer into task diff --git a/src/ui/main_window/MainWindowSlotFunction.cpp b/src/ui/main_window/MainWindowSlotFunction.cpp index 95eb9871..40c0dcb3 100644 --- a/src/ui/main_window/MainWindowSlotFunction.cpp +++ b/src/ui/main_window/MainWindowSlotFunction.cpp @@ -73,7 +73,7 @@ void MainWindow::slot_append_selected_keys() { auto key_ids = m_key_list_->GetSelected(); if (key_ids->empty()) { - SPDLOG_ERROR("no key is selected"); + GF_UI_LOG_ERROR("no key is selected"); return; } @@ -93,7 +93,7 @@ void MainWindow::slot_append_keys_create_datetime() { auto key_ids = m_key_list_->GetSelected(); if (key_ids->empty()) { - SPDLOG_ERROR("no key is selected"); + GF_UI_LOG_ERROR("no key is selected"); return; } @@ -119,7 +119,7 @@ void MainWindow::slot_append_keys_expire_datetime() { auto key_ids = m_key_list_->GetSelected(); if (key_ids->empty()) { - SPDLOG_ERROR("no key is selected"); + GF_UI_LOG_ERROR("no key is selected"); return; } @@ -271,16 +271,16 @@ void MainWindow::SlotOpenFile(const QString& path) { } void MainWindow::slot_version_upgrade_nofity() { - SPDLOG_DEBUG( + GF_UI_LOG_DEBUG( "slot version upgrade notify called, checking version info from rt..."); auto is_loading_done = Module::RetrieveRTValueTypedOrDefault<>( "com.bktus.gpgfrontend.module.integrated.version-checking", "version.loading_done", false); - SPDLOG_DEBUG("checking version info from rt, is loading done state: {}", - is_loading_done); + GF_UI_LOG_DEBUG("checking version info from rt, is loading done state: {}", + is_loading_done); if (!is_loading_done) { - SPDLOG_ERROR("invalid version info from rt, loading hasn't done yet"); + GF_UI_LOG_ERROR("invalid version info from rt, loading hasn't done yet"); return; } @@ -300,7 +300,7 @@ void MainWindow::slot_version_upgrade_nofity() { "com.bktus.gpgfrontend.module.integrated.version-checking", "version.latest_version", std::string{}); - SPDLOG_DEBUG( + GF_UI_LOG_DEBUG( "got version info from rt, need upgrade: {}, with drawn: {}, current " "version " "released: {}", diff --git a/src/ui/main_window/MainWindowSlotUI.cpp b/src/ui/main_window/MainWindowSlotUI.cpp index 37eb688b..54b4e413 100644 --- a/src/ui/main_window/MainWindowSlotUI.cpp +++ b/src/ui/main_window/MainWindowSlotUI.cpp @@ -113,7 +113,7 @@ void MainWindow::slot_open_settings_dialog() { int width = general_settings_state.Check("icon_size").Check("width", 24), height = general_settings_state.Check("icon_size").Check("height", 24); - SPDLOG_DEBUG("icon_size: {} {}", width, height); + GF_UI_LOG_DEBUG("icon_size: {} {}", width, height); general_settings_state.Check("info_font_size", 10); @@ -187,7 +187,7 @@ void MainWindow::slot_cut_pgp_header() { } void MainWindow::SlotSetRestartNeeded(int mode) { - SPDLOG_DEBUG("restart mode: {}", mode); + GF_UI_LOG_DEBUG("restart mode: {}", mode); this->restart_needed_ = mode; } @@ -195,7 +195,7 @@ int MainWindow::get_restart_needed() const { return this->restart_needed_; } void MainWindow::SetCryptoMenuStatus( MainWindow::CryptoMenu::OperationType type) { - SPDLOG_DEBUG("type: {}", type); + GF_UI_LOG_DEBUG("type: {}", type); // refresh status to disable all verify_act_->setDisabled(true); diff --git a/src/ui/struct/SettingsObject.cpp b/src/ui/struct/SettingsObject.cpp index 4b60410c..cf11fc5e 100644 --- a/src/ui/struct/SettingsObject.cpp +++ b/src/ui/struct/SettingsObject.cpp @@ -32,7 +32,7 @@ nlohmann::json& GpgFrontend::UI::SettingsObject::Check( const std::string& key, const nlohmann::json& default_value) { // check if the self null if (this->nlohmann::json::is_null()) { - SPDLOG_DEBUG("settings object is null, creating new one"); + GF_UI_LOG_DEBUG("settings object is null, creating new one"); this->nlohmann::json::operator=(nlohmann::json::object()); } @@ -41,9 +41,9 @@ nlohmann::json& GpgFrontend::UI::SettingsObject::Check( this->nlohmann::json::at(key).is_null() || this->nlohmann::json::at(key).type_name() != default_value.type_name()) { - SPDLOG_DEBUG("added missing key: {}", key); + GF_UI_LOG_DEBUG("added missing key: {}", key); if (default_value.is_null()) { - SPDLOG_WARN("default value is null, using empty object"); + GF_UI_LOG_WARN("default value is null, using empty object"); this->nlohmann::json::operator[](key) = nlohmann::json::object(); } else { this->nlohmann::json::operator[](key) = default_value; @@ -51,7 +51,7 @@ nlohmann::json& GpgFrontend::UI::SettingsObject::Check( } return this->nlohmann::json::at(key); } catch (nlohmann::json::exception& e) { - SPDLOG_ERROR(e.what()); + GF_UI_LOG_ERROR(e.what()); throw e; } } @@ -60,14 +60,14 @@ GpgFrontend::UI::SettingsObject GpgFrontend::UI::SettingsObject::Check( const std::string& key) { // check if the self null if (this->nlohmann::json::is_null()) { - SPDLOG_DEBUG("settings object is null, creating new one"); + GF_UI_LOG_DEBUG("settings object is null, creating new one"); this->nlohmann::json::operator=(nlohmann::json::object()); } if (!nlohmann::json::contains(key) || this->nlohmann::json::at(key).is_null() || this->nlohmann::json::at(key).type() != nlohmann::json::value_t::object) { - SPDLOG_DEBUG("added missing key: {}", key); + GF_UI_LOG_DEBUG("added missing key: {}", key); this->nlohmann::json::operator[](key) = nlohmann::json::object(); } return SettingsObject{nlohmann::json::operator[](key), false}; @@ -76,21 +76,21 @@ GpgFrontend::UI::SettingsObject GpgFrontend::UI::SettingsObject::Check( GpgFrontend::UI::SettingsObject::SettingsObject(std::string settings_name) : settings_name_(std::move(settings_name)) { try { - SPDLOG_DEBUG("loading settings from: {}", this->settings_name_); + GF_UI_LOG_DEBUG("loading settings from: {}", this->settings_name_); auto _json_optional = GpgFrontend::DataObjectOperator::GetInstance().GetDataObject( settings_name_); if (_json_optional.has_value()) { - SPDLOG_DEBUG("settings object: {} loaded.", settings_name_); + GF_UI_LOG_DEBUG("settings object: {} loaded.", settings_name_); nlohmann::json::operator=(_json_optional.value()); } else { - SPDLOG_DEBUG("settings object: {} not found.", settings_name_); + GF_UI_LOG_DEBUG("settings object: {} not found.", settings_name_); nlohmann::json::operator=({}); } } catch (std::exception& e) { - SPDLOG_ERROR(e.what()); + GF_UI_LOG_ERROR(e.what()); } } diff --git a/src/ui/thread/ListedKeyServerTestTask.cpp b/src/ui/thread/ListedKeyServerTestTask.cpp index 28eb33f7..18299725 100644 --- a/src/ui/thread/ListedKeyServerTestTask.cpp +++ b/src/ui/thread/ListedKeyServerTestTask.cpp @@ -47,20 +47,20 @@ void GpgFrontend::UI::ListedKeyServerTestTask::run() { size_t index = 0; for (const auto& url : urls_) { auto key_url = QUrl{url}; - SPDLOG_DEBUG("key server request: {}", key_url.host().toStdString()); + GF_UI_LOG_DEBUG("key server request: {}", key_url.host().toStdString()); auto* network_reply = network_manager_->get(QNetworkRequest{key_url}); auto* timer = new QTimer(this); connect(network_reply, &QNetworkReply::finished, this, [this, index, network_reply]() { - SPDLOG_DEBUG("key server domain reply: {}", - urls_[index].toStdString()); + GF_UI_LOG_DEBUG("key server domain reply: {}", + urls_[index].toStdString()); this->slot_process_network_reply(index, network_reply); }); connect(timer, &QTimer::timeout, this, [this, index, network_reply]() { - SPDLOG_DEBUG("timeout for key server: {}", urls_[index].toStdString()); + GF_UI_LOG_DEBUG("timeout for key server: {}", urls_[index].toStdString()); if (network_reply->isRunning()) { network_reply->abort(); this->slot_process_network_reply(index, network_reply); diff --git a/src/ui/thread/ProxyConnectionTestTask.cpp b/src/ui/thread/ProxyConnectionTestTask.cpp index 9a723727..b952d0b9 100644 --- a/src/ui/thread/ProxyConnectionTestTask.cpp +++ b/src/ui/thread/ProxyConnectionTestTask.cpp @@ -45,13 +45,13 @@ void GpgFrontend::UI::ProxyConnectionTestTask::run() { connect(network_reply, &QNetworkReply::finished, this, [this, network_reply]() { - SPDLOG_DEBUG("key server domain reply: {} received", - url_.toStdString()); + GF_UI_LOG_DEBUG("key server domain reply: {} received", + url_.toStdString()); this->slot_process_network_reply(network_reply); }); connect(timer, &QTimer::timeout, this, [this, network_reply]() { - SPDLOG_DEBUG("timeout for key server: {}", url_.toStdString()); + GF_UI_LOG_DEBUG("timeout for key server: {}", url_.toStdString()); if (network_reply->isRunning()) { network_reply->abort(); this->slot_process_network_reply(network_reply); @@ -64,8 +64,8 @@ void GpgFrontend::UI::ProxyConnectionTestTask::run() { void GpgFrontend::UI::ProxyConnectionTestTask::slot_process_network_reply( QNetworkReply* reply) { auto buffer = reply->readAll(); - SPDLOG_DEBUG("key server domain reply: {}, buffer size: {}", - url_.toStdString(), buffer.size()); + GF_UI_LOG_DEBUG("key server domain reply: {}, buffer size: {}", + url_.toStdString(), buffer.size()); if (reply->error() == QNetworkReply::NoError && !buffer.isEmpty()) { result_ = "Reachable"; diff --git a/src/ui/widgets/FilePage.cpp b/src/ui/widgets/FilePage.cpp index 8823eb96..71961c25 100644 --- a/src/ui/widgets/FilePage.cpp +++ b/src/ui/widgets/FilePage.cpp @@ -167,7 +167,7 @@ void FilePage::SlotGoPath() { } void FilePage::keyPressEvent(QKeyEvent* event) { - SPDLOG_DEBUG("file page notices key press by user: {}", event->key()); + GF_UI_LOG_DEBUG("file page notices key press by user: {}", event->key()); if (ui_->pathEdit->hasFocus() && (event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter)) { SlotGoPath(); diff --git a/src/ui/widgets/FileTreeView.cpp b/src/ui/widgets/FileTreeView.cpp index 9fc8aec4..79db51ac 100644 --- a/src/ui/widgets/FileTreeView.cpp +++ b/src/ui/widgets/FileTreeView.cpp @@ -58,8 +58,8 @@ void FileTreeView::selectionChanged(const QItemSelection& selected, if (!selected.indexes().empty()) { selected_path_ = dir_model_->fileInfo(selected.indexes().first()) .filesystemAbsoluteFilePath(); - SPDLOG_DEBUG("file tree view selected target path: {}", - selected_path_.u8string()); + GF_UI_LOG_DEBUG("file tree view selected target path: {}", + selected_path_.u8string()); emit SignalSelectedChanged(QString::fromStdString(selected_path_)); } else { selected_path_ = std::filesystem::path{}; @@ -70,8 +70,8 @@ void FileTreeView::SlotGoPath(const std::filesystem::path& target_path) { auto file_info = QFileInfo(target_path); if (file_info.isDir() && file_info.isReadable() && file_info.isExecutable()) { current_path_ = file_info.filesystemAbsoluteFilePath(); - SPDLOG_DEBUG("file tree view set target path: {}", - current_path_.u8string()); + GF_UI_LOG_DEBUG("file tree view set target path: {}", + current_path_.u8string()); this->setRootIndex(dir_model_->index(file_info.filePath())); dir_model_->setRootPath(file_info.filePath()); for (int i = 1; i < dir_model_->columnCount(); ++i) { @@ -107,7 +107,8 @@ void FileTreeView::SlotUpLevel() { dir_model_->fileInfo(current_root).filesystemAbsoluteFilePath(); if (target_path.has_parent_path() && !target_path.parent_path().empty()) { target_path = target_path.parent_path(); - SPDLOG_DEBUG("file tree view go parent path: {}", target_path.u8string()); + GF_UI_LOG_DEBUG("file tree view go parent path: {}", + target_path.u8string()); this->SlotGoPath(target_path); } current_path_ = target_path; @@ -140,7 +141,7 @@ auto FileTreeView::GetPathByClickPoint(const QPoint& point) } auto index_path = dir_model_->fileInfo(index).filesystemAbsoluteFilePath(); - SPDLOG_DEBUG("file tree view right click on: {}", index_path.string()); + GF_UI_LOG_DEBUG("file tree view right click on: {}", index_path.string()); return index_path; } @@ -158,7 +159,7 @@ auto FileTreeView::SlotDeleteSelectedItem() -> void { if (ret == QMessageBox::Cancel) return; - SPDLOG_DEBUG("delete item: {}", data.toString().toStdString()); + GF_UI_LOG_DEBUG("delete item: {}", data.toString().toStdString()); if (!dir_model_->remove(index)) { QMessageBox::critical(this, _("Error"), @@ -278,14 +279,14 @@ void FileTreeView::SlotRenameSelectedItem() { #else auto new_name_path = selected_path_.parent_path() / text.toStdString(); #endif - SPDLOG_DEBUG("new name path: {}", new_name_path.u8string()); + GF_UI_LOG_DEBUG("new name path: {}", new_name_path.u8string()); std::filesystem::rename(selected_path_, new_name_path); // refresh SlotGoPath(current_path_); } catch (...) { - SPDLOG_ERROR("file tree view rename error: {}", - selected_path_.u8string()); + GF_UI_LOG_ERROR("file tree view rename error: {}", + selected_path_.u8string()); QMessageBox::critical(this, _("Error"), _("Unable to rename the file or folder.")); } diff --git a/src/ui/widgets/InfoBoardWidget.cpp b/src/ui/widgets/InfoBoardWidget.cpp index c3369ff8..b2ac0119 100644 --- a/src/ui/widgets/InfoBoardWidget.cpp +++ b/src/ui/widgets/InfoBoardWidget.cpp @@ -116,7 +116,7 @@ void InfoBoardWidget::AssociateTabWidget(QTabWidget* tab) { void InfoBoardWidget::AddOptionalAction(const QString& name, const std::function<void()>& action) { - SPDLOG_DEBUG("add option: {}", name.toStdString()); + GF_UI_LOG_DEBUG("add option: {}", name.toStdString()); auto actionButton = new QPushButton(name); auto layout = new QHBoxLayout(); layout->setContentsMargins(5, 0, 5, 0); @@ -165,7 +165,7 @@ void InfoBoardWidget::slot_copy() { void InfoBoardWidget::slot_save() { auto file_path = QFileDialog::getSaveFileName( this, _("Save Information Board's Content"), {}, tr("Text (*.txt)")); - SPDLOG_DEBUG("file path: {}", file_path.toStdString()); + GF_UI_LOG_DEBUG("file path: {}", file_path.toStdString()); if (file_path.isEmpty()) return; QFile file(file_path); diff --git a/src/ui/widgets/KeyList.cpp b/src/ui/widgets/KeyList.cpp index 0e4bba5e..04c184b0 100644 --- a/src/ui/widgets/KeyList.cpp +++ b/src/ui/widgets/KeyList.cpp @@ -116,7 +116,7 @@ void KeyList::AddListGroupTab(const QString& name, const QString& id, KeyListRow::KeyType selectType, KeyListColumn::InfoType infoType, const KeyTable::KeyTableFilter filter) { - SPDLOG_DEBUG("add tab: {}", name.toStdString()); + GF_UI_LOG_DEBUG("add tab: {}", name.toStdString()); auto key_list = new QTableWidget(this); if (m_key_list_ == nullptr) { @@ -176,7 +176,7 @@ void KeyList::AddListGroupTab(const QString& name, const QString& id, } void KeyList::SlotRefresh() { - SPDLOG_DEBUG("refresh, address: {}", static_cast<void*>(this)); + GF_UI_LOG_DEBUG("refresh, address: {}", static_cast<void*>(this)); ui_->refreshKeyListButton->setDisabled(true); ui_->syncButton->setDisabled(true); @@ -187,7 +187,7 @@ void KeyList::SlotRefresh() { } void KeyList::SlotRefreshUI() { - SPDLOG_DEBUG("refresh, address: {}", static_cast<void*>(this)); + GF_UI_LOG_DEBUG("refresh, address: {}", static_cast<void*>(this)); this->slot_refresh_ui(); } @@ -315,8 +315,8 @@ void KeyList::contextMenuEvent(QContextMenuEvent* event) { QString current_tab_widget_obj_name = ui_->keyGroupTab->widget(ui_->keyGroupTab->currentIndex())->objectName(); - SPDLOG_DEBUG("current tab widget object name: {}", - current_tab_widget_obj_name.toStdString()); + GF_UI_LOG_DEBUG("current tab widget object name: {}", + current_tab_widget_obj_name.toStdString()); if (current_tab_widget_obj_name == "favourite") { QList<QAction*> actions = popup_menu_->actions(); for (QAction* action : actions) { @@ -401,7 +401,7 @@ void KeyList::dropEvent(QDropEvent* event) { QFile file; file.setFileName(tmp.toLocalFile()); if (!file.open(QIODevice::ReadOnly)) { - SPDLOG_ERROR("couldn't open file: {}", tmp.toString().toStdString()); + GF_UI_LOG_ERROR("couldn't open file: {}", tmp.toString().toStdString()); } QByteArray inBuffer = file.readAll(); this->import_keys(inBuffer); @@ -463,7 +463,7 @@ std::string KeyList::GetSelectedKey() { } void KeyList::slot_refresh_ui() { - SPDLOG_DEBUG("refresh: {}", static_cast<void*>(buffered_keys_list_.get())); + GF_UI_LOG_DEBUG("refresh: {}", static_cast<void*>(buffered_keys_list_.get())); if (buffered_keys_list_ != nullptr) { std::lock_guard<std::mutex> guard(buffered_key_list_mutex_); @@ -496,8 +496,8 @@ void KeyList::slot_sync_with_key_server() { CommonUtils::SlotImportKeyFromKeyServer( key_ids, [=](const std::string& key_id, const std::string& status, size_t current_index, size_t all_index) { - SPDLOG_DEBUG("import key: {} {} {} {}", key_id, status, current_index, - all_index); + GF_UI_LOG_DEBUG("import key: {} {} {} {}", key_id, status, + current_index, all_index); auto key = GpgKeyGetter::GetInstance().GetKey(key_id); boost::format status_str = boost::format(_("Sync [%1%/%2%] %3% %4%")) % @@ -518,7 +518,7 @@ void KeyList::filter_by_keyword() { auto keyword = ui_->searchBarEdit->text(); keyword = keyword.trimmed(); - SPDLOG_DEBUG("get new keyword of search bar: {}", keyword.toStdString()); + GF_UI_LOG_DEBUG("get new keyword of search bar: {}", keyword.toStdString()); for (auto& table : m_key_tables_) { // refresh arguments table.SetFilterKeyword(keyword.toLower().toStdString()); diff --git a/src/ui/widgets/PlainTextEditorPage.cpp b/src/ui/widgets/PlainTextEditorPage.cpp index 2037689e..d5094dd3 100644 --- a/src/ui/widgets/PlainTextEditorPage.cpp +++ b/src/ui/widgets/PlainTextEditorPage.cpp @@ -182,7 +182,7 @@ void PlainTextEditorPage::ReadFile() { &FileReadTask::SignalFileBytesReadNext, Qt::QueuedConnection); connect(read_task, &FileReadTask::SignalTaskShouldEnd, this, - []() { SPDLOG_DEBUG("read thread closed"); }); + []() { GF_UI_LOG_DEBUG("read thread closed"); }); connect(this, &PlainTextEditorPage::close, read_task, [=]() { read_task->SignalTaskShouldEnd(0); }); connect(read_task, &FileReadTask::SignalFileBytesReadEnd, this, [=]() { @@ -210,7 +210,7 @@ auto BinaryToString(const std::string &source) -> std::string { void PlainTextEditorPage::slot_insert_text(QByteArray bytes_data) { std::string data = bytes_data.toStdString(); - SPDLOG_TRACE("inserting data read to editor, data size: {}", data.size()); + GF_UI_LOG_TRACE("inserting data read to editor, data size: {}", data.size()); read_bytes_ += data.size(); // If binary format is detected, the entire file is converted to binary // format for display. diff --git a/src/ui/widgets/TextEdit.cpp b/src/ui/widgets/TextEdit.cpp index 5ec44230..079a8496 100644 --- a/src/ui/widgets/TextEdit.cpp +++ b/src/ui/widgets/TextEdit.cpp @@ -118,8 +118,8 @@ void TextEdit::SlotNewFileTab() const { void TextEdit::SlotOpenFile(const QString& path) { QFile file(path); - SPDLOG_DEBUG("main window editor is opening file at path: {}", - path.toStdString()); + GF_UI_LOG_DEBUG("main window editor is opening file at path: {}", + path.toStdString()); auto result = file.open(QIODevice::ReadOnly | QIODevice::Text); if (result) { auto* page = new PlainTextEditorPage(path); @@ -541,7 +541,7 @@ QHash<int, QString> TextEdit::UnsavedDocuments() const { if (ep != nullptr && ep->ReadDone() && ep->GetTextPage()->document()->isModified()) { QString doc_name = tab_widget_->tabText(i); - SPDLOG_DEBUG("unsaved: {}", doc_name.toStdString()); + GF_UI_LOG_DEBUG("unsaved: {}", doc_name.toStdString()); // remove * before name of modified doc doc_name.remove(0, 2); @@ -642,16 +642,16 @@ void TextEdit::slot_save_status_to_cache_for_revovery() { restore_text_editor_page = settings.lookup("general.restore_text_editor_page"); } catch (...) { - SPDLOG_ERROR("setting operation error: restore_text_editor_page"); + GF_UI_LOG_ERROR("setting operation error: restore_text_editor_page"); } if (!restore_text_editor_page) { - SPDLOG_DEBUG("restore_text_editor_page is false, ignoring..."); + GF_UI_LOG_DEBUG("restore_text_editor_page is false, ignoring..."); return; } int tab_count = tab_widget_->count(); - SPDLOG_DEBUG( + GF_UI_LOG_DEBUG( "restore_text_editor_page is true, pan to save pages, current tabs " "count: " "{}", @@ -676,8 +676,8 @@ void TextEdit::slot_save_status_to_cache_for_revovery() { } auto raw_text = document->toRawText().toStdString(); - SPDLOG_DEBUG("unsaved page index: {}, tab title: {} tab content: {}", i, - tab_title, raw_text.size()); + GF_UI_LOG_DEBUG("unsaved page index: {}, tab title: {} tab content: {}", i, + tab_title, raw_text.size()); unsaved_pages.push_back({i, tab_title, raw_text}); } @@ -691,7 +691,7 @@ void TextEdit::slot_save_status_to_cache_for_revovery() { unsaved_page_array.push_back(page_json); } - SPDLOG_DEBUG("unsaved page json array: {}", unsaved_page_array.dump()); + GF_UI_LOG_DEBUG("unsaved page json array: {}", unsaved_page_array.dump()); CacheManager::GetInstance().SaveCache("editor_unsaved_pages", unsaved_page_array); } |