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/core | |
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/core')
45 files changed, 822 insertions, 538 deletions
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) { |