| 60 | |
| 61 | |
| 62 | bool Logger::install(const QString &logFilePath, bool consoleOutput) |
| 63 | { |
| 64 | QLoggingCategory::setFilterRules("qt.tlsbackend.ossl=false\nqt.network.ssl=false"); |
| 65 | log_utils::paths::deleteOldUnusedLogs(); |
| 66 | |
| 67 | #ifdef Q_OS_WIN |
| 68 | std::wstring path = logFilePath.toStdWString(); |
| 69 | #else |
| 70 | std::string path = logFilePath.toStdString(); |
| 71 | #endif |
| 72 | |
| 73 | // Initialize spdlog logger |
| 74 | try |
| 75 | { |
| 76 | if (log_utils::isOldLogFormat(path)) { |
| 77 | // Use the nothrow version of remove since the removal is not critical and we would |
| 78 | // like to continue with spdlog creation if the removal does fail. |
| 79 | std::error_code ec; |
| 80 | std::filesystem::remove(path, ec); |
| 81 | } |
| 82 | // Create rotation logger with 2 file with max size 2MB each |
| 83 | // rotate it on open, the first file is the current log, the 2nd is the previous log |
| 84 | auto fileSink = std::make_shared<spdlog::sinks::rotating_file_sink_mt>(path, 2 * 1024 * 1024, 1, true); |
| 85 | auto defaultLogger = std::make_shared<spdlog::logger>("qt", fileSink); |
| 86 | spdlog::set_default_logger(defaultLogger); |
| 87 | |
| 88 | // Create the logger without formatting for logging output from libraries such as wsnet, which format logs themselves |
| 89 | auto rawLogger = std::make_shared<spdlog::logger>("raw", fileSink); |
| 90 | spdlog::register_logger(rawLogger); |
| 91 | |
| 92 | // Also output logs to debugger/stdout for QA/dev use. |
| 93 | #if defined(Q_OS_WIN) |
| 94 | auto sinkDebug = std::make_shared<spdlog::sinks::msvc_sink_mt>(false); |
| 95 | spdlog::default_logger()->sinks().push_back(sinkDebug); |
| 96 | spdlog::get("raw")->sinks().push_back(sinkDebug); |
| 97 | #elif not defined(CLI_ONLY) |
| 98 | auto sinkDebug = std::make_shared<spdlog::sinks::stdout_sink_mt>(); |
| 99 | sinkDebug->set_level(spdlog::level::trace); // Required to get any output in the terminal on Linux. |
| 100 | spdlog::default_logger()->sinks().push_back(sinkDebug); |
| 101 | spdlog::get("raw")->sinks().push_back(sinkDebug); |
| 102 | #endif |
| 103 | |
| 104 | // this will trigger flush on every log message |
| 105 | spdlog::flush_on(spdlog::level::trace); |
| 106 | spdlog::set_level(spdlog::level::trace); |
| 107 | |
| 108 | auto formatter = std::make_unique<log_utils::CustomFormatter>(spdlog::details::make_unique<spdlog::pattern_formatter>("{\"tm\": \"%Y-%m-%d %H:%M:%S.%e\", \"lvl\": \"%^%l%$\", %v}")); |
| 109 | defaultLogger->set_formatter(std::move(formatter)); |
| 110 | } |
| 111 | catch (const spdlog::spdlog_ex &ex) |
| 112 | { |
| 113 | printf("spdlog init failed: %s\n", ex.what()); |
| 114 | return false; |
| 115 | } |
| 116 | |
| 117 | prevMessageHandler_ = qInstallMessageHandler(myMessageHandler); |
| 118 | return true; |
| 119 | } |
no test coverage detected