From 0637adc8067db6dddaa7539d3cbc3f133f2e2675 Mon Sep 17 00:00:00 2001 From: Michel Boyer de la Giroday Date: Fri, 16 Aug 2024 09:48:06 +0200 Subject: [PATCH] refactor: Use std::source_location for the LOG Fixes: #109 --- src/core/astnode.cpp | 2 +- src/core/classsymbol.cpp | 2 +- src/core/codedocument.cpp | 48 +++++++++++---------- src/core/codedocument_p.cpp | 8 ++-- src/core/cppdocument.cpp | 76 +++++++++++++++------------------ src/core/document.cpp | 4 +- src/core/imagedocument.cpp | 2 +- src/core/knutcore.cpp | 4 +- src/core/mark.cpp | 2 +- src/core/project.cpp | 6 +-- src/core/qttsdocument.cpp | 6 +-- src/core/qtuidocument.cpp | 14 +++--- src/core/querymatch.cpp | 2 +- src/core/rangemark.cpp | 10 ++--- src/core/rcdocument.cpp | 11 +++-- src/core/scriptdialogitem.cpp | 14 +++--- src/core/scriptdialogitem_p.cpp | 2 +- src/core/scriptmanager.cpp | 9 ++-- src/core/scriptmodel.cpp | 6 +-- src/core/scriptrunner.cpp | 14 +++--- src/core/settings.cpp | 12 +++--- src/core/symbol.cpp | 4 +- src/core/textdocument.cpp | 20 ++++----- src/core/userdialog.cpp | 14 +++--- src/core/utils.cpp | 2 +- src/gui/apiexecutorwidget.cpp | 2 +- src/gui/optionsdialog.cpp | 2 +- src/gui/scriptlistpanel.cpp | 2 +- src/gui/scriptpanel.cpp | 10 ++--- src/gui/slintview.cpp | 2 +- src/lsp/client.cpp | 10 ++--- src/rccore/lexer.cpp | 2 +- src/rccore/rc_convert.cpp | 20 +++++---- src/rccore/rc_parse.cpp | 42 ++++++++++-------- src/rccore/ribbon.cpp | 2 +- src/treesitter/node.cpp | 4 +- src/treesitter/predicates.cpp | 24 +++++------ src/utils/log.h | 71 ++++++++++++++++++++++++++++++ 38 files changed, 281 insertions(+), 206 deletions(-) diff --git a/src/core/astnode.cpp b/src/core/astnode.cpp index 339900bf..0add3b4f 100644 --- a/src/core/astnode.cpp +++ b/src/core/astnode.cpp @@ -50,7 +50,7 @@ bool AstNode::isValid() const std::optional AstNode::node() const { if (!isValid()) { - spdlog::warn("AstNode is invalid"); + spdlog::warn("{}: AstNode is invalid", LOGFUNCTION()); return std::nullopt; } diff --git a/src/core/classsymbol.cpp b/src/core/classsymbol.cpp index 5105d36d..7a6db216 100644 --- a/src/core/classsymbol.cpp +++ b/src/core/classsymbol.cpp @@ -40,7 +40,7 @@ QList ClassSymbol::findMembers() const } return members; } - spdlog::warn("Parent of CppClass {} is not an CodeDocument!", m_name); + spdlog::warn("{}: Parent of CppClass {} is not an CodeDocument!", LOGFUNCTION(), m_name); return {}; } diff --git a/src/core/codedocument.cpp b/src/core/codedocument.cpp index 8baa3655..9e170b58 100644 --- a/src/core/codedocument.cpp +++ b/src/core/codedocument.cpp @@ -199,7 +199,7 @@ QString CodeDocument::hover(int position, std::function a std::pair> CodeDocument::hoverWithRange( int position, std::function)> asyncCallback /* = {} */) const { - spdlog::debug("CodeDocument::hover"); + spdlog::debug("{}", LOGFUNCTION()); if (!checkClient()) return {"", {}}; @@ -226,8 +226,10 @@ std::pair> CodeDocument::hoverWithRange( if (const auto *content = std::get_if(&hover.contents)) { return {QString::fromStdString(content->value), range}; } else { - spdlog::warn("LSP returned deprecated MarkedString type which is unsupported by Knut\n - Consider updating " - "your LSP server"); + spdlog::warn( + "{}: LSP returned deprecated MarkedString type which is unsupported by Knut\n - Consider updating " + "your LSP server", + LOGFUNCTION()); return {"", {}}; } }; @@ -245,7 +247,7 @@ std::pair> CodeDocument::hoverWithRange( // a Tooltip is requested. // See: TextView::eventFilter. if (!std::holds_alternative(result.value())) { - spdlog::debug("LSP server returned no result for Hover"); + spdlog::debug("{}: LSP server returned no result for Hover", LOGFUNCTION()); } return convertResult(result.value()); } @@ -256,7 +258,7 @@ std::pair> CodeDocument::hoverWithRange( RangeMarkList CodeDocument::references(int position) const { - spdlog::debug("CodeDocument::references"); + spdlog::debug("{}", LOGFUNCTION()); if (!checkClient()) { return {}; @@ -271,10 +273,10 @@ RangeMarkList CodeDocument::references(int position) const if (const auto *locations = std::get_if>(&value)) { return Utils::lspToRangeMarkList(*locations); } else { - spdlog::warn("CodeDocument::references: Language server returned unsupported references type!"); + spdlog::warn("{}: Language server returned unsupported references type!", LOGFUNCTION()); } } else { - spdlog::warn("CodeDocument::references: LSP call to references returned nothing!"); + spdlog::warn("{}: LSP call to references returned nothing!", LOGFUNCTION()); } return {}; @@ -283,7 +285,7 @@ RangeMarkList CodeDocument::references(int position) const // Follows the symbol under the cursor. Document *CodeDocument::followSymbol() { - spdlog::debug("CodeDocument::followSymbol"); + spdlog::debug("{}", LOGFUNCTION()); if (!checkClient()) return {}; @@ -332,7 +334,7 @@ Document *CodeDocument::followSymbol(int pos) return nullptr; if (locations.size() > 1) - spdlog::warn("CodeDocument::followSymbol: Multiple locations returned!"); + spdlog::warn("{}: Multiple locations returned!", LOGFUNCTION()); // Heuristic: If multiple locations were found, use the last one. auto location = locations.back(); @@ -347,8 +349,7 @@ Document *CodeDocument::followSymbol(int pos) if (auto *codeDocument = qobject_cast(document)) { codeDocument->selectRange(Utils::lspToRange(*codeDocument, location.range)); } else { - spdlog::warn("CodeDocument::followSymbol: Opened document '{}' is not an CodeDocument", - document->fileName()); + spdlog::warn("{}: Opened document '{}' is not an CodeDocument", LOGFUNCTION(), document->fileName()); } } @@ -358,7 +359,7 @@ Document *CodeDocument::followSymbol(int pos) // Switches between the function declaration or definition. Document *CodeDocument::switchDeclarationDefinition() { - spdlog::debug("CodeDocument::switchDeclarationDefinition"); + spdlog::debug("{}", LOGFUNCTION()); if (!checkClient()) return {}; @@ -371,7 +372,7 @@ Document *CodeDocument::switchDeclarationDefinition() }); if (!currentFunction) { - spdlog::info("CodeDocument::switchDeclarationDefinition: Cursor is currently not within a function!"); + spdlog::info("{}: Cursor is currently not within a function!", LOGFUNCTION()); return nullptr; } @@ -469,8 +470,7 @@ int CodeDocument::selectSmallerSyntaxNode(int count /* = 1*/) if (node.has_value()) { selectRegion(node->startPosition(), node->endPosition()); } else { - spdlog::warn( - "CodeDocument::selectSmallerSyntaxNode: No smaller node found! Do you currently not have a selection?"); + spdlog::warn("{}: No smaller node found! Do you currently not have a selection?", LOGFUNCTION()); } LOG_RETURN("pos", position()); @@ -718,17 +718,17 @@ Core::QueryMatchList CodeDocument::queryInRange(const Core::RangeMark &range, co LOG("CodeDocument::queryInRange", LOG_ARG("range", range), LOG_ARG("query", query)); if (!range.isValid()) { - spdlog::warn("CodeDocument::queryInRange: Range is not valid"); + spdlog::warn("{}: Range is not valid", LOGFUNCTION()); return {}; } const auto nodes = m_treeSitterHelper->nodesInRange(range); if (nodes.isEmpty()) { - spdlog::warn("CodeDocument::queryInRange: No nodes in range"); + spdlog::warn("{}: No nodes in range", LOGFUNCTION()); return {}; } - spdlog::debug("CodeDocument::queryInRange: Found {} nodes in range", nodes.size()); + spdlog::debug("{}: Found {} nodes in range", LOGFUNCTION(), nodes.size()); auto tsQuery = m_treeSitterHelper->constructQuery(query); if (!tsQuery) @@ -755,7 +755,7 @@ bool CodeDocument::checkClient() const { Q_ASSERT(textEdit()); if (!client()) { - spdlog::error("CodeDocument {} has no LSP client - API not available", fileName()); + spdlog::error("{}: CodeDocument {} has no LSP client - API not available", LOGFUNCTION(), fileName()); return false; } return true; @@ -770,14 +770,16 @@ void CodeDocument::changeContentLsp(int position, int charsRemoved, int charsAdd // TODO: Keep copy of previous string around, so we can find the oldEndPosition. // const auto document = textEdit()->document(); // const auto startblock = document->findBlock(position); - // spdlog::warn("start point: {}, {}", startblock.blockNumber(), position - startblock.position()); + // spdlog::warn("{} - start point: {}, {}", LOGFUNCTION(), startblock.blockNumber(), position - + // startblock.position()); // const auto newEndPosition = position + charsAdded; // const auto newEndBlock = document->findBlock(newEndPosition); - // spdlog::warn("new end point: {}, {}", newEndBlock.blockNumber(), newEndPosition - newEndBlock.position()); + // spdlog::warn("{} - new end point: {}, {}", LOGFUNCTION(), newEndBlock.blockNumber(), newEndPosition - + // newEndBlock.position()); // const auto plain = document->toPlainText(); - // spdlog::warn("added: {}", plain.sliced(position, charsAdded)); + // spdlog::warn("{} - added: {}", LOGFUNCTION(), plain.sliced(position, charsAdded)); if (!checkClient()) { return; @@ -811,7 +813,7 @@ void CodeDocument::changeContentLsp(int position, int charsRemoved, int charsAdd client()->didChange(std::move(params)); } else { - spdlog::error("LSP server does not support Document changes!"); + spdlog::error("{}: LSP server does not support Document changes!", LOGFUNCTION()); } } diff --git a/src/core/codedocument_p.cpp b/src/core/codedocument_p.cpp index d23db3e6..715ed2a6 100644 --- a/src/core/codedocument_p.cpp +++ b/src/core/codedocument_p.cpp @@ -50,12 +50,12 @@ std::optional &TreeSitterHelper::syntaxTree() if (!m_tree) { auto &parser = this->parser(); if (!parser.setIncludedRanges(m_document->includedRanges())) { - spdlog::warn("TreeSitterHelper::syntaxTree: Unable to set the included ranges on the treesitter parser!"); + spdlog::warn("{}: Unable to set the included ranges on the treesitter parser!", LOGFUNCTION()); parser.setIncludedRanges({}); } m_tree = parser.parseString(m_document->text()); if (!m_tree) { - spdlog::warn("CodeDocument::syntaxTree: Failed to parse document {}!", m_document->fileName()); + spdlog::warn("{}: Failed to parse document {}!", LOGFUNCTION(), m_document->fileName()); } } return m_tree; @@ -67,8 +67,8 @@ std::shared_ptr TreeSitterHelper::constructQuery(const QStrin try { tsQuery = std::make_shared(parser().language(), query); } catch (treesitter::Query::Error &error) { - spdlog::error("CodeDocument::constructQuery: Failed to parse query `{}` error: {} at: {}", query, - error.description, error.utf8_offset); + spdlog::error("{}: Failed to parse query `{}` error: {} at: {}", LOGFUNCTION(), query, error.description, + error.utf8_offset); return {}; } return tsQuery; diff --git a/src/core/cppdocument.cpp b/src/core/cppdocument.cpp index c8be798b..6e0c2e42 100644 --- a/src/core/cppdocument.cpp +++ b/src/core/cppdocument.cpp @@ -453,7 +453,7 @@ QString CppDocument::correspondingHeaderSource() const if (QFile::exists(testFileName)) { cache[fileName()] = testFileName; cache[testFileName] = fileName(); - spdlog::debug("CppDocument::correspondingHeaderSource {} => {}", fileName(), testFileName); + spdlog::debug("{}: {} => {}", LOGFUNCTION(), fileName(), testFileName); LOG_RETURN("path", testFileName); } } @@ -482,11 +482,11 @@ QString CppDocument::correspondingHeaderSource() const if (!bestFileName.isEmpty()) { cache[fileName()] = bestFileName; cache[bestFileName] = fileName(); - spdlog::debug("CppDocument::correspondingHeaderSource {} => {}", fileName(), bestFileName); + spdlog::debug("{}: {} => {}", LOGFUNCTION(), fileName(), bestFileName); LOG_RETURN("path", bestFileName); } - spdlog::warn("CppDocument::correspondingHeaderSource {} - not found ", fileName()); + spdlog::warn("{}: {} - not found ", LOGFUNCTION(), fileName()); return {}; } @@ -523,13 +523,12 @@ Core::QueryMatch CppDocument::queryClassDefinition(const QString &className) auto matches = query(classDefinitionQuery); if (matches.isEmpty()) { - spdlog::warn("CppDocument::queryClassDefinition: No class named `{}` found in `{}`", className, fileName()); + spdlog::warn("{}: No class named `{}` found in `{}`", LOGFUNCTION(), className, fileName()); return {}; } if (matches.size() > 1) { - spdlog::error("CppDocument::queryClassDefinition: Multiple classes named `{}` found in `{}`!", className, - fileName()); + spdlog::error("{}: Multiple classes named `{}` found in `{}`!", LOGFUNCTION(), className, fileName()); } return matches.first(); } @@ -601,7 +600,7 @@ Core::QueryMatchList CppDocument::queryFunctionCall(const QString &functionName, for (const auto &argument : argumentCaptures) { if (kdalgorithms::value_in(argument, {"call", "name", "argument-list"})) { - spdlog::warn("CppDocument::queryFunctionCall: provided capture {} is reserved!", argument); + spdlog::warn("{}: provided capture {} is reserved!", LOGFUNCTION(), argument); } } @@ -654,12 +653,12 @@ bool CppDocument::insertCodeInMethod(const QString &methodName, QString code, Po auto symbol = findSymbol(methodName); if (!symbol) { - spdlog::warn("CppDocument::insertCodeInMethod: No symbol found for {}.", methodName); + spdlog::warn("{}: No symbol found for {}.", LOGFUNCTION(), methodName); return false; } if (!symbol->isFunction()) { - spdlog::warn("CppDocument::insertCodeInMethod: {} is not a function or a method.", symbol->name()); + spdlog::warn("{}: {} is not a function or a method.", LOGFUNCTION(), symbol->name()); return false; } @@ -667,7 +666,7 @@ bool CppDocument::insertCodeInMethod(const QString &methodName, QString code, Po cursor.setPosition(symbol->range().end()); cursor.movePosition(QTextCursor::Left, QTextCursor::KeepAnchor); if (cursor.selectedText() != "}") { - spdlog::warn("CppDocument::insertCodeInMethod: {} is not a function definition.", symbol->name()); + spdlog::warn("{}: {} is not a function definition.", LOGFUNCTION(), symbol->name()); return false; } @@ -726,7 +725,7 @@ bool CppDocument::insertForwardDeclaration(const QString &forwardDeclaration) { LOG("CppDocument::insertForwardDeclaration", LOG_ARG("text", forwardDeclaration)); if (!isHeader()) { - spdlog::warn("CppDocument::insertForwardDeclaration: {} - is not a header file. ", fileName()); + spdlog::warn("{}: {} - is not a header file. ", LOGFUNCTION(), fileName()); return false; } @@ -734,8 +733,7 @@ bool CppDocument::insertForwardDeclaration(const QString &forwardDeclaration) const auto classOrStruct = QStringView(forwardDeclaration).left(spacePos); if (forwardDeclaration.isEmpty() || (classOrStruct != QStringLiteral("class") && classOrStruct != QStringLiteral("struct"))) { - spdlog::warn("CppDocument::insertForwardDeclaration: {} - should start with 'class ' or 'struct '. ", - forwardDeclaration); + spdlog::warn("{}: {} - should start with 'class ' or 'struct '. ", LOGFUNCTION(), forwardDeclaration); return false; } @@ -751,7 +749,7 @@ bool CppDocument::insertForwardDeclaration(const QString &forwardDeclaration) QTextCursor cursor(doc); cursor = doc->find(result, cursor, QTextDocument::FindWholeWords); if (!cursor.isNull()) { - spdlog::warn("CppDocument::insertForwardDeclaration: '{}' - already exists in file.", forwardDeclaration); + spdlog::warn("{}: '{}' - already exists in file.", LOGFUNCTION(), forwardDeclaration); return false; } @@ -799,12 +797,12 @@ DataExchange CppDocument::mfcExtractDDX(const QString &className) auto functions = queryMethodDefinition(className, "DoDataExchange"); if (functions.isEmpty()) { - spdlog::warn("CppDocument::mfcExtractDDX: No DoDataExchange found in `{}`", fileName()); + spdlog::warn("{}: No DoDataExchange found in `{}`", LOGFUNCTION(), fileName()); return {}; } if (functions.size() > 1) { - spdlog::warn("CppDocument::mfcExtractDDX: Too many DoDataExchange methods found in `{}`", fileName()); + spdlog::warn("{}: Too many DoDataExchange methods found in `{}`", LOGFUNCTION(), fileName()); } auto &function = functions.first(); @@ -872,7 +870,7 @@ MessageMap CppDocument::mfcExtractMessageMap(const QString &className /* = ""*/) // As the MessageMap query is quite complicated, this can significantly improve performance. auto match = queryFirst(queryString); if (match.isEmpty()) { - spdlog::warn("CppDocument::mfcExtractMessageMap: No message map found in `{}`", fileName()); + spdlog::warn("{}: No message map found in `{}`", LOGFUNCTION(), fileName()); return {}; } @@ -905,7 +903,7 @@ Core::QueryMatchList CppDocument::queryMethodDeclaration(const QString &classNam auto classQuery = queryClassDefinition(className); if (classQuery.isEmpty()) { - spdlog::warn("CppDocument::queryMethodDeclaration: No class named `{}` found in `{}`", className, fileName()); + spdlog::warn("{}: No class named `{}` found in `{}`", LOGFUNCTION(), className, fileName()); return {}; } @@ -940,8 +938,7 @@ Core::QueryMatchList CppDocument::queryMethodDeclaration(const QString &classNam auto matches = classQuery.queryIn("body", queryString); if (matches.isEmpty()) { - spdlog::warn("CppDocument::queryMethodDeclaration: No method named `{}` found in `{}`", functionName, - fileName()); + spdlog::warn("{}: No method named `{}` found in `{}`", LOGFUNCTION(), functionName, fileName()); } return matches; @@ -969,12 +966,12 @@ Core::QueryMatch CppDocument::queryMember(const QString &className, const QStrin auto matches = classQuery.queryIn("body", membersQuery(memberName)); if (matches.isEmpty()) { - spdlog::warn("CppDocument::queryMember: No member named `{}` found in `{}`", memberName, fileName()); + spdlog::warn("{}: No member named `{}` found in `{}`", LOGFUNCTION(), memberName, fileName()); return {}; } if (matches.size() > 1) { - spdlog::error("CppDocument::queryMember: Multiple members named `{}` found in `{}`!", memberName, fileName()); + spdlog::error("{}: Multiple members named `{}` found in `{}`!", LOGFUNCTION(), memberName, fileName()); } return matches.first(); } @@ -1269,13 +1266,12 @@ bool CppDocument::insertInclude(const QString &include, bool newGroup) IncludeHelper includeHelper(this); auto includePos = includeHelper.includePositionForInsertion(include, newGroup); if (!includePos) { - spdlog::error(R"(CppDocument::insertInclude - the include '{}' is malformed, should be '' or '"foo.h"')", - include); + spdlog::error(R"({}: the include '{}' is malformed, should be '' or '"foo.h"')", LOGFUNCTION(), include); return false; } if (includePos->alreadyExists()) { - spdlog::info("CppDocument::insertInclude - the include '{}' is already included.", include); + spdlog::info("{}: the include '{}' is already included.", LOGFUNCTION(), include); return true; } @@ -1346,7 +1342,7 @@ bool CppDocument::addMember(const QString &member, const QString &className, Acc auto result = addMemberOrMethod(member, className, specifier); if (result == MemberOrMethodAdditionResult::ClassNotFound) { - spdlog::error(R"(CppDocument::addMember- Can't find class '{}')", className); + spdlog::error(R"({}: Can't find class '{}')", LOGFUNCTION(), className); } return true; @@ -1371,7 +1367,7 @@ bool CppDocument::addMethodDeclaration(const QString &method, const QString &cla auto result = addMemberOrMethod(method, className, specifier); if (result == MemberOrMethodAdditionResult::ClassNotFound) { - spdlog::error(R"(CppDocument::addMethodDeclaration - Can't find class '{}')", className); + spdlog::error(R"({}: Can't find class '{}')", LOGFUNCTION(), className); } return true; @@ -1460,13 +1456,13 @@ bool CppDocument::addMethod(const QString &declaration, const QString &className if (header) { result &= header->addMethodDeclaration(declaration, className, specifier); } else { - spdlog::error("CppDocument::addMethod - Can't find header file for '{}'", className); + spdlog::error("{}: Can't find header file for '{}'", LOGFUNCTION(), className); } if (source) { result &= source->addMethodDefinition(declaration, className, body); } else { - spdlog::error("CppDocument::addMethod - Can't find source file for '{}'", className); + spdlog::error("{}: Can't find source file for '{}'", LOGFUNCTION(), className); } return result; @@ -1514,13 +1510,12 @@ bool CppDocument::removeInclude(const QString &include) IncludeHelper includeHelper(this); auto line = includeHelper.includePositionForRemoval(include); if (!line) { - spdlog::error(R"(CppDocument::removeInclude - the include '{}' is malformed, should be '' or '"foo.h"')", - include); + spdlog::error(R"({}: the include '{}' is malformed, should be '' or '"foo.h"')", LOGFUNCTION(), include); return false; } if (line.value() == -1) { - spdlog::info("CppDocument::removeInclude - the include '{}' is not included."); + spdlog::info("{}: the include '{}' is not included.", LOGFUNCTION(), include); return true; } @@ -1558,7 +1553,7 @@ void CppDocument::deleteMethodLocal(const QString &methodName, const QString &si std::ranges::sort(symbolList, byRange); for (const auto &symbol : std::as_const(symbolList)) { - spdlog::trace("CppDocument::deleteMethodLocal: Removing symbol '{}'", symbol->name()); + spdlog::trace("{}: Removing symbol '{}'", LOGFUNCTION(), symbol->name()); deleteSymbol(*symbol); } @@ -1635,8 +1630,7 @@ void CppDocument::deleteMethod() auto symbol = currentSymbol(isFunction); if (!symbol) { - spdlog::error( - "CppDocument::deleteMethod: Cursor is not currently within a function definition or declaration!"); + spdlog::error("{}: Cursor is not currently within a function definition or declaration!", LOGFUNCTION()); } else { deleteMethod(symbol->name(), symbol->toFunction()->signature()); } @@ -1684,20 +1678,19 @@ bool CppDocument::changeBaseClass(CppDocument *header, CppDocument *source, cons auto result = true; const QString baseClassName = header->queryClassDefinition(className).get("base").text(); if (baseClassName.isEmpty()) { - spdlog::error("CppDocument::changeBaseClass - Can't find base class name for class: '{}'", - className.toStdString()); + spdlog::error("{}: Can't find base class name for class: '{}'", LOGFUNCTION(), className.toStdString()); return false; } if (header) { result &= header->changeBaseClassHeader(className, baseClassName, newClassBaseName); } else { - spdlog::warn("CppDocument::changeBaseClass - Can't find header file for '{}'", baseClassName); + spdlog::warn("{}: Can't find header file for '{}'", LOGFUNCTION(), baseClassName); result = false; } if (source) { result &= source->changeBaseClassSource(className, baseClassName, newClassBaseName); } else { - spdlog::warn("CppDocument::changeBaseClass - Can't find source file for '{}'", baseClassName); + spdlog::warn("{}: Can't find source file for '{}'", LOGFUNCTION(), baseClassName); result = false; } return result; @@ -1718,7 +1711,7 @@ bool CppDocument::changeBaseClass(const QString &className, const QString &newCl auto header = this; auto source = openHeaderSource(); if (!source) { - spdlog::warn("CppDocument::changeBaseClass - Can't find source file"); + spdlog::warn("{}: Can't find source file", LOGFUNCTION()); } else if (!isHeader()) { std::swap(header, source); } @@ -1757,8 +1750,7 @@ QList CppDocument::includedRanges() const QRegularExpression regex(macros.join("|")); if (!regex.isValid()) { - spdlog::error("CppDocument::includedRanges: Failed to create regex for excluded macros: {}", - regex.errorString()); + spdlog::error("{}: Failed to create regex for excluded macros: {}", LOGFUNCTION(), regex.errorString()); return {}; } diff --git a/src/core/document.cpp b/src/core/document.cpp index 902ae18d..3fa614f9 100644 --- a/src/core/document.cpp +++ b/src/core/document.cpp @@ -146,7 +146,7 @@ bool Document::load(const QString &fileName) { LOG("Document::load", fileName); if (fileName.isEmpty()) { - spdlog::warn("Document::load - fileName is empty"); + spdlog::warn("{}: fileName is empty", LOGFUNCTION()); return false; } if (m_fileName == fileName) @@ -182,7 +182,7 @@ bool Document::saveAs(const QString &fileName) { LOG("Document::saveAs", fileName); if (fileName.isEmpty()) { - spdlog::error("Document::saveAs - fileName is empty"); + spdlog::error("{}: fileName is empty", LOGFUNCTION()); return false; } diff --git a/src/core/imagedocument.cpp b/src/core/imagedocument.cpp index 5b3ca235..84f709aa 100644 --- a/src/core/imagedocument.cpp +++ b/src/core/imagedocument.cpp @@ -26,7 +26,7 @@ QImage ImageDocument::image() const bool ImageDocument::doSave(const QString &fileName) { Q_UNUSED(fileName) - spdlog::error("ImageDocument::doSave - not implemented yet"); + spdlog::error("{}: not implemented yet", LOGFUNCTION()); return false; } diff --git a/src/core/knutcore.cpp b/src/core/knutcore.cpp index 9418519a..c9ef923d 100644 --- a/src/core/knutcore.cpp +++ b/src/core/knutcore.cpp @@ -100,7 +100,7 @@ bool KnutCore::process(const QStringList &arguments) if (pathDir.exists()) { Project::instance()->setRoot(rootDir); } else { - spdlog::error("KnutCore::process - Root directory: {}, does not exist. Cannot open a new project!", + spdlog::error("{} - Root directory: {}, does not exist. Cannot open a new project!", LOGFUNCTION(), pathDir.absolutePath()); return false; } @@ -131,7 +131,7 @@ bool KnutCore::process(const QStringList &arguments) try { jsonData = json::parse(jsonDataStr.toStdString()); } catch (const json::parse_error &ex) { - spdlog::error("JSON parsing error at byte {}: {}", ex.byte, ex.what()); + spdlog::error("{} - JSON parsing error at byte {}: {}", LOGFUNCTION(), ex.byte, ex.what()); return false; } } diff --git a/src/core/mark.cpp b/src/core/mark.cpp index d02c30e2..7aeae17d 100644 --- a/src/core/mark.cpp +++ b/src/core/mark.cpp @@ -51,7 +51,7 @@ namespace Core { bool MarkPrivate::checkEditor() const { if (!m_editor) { - spdlog::error("Mark::checkEditor - document does not exist anymore"); + spdlog::error("{}: - document does not exist anymore", LOGFUNCTION()); return false; } return true; diff --git a/src/core/project.cpp b/src/core/project.cpp index f6fecd56..a4527e41 100644 --- a/src/core/project.cpp +++ b/src/core/project.cpp @@ -92,9 +92,9 @@ bool Project::setRoot(const QString &newRoot) return true; if (m_root.isEmpty()) { - spdlog::info("Project::setRoot {}", dir.absolutePath()); + spdlog::info("{}: {}", LOGFUNCTION(), dir.absolutePath()); } else { - spdlog::error("Project::setRoot - can't open a new project"); + spdlog::error("{}: can't open a new project", LOGFUNCTION()); return false; } @@ -287,7 +287,7 @@ Document *Project::getDocument(QString fileName, bool moveToBack) m_documents.push_back(doc); emit documentsChanged(); } else { - spdlog::error("Project::open {} - unknown document type", fi.suffix()); + spdlog::error("{}: {} - unknown document type", LOGFUNCTION(), fi.suffix()); return nullptr; } } diff --git a/src/core/qttsdocument.cpp b/src/core/qttsdocument.cpp index adff5d3c..9d677dfd 100644 --- a/src/core/qttsdocument.cpp +++ b/src/core/qttsdocument.cpp @@ -127,7 +127,7 @@ void QtTsDocument::addMessage(const QString &context, const QString &fileName, c { LOG("QtTsDocument::addMessage", context, fileName, source, translation, comment); if (fileName.isEmpty() || source.isEmpty() || context.isEmpty()) { - spdlog::error(R"(Location or context or source is empty)"); + spdlog::error(R"({}: Location or context or source is empty)", LOGFUNCTION()); } initializeXml(); @@ -243,13 +243,13 @@ bool QtTsDocument::doLoad(const QString &fileName) m_document.load_file(fileName.toLatin1().constData(), pugi::parse_default | pugi::parse_declaration); if (!result) { - spdlog::critical("{}({}): {}", fileName, result.offset, result.description()); + spdlog::critical("{} - {}({}): {}", LOGFUNCTION(), fileName, result.offset, result.description()); return false; } const auto ts = m_document.select_nodes("TS"); if (ts.empty()) { - spdlog::critical("invalid file {}", fileName); + spdlog::critical("{}: invalid file {}", LOGFUNCTION(), fileName); return false; } diff --git a/src/core/qtuidocument.cpp b/src/core/qtuidocument.cpp index 97d1bb2d..ce6a4683 100644 --- a/src/core/qtuidocument.cpp +++ b/src/core/qtuidocument.cpp @@ -65,7 +65,7 @@ Core::QtUiWidget *QtUiDocument::addWidget(const QString &className, const QStrin LOG("QtUiDocument::addWidget", className, name); if (m_widgets.empty() && parent) { - spdlog::error("QtUiDocument::addWidget - adding a widget to a non-root widget is not supported yet."); + spdlog::error("{}: adding a widget to a non-root widget is not supported yet.", LOGFUNCTION()); return nullptr; } @@ -101,12 +101,10 @@ void QtUiDocument::addCustomWidget(const QString &className, const QString &base setHasChanged(true); return; case Utils::QtUiWriter::AlreadyExists: - spdlog::info(R"(QtUiDocument::addCustomWidget - the custom widget '{}' already exists)", className); + spdlog::info(R"({}: the custom widget '{}' already exists)", LOGFUNCTION(), className); return; case Utils::QtUiWriter::InvalidHeader: - spdlog::error( - R"(QtUiDocument::addCustomWidget - the include '{}' is malformed, should be '' or '"foo.h"')", - header); + spdlog::error(R"({}: the include '{}' is malformed, should be '' or '"foo.h"')", LOGFUNCTION(), header); return; case Utils::QtUiWriter::InvalidProperty: Q_UNREACHABLE(); @@ -143,7 +141,7 @@ bool QtUiDocument::doLoad(const QString &fileName) m_document.load_file(fileName.toLatin1().constData(), pugi::parse_default | pugi::parse_declaration); if (!result) { - spdlog::critical("{}({}): {}", fileName, result.offset, result.description()); + spdlog::critical("{}: {}({}): {}", LOGFUNCTION(), fileName, result.offset, result.description()); return false; } @@ -256,7 +254,7 @@ QVariant QtUiWidget::getProperty(const QString &name) const return dataNode.text().as_string(); } - spdlog::error(R"(QtUiWidget::property - unknown {} property)", name); + spdlog::error(R"({}: unknown {} property)", LOGFUNCTION(), name); return {}; } @@ -285,7 +283,7 @@ void QtUiWidget::addProperty(const QString &name, const QVariant &value, const Q qobject_cast(parent())->setHasChanged(true); return; case Utils::QtUiWriter::InvalidProperty: - spdlog::error(R"(QtUiWidget::addProperty - unknown {} type)", value.typeName()); + spdlog::error(R"({}: unknown {} type)", LOGFUNCTION(), value.typeName()); return; case Utils::QtUiWriter::AlreadyExists: case Utils::QtUiWriter::InvalidHeader: diff --git a/src/core/querymatch.cpp b/src/core/querymatch.cpp index 382aa229..ac056587 100644 --- a/src/core/querymatch.cpp +++ b/src/core/querymatch.cpp @@ -223,7 +223,7 @@ Core::QueryMatchList QueryMatch::queryIn(const QString &capture, const QString & if (document) { result.append(document->queryInRange(range, query)); } else { - spdlog::warn("QueryMatch::queryIn: RangeMark is not backed by CodeDocument!"); + spdlog::warn("{}: RangeMark is not backed by CodeDocument!", LOGFUNCTION()); } } diff --git a/src/core/rangemark.cpp b/src/core/rangemark.cpp index 21056fbd..3022b204 100644 --- a/src/core/rangemark.cpp +++ b/src/core/rangemark.cpp @@ -66,7 +66,7 @@ RangeMarkPrivate::RangeMarkPrivate(TextDocument *editor, int start, int end) bool RangeMarkPrivate::checkEditor() const { if (!m_editor) { - spdlog::error("RangeMark::checkEditor - document does not exist anymore"); + spdlog::error("{}: document does not exist anymore", LOGFUNCTION()); return false; } return true; @@ -75,7 +75,7 @@ bool RangeMarkPrivate::checkEditor() const void RangeMarkPrivate::ensureInvariant() { if (m_start > m_end) { - spdlog::warn("RangeMark::ensureInvariant: invariant violated: m_start > m_end ({} > {})", m_start, m_end); + spdlog::warn("{}: invariant violated: m_start > m_end ({} > {})", LOGFUNCTION(), m_start, m_end); std::swap(m_start, m_end); } } @@ -199,15 +199,15 @@ RangeMark RangeMark::join(const RangeMark &other) const QString RangeMark::textExcept(const RangeMark &other) const { if (!isValid()) { - spdlog::error("RangeMark::textExcept: invalid range"); + spdlog::error("{}: invalid range", LOGFUNCTION()); return ""; } if (!other.isValid()) { - spdlog::debug("RangeMark::textExcept: invalid other range"); + spdlog::debug("{}: invalid other range", LOGFUNCTION()); return text(); } if (document() != other.document()) { - spdlog::error("RangeMark::textExcept: different documents"); + spdlog::error("{}: different documents", LOGFUNCTION()); return text(); } diff --git a/src/core/rcdocument.cpp b/src/core/rcdocument.cpp index 7ae62b30..c29b98d1 100644 --- a/src/core/rcdocument.cpp +++ b/src/core/rcdocument.cpp @@ -378,7 +378,7 @@ QString RcDocument::stringForLanguage(const QString &language, const QString &id const auto &strings = data.strings; return strings.value(id).text; } else { - spdlog::warn("RcDocument::stringForLanguage: language {} does not exist in the rc file.", language); + spdlog::warn("{}: language {} does not exist in the rc file.", LOGFUNCTION(), language); return {}; } } @@ -422,13 +422,12 @@ QString extractStringForDialog(const RcCore::Data::Dialog *dialog, const QString if (dialog) { const auto control = findControlWithId(dialog, id); if (!control) { - spdlog::warn("RcDocument::stringForDialogAndLanguage: control from id {} does not exist in the rc file.", - id); + spdlog::warn("{}: control from id {} does not exist in the rc file.", LOGFUNCTION(), id); return {}; } return control.value().text; } else { - spdlog::warn("RcDocument::stringForDialogAndLanguage: id {} does not exist in the rc file.", id); + spdlog::warn("{}: id {} does not exist in the rc file.", LOGFUNCTION(), id); return {}; } } @@ -447,7 +446,7 @@ QString RcDocument::stringForDialogAndLanguage(const QString &language, const QS const auto dialog = data.dialog(dialogId); return extractStringForDialog(dialog, id); } else { - spdlog::warn("RcDocument::stringForDialogAndLanguage: language {} does not exist in the rc file.", language); + spdlog::warn("{}: language {} does not exist in the rc file.", LOGFUNCTION(), language); return {}; } } @@ -483,7 +482,7 @@ void RcDocument::setLanguage(const QString &language) LOG("RcDocument::setLanguage", language); if (!m_rcFile.data.contains(language)) { - spdlog::warn("RcDocument::setLanguage: language {} does not exist in the rc file.", language); + spdlog::warn("{}: language {} does not exist in the rc file.", LOGFUNCTION(), language); return; } diff --git a/src/core/scriptdialogitem.cpp b/src/core/scriptdialogitem.cpp index ee68c2ab..bed7b2e1 100644 --- a/src/core/scriptdialogitem.cpp +++ b/src/core/scriptdialogitem.cpp @@ -171,7 +171,7 @@ void ScriptDialogItem::initialize(nlohmann::json &&jsonData) } else if (it.value().is_number_float()) { value = it.value().get(); } else { - spdlog::error("Unsupported data type for key '{}'", it.key()); + spdlog::error("{}: Unsupported data type for key '{}'", LOGFUNCTION(), it.key()); value = QString::fromStdString(it.value().dump()); } @@ -292,7 +292,7 @@ void ScriptDialogItem::continueScript() void ScriptDialogItem::abortScript() { - spdlog::info("Script aborted."); + spdlog::info("{}: Script aborted.", LOGFUNCTION()); finishScript(); } @@ -311,7 +311,7 @@ void ScriptDialogItem::runNextStep() const auto done = result.property("done").toBool(); m_nextStepTitle = result.property("value").toString(); - spdlog::info("{} done.", m_currentStepTitle); + spdlog::info("{}: {} done.", LOGFUNCTION(), m_currentStepTitle); if (done) { finishScript(); @@ -497,7 +497,7 @@ void ScriptDialogItem::setUiFile(const QString &fileName) setWindowTitle(internalWidget->windowTitle()); createProperties(internalWidget); } else { - spdlog::error("Can't open {}", fileName); + spdlog::error("{}: Can't open {}", LOGFUNCTION(), fileName); } } @@ -638,10 +638,10 @@ void ScriptDialogItem::changeValue(const QString &key, const QVariant &value) } if (!widget) { - spdlog::warn("No widget found for the key '{}'.", key.toStdString()); + spdlog::warn("{}: No widget found for the key '{}'.", LOGFUNCTION(), key.toStdString()); } else { - spdlog::warn("Unsupported widget type '{}' for the key '{}'.", widget->metaObject()->className(), - key.toStdString()); + spdlog::warn("{}: Unsupported widget type '{}' for the key '{}'.", LOGFUNCTION(), + widget->metaObject()->className(), key.toStdString()); } } diff --git a/src/core/scriptdialogitem_p.cpp b/src/core/scriptdialogitem_p.cpp index 0011d467..5e2f7927 100644 --- a/src/core/scriptdialogitem_p.cpp +++ b/src/core/scriptdialogitem_p.cpp @@ -73,7 +73,7 @@ int DynamicObject::qt_metacall(QMetaObject::Call call, int id, void **argv) if (m_dataChangedCallback) m_dataChangedCallback(property.name, property.variant); } else { - spdlog::warn("DynamicObject::qt_metacall: id {} not handled.", id); + spdlog::warn("{}: id {} not handled.", LOGFUNCTION(), id); } return -1; diff --git a/src/core/scriptmanager.cpp b/src/core/scriptmanager.cpp index cc0b0268..27610f57 100644 --- a/src/core/scriptmanager.cpp +++ b/src/core/scriptmanager.cpp @@ -80,10 +80,10 @@ QAbstractItemModel *ScriptManager::model() void ScriptManager::runScript(const QString &fileName, nlohmann::json &&data, bool async, bool log) { if (log) - spdlog::debug("==> Start script {}", fileName); + spdlog::debug("{}: ==> Start script {}", LOGFUNCTION(), fileName); auto endScriptCallback = [this, log, fileName]() { if (log) - spdlog::debug("<== End script {}", fileName); + spdlog::debug("{}: <== End script {}", LOGFUNCTION(), fileName); emit scriptFinished(m_result); }; @@ -205,10 +205,11 @@ void ScriptManager::doRunScript(const QString &fileName, nlohmann::json &&data, if (m_runner->hasError()) { const auto errors = m_runner->errors(); for (const auto &error : errors) - spdlog::error("{}({}): {}", error.url().toLocalFile(), error.line(), error.description()); + spdlog::error("{}: {}({}): {}", LOGFUNCTION(), error.url().toLocalFile(), error.line(), + error.description()); } else { if (m_result.isValid()) - spdlog::info("Script result is {}", m_result.toString()); + spdlog::info("{}: Script result is {}", LOGFUNCTION(), m_result.toString()); } } diff --git a/src/core/scriptmodel.cpp b/src/core/scriptmodel.cpp index fb866407..9b3a5028 100644 --- a/src/core/scriptmodel.cpp +++ b/src/core/scriptmodel.cpp @@ -71,7 +71,7 @@ QVariant ScriptModel::columnHeaderDisplayData(int column) const case DescriptionColumn: return tr("Description"); default: - spdlog::error("SuggestedScripts::columnHeaderDisplayData: column out of range: {}", column); + spdlog::error("{}: Suggested Scripts - column out of range: {}", LOGFUNCTION(), column); return {}; } } @@ -95,7 +95,7 @@ QVariant ScriptModel::data(const QModelIndex &index, int role) const const auto &scripts = scriptList(); if (row < 0 || static_cast(row) >= scripts.size()) { - spdlog::error("SuggestedScripts::data: row out of range: {}", row); + spdlog::error("{}: Suggested Scripts - row out of range: {}", LOGFUNCTION(), row); return {}; } @@ -120,7 +120,7 @@ QVariant ScriptModel::displayData(const ScriptManager::Script &script, int colum case DescriptionColumn: return script.description; default: - spdlog::error("SuggestedScripts::displayData: column out of range: {}", column); + spdlog::error("{}: Suggested Scripts - column out of range: {}", LOGFUNCTION(), column); return {}; } } diff --git a/src/core/scriptrunner.cpp b/src/core/scriptrunner.cpp index f0370a01..3224f125 100644 --- a/src/core/scriptrunner.cpp +++ b/src/core/scriptrunner.cpp @@ -196,7 +196,7 @@ QVariant ScriptRunner::runScript(const QString &fileName, nlohmann::json &&data, } // engine is deleted in runJavascript or runQml } else { - spdlog::error("File {} doesn't exist", fileName); + spdlog::error("{}: File {} doesn't exist", LOGFUNCTION(), fileName); return QVariant(ErrorCode); } @@ -223,8 +223,8 @@ void ScriptRunner::compare(QObject *object, const QJSValue &actual, const QJSVal if (message.isEmpty()) message = "Compared values are not the same"; - spdlog::critical("FAIL!: {}({}) - {}\n Actual :{}\n Expected:{}", callerFile(object), - callerLine(object), message, actual.toString(), expected.toString()); + spdlog::critical("FAIL!: {} - {}({}) - {}\n Actual :{}\n Expected:{}", LOGFUNCTION(), + callerFile(object), callerLine(object), message, actual.toString(), expected.toString()); object->setProperty("failed", object->property("failed").toInt() + 1); } } @@ -236,7 +236,7 @@ void ScriptRunner::verify(QObject *object, bool value, QString message) if (message.isEmpty()) message = "Verification failed"; - spdlog::critical("FAIL!: {}({}) - {}", callerFile(object), callerLine(object), message); + spdlog::critical("FAIL!: {} - {}({}) - {}", LOGFUNCTION(), callerFile(object), callerLine(object), message); object->setProperty("failed", object->property("failed").toInt() + 1); } } @@ -277,9 +277,11 @@ QQmlEngine *ScriptRunner::getEngine(const QString &fileName) auto logWarnings = [this](const QList &warnings) { for (const auto &warning : warnings) { if (warning.description().contains("error", Qt::CaseInsensitive)) - spdlog::error("{}({}): {}", warning.url().toLocalFile(), warning.line(), warning.description()); + spdlog::error("{}: {}({}): {}", LOGFUNCTION(), warning.url().toLocalFile(), warning.line(), + warning.description()); else - spdlog::warn("{}({}): {}", warning.url().toLocalFile(), warning.line(), warning.description()); + spdlog::warn("{}: {}({}): {}", LOGFUNCTION(), warning.url().toLocalFile(), warning.line(), + warning.description()); m_hasError = true; } }; diff --git a/src/core/settings.cpp b/src/core/settings.cpp index ef12560b..cd31509a 100644 --- a/src/core/settings.cpp +++ b/src/core/settings.cpp @@ -167,9 +167,9 @@ QVariant Settings::value(QString path, const QVariant &defaultValue) const return QStringList(); } } - spdlog::error("Settings::value {} - can't convert", path); + spdlog::error("{}: {} - cannot convert", LOGFUNCTION(), path); } catch (...) { - spdlog::info("Settings::value {} - accessing non-existing value", path); + spdlog::info("{}: {} - accessing non-existing value", LOGFUNCTION(), path); } return defaultValue; } @@ -183,7 +183,7 @@ bool Settings::setValue(QString path, const QJSValue &value) LOG("Settings::setValue", path, value); if (value.isNull()) { - spdlog::error("Settings::setValue {} in {} - value is null", value.toString(), path); + spdlog::error("{}: {} in {} - value is null", LOGFUNCTION(), value.toString(), path); return false; } @@ -228,11 +228,11 @@ bool Settings::setValue(QString path, const QJSValue &value) m_settings[jsonPath] = list; m_projectSettings[jsonPath] = list; } else { - spdlog::error("Settings::setValue {} in {} - only string lists are supported", value.toString(), path); + spdlog::error("{}: {} in {} - only string lists are supported", LOGFUNCTION(), value.toString(), path); } } break; default: - spdlog::error("Settings::setValue {} in {} - value type not handled", value.toString(), path); + spdlog::error("{}: {} in {} - value type not handled", LOGFUNCTION(), value.toString(), path); return false; } @@ -289,7 +289,7 @@ void Settings::saveSettings() QFile file(filePath); if (!file.open(QIODevice::WriteOnly | QIODevice::Truncate)) { - spdlog::error("Settings::saveSettings {}", filePath); + spdlog::error("{}: {}", LOGFUNCTION(), filePath); return; } diff --git a/src/core/symbol.cpp b/src/core/symbol.cpp index 29dcc6c8..4e88dac9 100644 --- a/src/core/symbol.cpp +++ b/src/core/symbol.cpp @@ -143,7 +143,7 @@ ClassSymbol *Symbol::toClass() auto clazz = qobject_cast(this); if (!clazz) - spdlog::warn("Symbol::toClass - {} should be a `Class`.", m_name); + spdlog::warn("{}: {} should be a `Class`.", LOGFUNCTION(), m_name); return clazz; } @@ -164,7 +164,7 @@ FunctionSymbol *Symbol::toFunction() auto function = qobject_cast(this); if (!function) - spdlog::warn("Symbol::toFunction - {} should be either a method or a function.", m_name); + spdlog::warn("{}: {} should be either a method or a function.", LOGFUNCTION(), m_name); return function; } diff --git a/src/core/textdocument.cpp b/src/core/textdocument.cpp index ec3ad4da..4cad6ded 100644 --- a/src/core/textdocument.cpp +++ b/src/core/textdocument.cpp @@ -243,7 +243,7 @@ bool TextDocument::doSave(const QString &fileName) QFile file(fileName); if (!file.open(QIODevice::WriteOnly | QIODevice::Truncate)) { setErrorString(file.errorString()); - spdlog::error("Can't save file {}: {}", fileName, errorString()); + spdlog::error("{} - Can't save file {}: {}", LOGFUNCTION(), fileName, errorString()); return false; } @@ -266,7 +266,7 @@ bool TextDocument::doLoad(const QString &fileName) QFile file(fileName); if (!file.open(QIODevice::ReadOnly)) { setErrorString(file.errorString()); - spdlog::warn("Can't load file {}: {}", fileName, errorString()); + spdlog::warn("{} - Can't load file {}: {}", LOGFUNCTION(), fileName, errorString()); return false; } @@ -1126,7 +1126,7 @@ void TextDocument::gotoMark(const Mark &mark) { LOG("TextDocument::gotoMark", LOG_ARG("mark", mark)); if (mark.document() != this) { - spdlog::error("Can't use a mark from another editor."); + spdlog::error("{}: Can't use a mark from another editor.", LOGFUNCTION()); return; } @@ -1143,7 +1143,7 @@ void TextDocument::selectToMark(const Mark &mark) { LOG("TextDocument::selectToMark", LOG_ARG("mark", mark)); if (mark.document() != this) { - spdlog::error("Can't use a mark from another editor."); + spdlog::error("{}: Can't use a mark from another editor.", LOGFUNCTION()); return; } @@ -1180,7 +1180,7 @@ Core::RangeMark TextDocument::createRangeMark() const int end = cursor.selectionEnd(); if (start == end) - spdlog::warn("TextDocument::createRangeMark: Creating a range mark with an empty range."); + spdlog::warn("{}: Creating a range mark with an empty range.", LOGFUNCTION()); LOG_RETURN("rangeMark", createRangeMark(start, end)); } @@ -1197,7 +1197,7 @@ void TextDocument::selectRangeMark(const Core::RangeMark &mark) LOG("TextDocument::selectRangeMark", LOG_ARG("mark", mark)); if (mark.document() != this) { - spdlog::error("Can't use a range mark from another editor."); + spdlog::error("{}: Can't use a range mark from another editor.", LOGFUNCTION()); return; } @@ -1419,11 +1419,11 @@ int TextDocument::replaceAllInRange(const QString &before, const QString &after, { LOG("TextDocument::replaceAllInRange", LOG_ARG("text", before), after, range, options); if (!range.isValid()) { - spdlog::warn("TextDocument::replaceAllInRange: Invalid range!"); + spdlog::warn("{}: Invalid range!", LOGFUNCTION()); return 0; } if (range.document() != this) { - spdlog::warn("TextDocument::replaceAllInRange: Range is not from this document!"); + spdlog::warn("{}: Range is not from this document!", LOGFUNCTION()); return 0; } @@ -1502,11 +1502,11 @@ int TextDocument::replaceAllRegexpInRange(const QString ®exp, const QString & { LOG("TextDocument::replaceAllRegexpInRange", LOG_ARG("text", regexp), after, range, options); if (!range.isValid()) { - spdlog::warn("TextDocument::replaceAllRegexpInRange: Invalid range!"); + spdlog::warn("{}: Invalid range!", LOGFUNCTION()); return 0; } if (range.document() != this) { - spdlog::warn("TextDocument::replaceAllRegexpInRange: Range is not from this document!"); + spdlog::warn("{}: Range is not from this document!", LOGFUNCTION()); return 0; } diff --git a/src/core/userdialog.cpp b/src/core/userdialog.cpp index b19a29e7..494b760c 100644 --- a/src/core/userdialog.cpp +++ b/src/core/userdialog.cpp @@ -53,7 +53,7 @@ QJSValue UserDialog::getOpenFileName(const QString &caption, const QString &dir, LOG("UserDialog::getOpenFileName", caption, dir, filters); const QString s = QFileDialog::getOpenFileName(dialogParent(), caption, dir, filters); if (!s.isEmpty()) { - spdlog::debug("UserDialog::getOpenFileName returns {}", s); + spdlog::debug("{} returns {}", LOGFUNCTION(), s); return s; } return QJSValue(QJSValue::NullValue); @@ -71,7 +71,7 @@ QJSValue UserDialog::getSaveFileName(const QString &caption, const QString &dir, LOG("UserDialog::getSaveFileName", caption, dir, filters); const QString s = QFileDialog::getSaveFileName(dialogParent(), caption, dir, filters); if (!s.isEmpty()) { - spdlog::debug("UserDialog::getSaveFileName returns {}", s); + spdlog::debug("{} returns {}", LOGFUNCTION(), s); return s; } return QJSValue(QJSValue::NullValue); @@ -88,7 +88,7 @@ QJSValue UserDialog::getExistingDirectory(const QString &caption, const QString LOG("UserDialog::getExistingDirectory", caption, dir); const QString s = QFileDialog::getExistingDirectory(dialogParent(), caption, dir); if (!s.isEmpty()) { - spdlog::debug("UserDialog::getExistingDirectory returns {}", s); + spdlog::debug("{} returns {}", LOGFUNCTION(), s); return s; } return QJSValue(QJSValue::NullValue); @@ -111,7 +111,7 @@ QJSValue UserDialog::getItem(const QString &title, const QString &label, const Q bool ok; const QString ret = QInputDialog::getItem(dialogParent(), title, label, items, current, editable, &ok); if (ok) { - spdlog::debug("UserDialog::getItem returns {}", ret); + spdlog::debug("{} returns {}", LOGFUNCTION(), ret); return ret; } return QJSValue(QJSValue::NullValue); @@ -136,7 +136,7 @@ QJSValue UserDialog::getDouble(const QString &title, const QString &label, doubl const double ret = QInputDialog::getDouble(dialogParent(), title, label, value, min, max, decimals, &ok, Qt::WindowFlags(), step); if (ok) { - spdlog::debug("UserDialog::getDouble returns {}", ret); + spdlog::debug("{} returns {}", LOGFUNCTION(), ret); return ret; } return QJSValue(QJSValue::NullValue); @@ -158,7 +158,7 @@ QJSValue UserDialog::getInt(const QString &title, const QString &label, int valu bool ok; const int ret = QInputDialog::getInt(dialogParent(), title, label, value, min, max, step, &ok); if (ok) { - spdlog::debug("UserDialog::getInt returns {}", ret); + spdlog::debug("{} returns {}", LOGFUNCTION(), ret); return ret; } return QJSValue(QJSValue::NullValue); @@ -177,7 +177,7 @@ QJSValue UserDialog::getText(const QString &title, const QString &label, const Q bool ok; const QString ret = QInputDialog::getText(dialogParent(), title, label, QLineEdit::Normal, text, &ok); if (ok) { - spdlog::debug("UserDialog::getText returns {}", ret); + spdlog::debug("{} returns {}", LOGFUNCTION(), ret); return ret; } return QJSValue(QJSValue::NullValue); diff --git a/src/core/utils.cpp b/src/core/utils.cpp index 9d921f5f..5d9cc546 100644 --- a/src/core/utils.cpp +++ b/src/core/utils.cpp @@ -155,7 +155,7 @@ QString Utils::mktemp(const QString &pattern) return {}; file.close(); - spdlog::debug("Utils::mktemp created {}", tmp); + spdlog::debug("{}: created {}", LOGFUNCTION(), tmp); return file.fileName(); } diff --git a/src/gui/apiexecutorwidget.cpp b/src/gui/apiexecutorwidget.cpp index 2ef4c161..ca9c6831 100644 --- a/src/gui/apiexecutorwidget.cpp +++ b/src/gui/apiexecutorwidget.cpp @@ -288,7 +288,7 @@ void APIExecutorWidget::executeAPI(Core::Document *document, const QByteArray &n genericArgs.value(5), genericArgs.value(6), genericArgs.value(7), genericArgs.value(8), genericArgs.value(9)); if (!success) - spdlog::error("Error trying to execute the function {}", name); + spdlog::error("{}: Error trying to execute the function {}", LOGFUNCTION(), name); } void APIExecutorWidget::open() diff --git a/src/gui/optionsdialog.cpp b/src/gui/optionsdialog.cpp index e4eb0ed2..b80ad047 100644 --- a/src/gui/optionsdialog.cpp +++ b/src/gui/optionsdialog.cpp @@ -235,7 +235,7 @@ void OptionsDialog::initializeCppSettings() if (model->insertRows(0, 1)) { model->setData(model->index(0), excludeMacro); } else { - spdlog::warn("OptionsDialog::excludeMacro: Failed to create new row!"); + spdlog::warn("{}: OptionsDialog::excludeMacro: Failed to create new row!", LOGFUNCTION()); } } }); diff --git a/src/gui/scriptlistpanel.cpp b/src/gui/scriptlistpanel.cpp index 35974360..6b779393 100644 --- a/src/gui/scriptlistpanel.cpp +++ b/src/gui/scriptlistpanel.cpp @@ -93,7 +93,7 @@ void ScriptListPanel::runScript(const QModelIndex &index) const auto fileName = index.data(Core::ScriptModel::PathRole).toString(); if (fileName.isEmpty()) { - spdlog::warn("ScriptListPanel::runScript - fileName is empty"); + spdlog::warn("{}: fileName is empty", LOGFUNCTION()); return; } diff --git a/src/gui/scriptpanel.cpp b/src/gui/scriptpanel.cpp index abae63a7..9b73bc8c 100644 --- a/src/gui/scriptpanel.cpp +++ b/src/gui/scriptpanel.cpp @@ -154,7 +154,7 @@ void ScriptPanel::openScript() QFileInfo fi(m_fileName); m_scriptName->setText(fi.fileName()); } else { - spdlog::error("Error reading script - can't open the file for reading."); + spdlog::error("{}: Error reading script - can't open the file for reading.", LOGFUNCTION()); } } @@ -207,7 +207,7 @@ void ScriptPanel::saveScript() if (isQml && text.contains("ScriptDialog")) createDialogFile(); } else { - spdlog::error("Error saving script - can't open the file for writing."); + spdlog::error("{}: Error saving script - can't open the file for writing.", LOGFUNCTION()); } } @@ -226,7 +226,7 @@ void ScriptPanel::editDialog() if (!QDesktopServices::openUrl(QString("file:///%1").arg(uiFileName))) { QMessageBox::information(this, "Script Dialog Edition", "In order to edit the dialog, you need to install the Qt Designer tool."); - spdlog::error("Error editing dialog - Qt Designer is not found."); + spdlog::error("{}: Error editing dialog - Qt Designer is not found.", LOGFUNCTION()); } } @@ -244,7 +244,7 @@ QString ScriptPanel::createDialogFile() QString uiFileName = fi.absolutePath() + '/' + fi.baseName() + ".ui"; if (!QFile::exists(uiFileName) && !QFile::copy(":/gui/default-dialog.ui", uiFileName)) { - spdlog::error("Error creating dialog - can't create the dialog file."); + spdlog::error("{}: Error creating dialog - can't create the dialog file.", LOGFUNCTION()); return {}; } return uiFileName; @@ -268,7 +268,7 @@ void ScriptPanel::runScript() file.close(); Core::ScriptManager::instance()->runScript(file.fileName(), false, false); } else { - spdlog::error("Error running script - can't save to temporary file."); + spdlog::error("{}: Error running script - can't save to temporary file.", LOGFUNCTION()); } } diff --git a/src/gui/slintview.cpp b/src/gui/slintview.cpp index c02137fe..e3cd6740 100644 --- a/src/gui/slintview.cpp +++ b/src/gui/slintview.cpp @@ -67,7 +67,7 @@ SlintView::~SlintView() void SlintView::runSlint() { if (m_process && m_process->state() == QProcess::Running) { - spdlog::warn("Slint-viewer process is already running"); + spdlog::warn("{}: Slint-viewer process is already running", LOGFUNCTION()); return; } diff --git a/src/lsp/client.cpp b/src/lsp/client.cpp index fa328ee9..7af83241 100644 --- a/src/lsp/client.cpp +++ b/src/lsp/client.cpp @@ -83,7 +83,7 @@ bool Client::initialize(const QString &rootPath) if (!m_backend->start()) return false; - spdlog::debug("LSP server started in: {}", rootPath); + spdlog::debug("{}: LSP server started in: {}", LOGFUNCTION(), rootPath); InitializeRequest request; request.id = m_nextRequestId++; @@ -254,14 +254,14 @@ void Client::setState(State newState) bool Client::initializeCallback(InitializeRequest::Response response) { if (!response.isValid() || response.error) { - spdlog::error("Error initializing the server"); + spdlog::error("{}: Error initializing the server", LOGFUNCTION()); setState(Error); return false; } m_serverCapabilities = response.result->capabilities; m_backend->sendNotification(InitializedNotification()); - spdlog::debug("LSP server initialized"); + spdlog::debug("{}: LSP server initialized", LOGFUNCTION()); setState(Initialized); return true; } @@ -269,13 +269,13 @@ bool Client::initializeCallback(InitializeRequest::Response response) bool Client::shutdownCallback(ShutdownRequest::Response response) { if (!response.isValid() || response.error) { - spdlog::error("Error shutting down the server"); + spdlog::error("{}: Error shutting down the server", LOGFUNCTION()); setState(Error); return false; } m_backend->sendNotification(ExitNotification()); - spdlog::debug("LSP server exited"); + spdlog::debug("{}: LSP server exited", LOGFUNCTION()); setState(Shutdown); return true; } diff --git a/src/rccore/lexer.cpp b/src/rccore/lexer.cpp index 643a8f29..436da83d 100644 --- a/src/rccore/lexer.cpp +++ b/src/rccore/lexer.cpp @@ -266,7 +266,7 @@ std::optional Lexer::readNext() if (ch == '<') return readInclude(); - spdlog::critical("{}({}): general lexer error reading next token", m_fileName, m_stream.line()); + spdlog::critical("{}: {}({}): general lexer error reading next token", LOGFUNCTION(), m_fileName, m_stream.line()); return {}; } diff --git a/src/rccore/rc_convert.cpp b/src/rccore/rc_convert.cpp index 7f77eb24..ec92fdb8 100644 --- a/src/rccore/rc_convert.cpp +++ b/src/rccore/rc_convert.cpp @@ -33,7 +33,8 @@ static QList splitToolBar(const Data &data, const ToolBar &toolBar, const const int width = toolBar.iconSize.width(); if (iconCount * width != image.width()) { - spdlog::warn("{}({}): asset and toolbar widths don't match for {}", data.fileName, asset.line, asset.id); + spdlog::warn("{}: {}({}): asset and toolbar widths don't match for {}", LOGFUNCTION(), data.fileName, + asset.line, asset.id); } QList assets; @@ -137,7 +138,7 @@ static void convertStyles(const Data &data, Widget &widget, Data::Control &contr control.styles.removeOne("WS_TABSTOP"); if (!control.styles.isEmpty()) { - spdlog::info("{}({}): {} has unused styles {}", data.fileName, control.line, control.id, + spdlog::info("{}: {}({}): {} has unused styles {}", LOGFUNCTION(), data.fileName, control.line, control.id, control.styles.join(", ")); } } @@ -578,7 +579,8 @@ static Widget convertControl(const Data &data, const QString &dialogId, Data::Co if (control.className == "MfcButton") return convertButton(data, control); - spdlog::warn("{}({}): unknown CONTROL {} / {}", data.fileName, control.line, control.id, control.className); + spdlog::warn("{}: {}({}): unknown CONTROL {} / {}", LOGFUNCTION(), data.fileName, control.line, control.id, + control.className); Widget widget; widget.className = "QWidget"; @@ -631,7 +633,7 @@ static Widget convertChildWidget(const Data &data, const QString &dialogId, Data widget = convertControl(data, dialogId, control, useIdForPixmap); break; default: - spdlog::error("{}({}): unknown control type {}", data.fileName, control.line, + spdlog::error("{}: {}({}): unknown control type {}", LOGFUNCTION(), data.fileName, control.line, Token {Token::Keyword, type}.toString()); } @@ -718,7 +720,7 @@ Widget convertDialog(const Data &data, const Data::Dialog &d, Widget::Conversion } if (!dialog.styles.isEmpty()) { - spdlog::info("{}({}): {} has unused styles {}", data.fileName, dialog.line, dialog.id, + spdlog::info("{}: {}({}): {} has unused styles {}", LOGFUNCTION(), data.fileName, dialog.line, dialog.id, dialog.styles.join(", ")); } @@ -761,7 +763,7 @@ static void createActionForMenu(const Data &data, QList &actions, QHash< } else if (item.isAction()) { // We stop here in case of duplication in the menu if (actionIdMap.contains(item.id)) { - spdlog::info("{}({}): duplicate action in menu {}", data.fileName, item.line, item.id); + spdlog::info("{}: {}({}): duplicate action in menu {}", LOGFUNCTION(), data.fileName, item.line, item.id); return; } @@ -782,8 +784,8 @@ static void createActionForMenu(const Data &data, QList &actions, QHash< static Shortcut createShortcut(const Data &data, const Data::Accelerator &accelerator) { if (accelerator.isUnknown()) { - spdlog::warn("{}({}): unknown shortcut {} / {}", data.fileName, accelerator.line, accelerator.id, - accelerator.shortcut); + spdlog::warn("{}: {}({}): unknown shortcut {} / {}", LOGFUNCTION(), data.fileName, accelerator.line, + accelerator.id, accelerator.shortcut); return {accelerator.shortcut, true}; } return {accelerator.shortcut}; @@ -915,7 +917,7 @@ QString convertLanguageToCode(const QString &name) } } } - spdlog::error("Unknown language name conversion {} ", name); + spdlog::error("{}: Unknown language name conversion {} ", LOGFUNCTION(), name); return "en"; } diff --git a/src/rccore/rc_parse.cpp b/src/rccore/rc_parse.cpp index 05f82d4d..81ff0875 100644 --- a/src/rccore/rc_parse.cpp +++ b/src/rccore/rc_parse.cpp @@ -155,7 +155,8 @@ static void readDialogStatements(Context &context, Data::Dialog &dialog) dialog.styles = readStyles(lexer); break; default: - spdlog::error("{}({}): parser error on token {}", context.fileName(), context.line(), token->prettyPrint()); + spdlog::error("{}: {}({}): parser error on token {}", LOGFUNCTION(), context.fileName(), context.line(), + token->prettyPrint()); break; } } @@ -908,7 +909,8 @@ static Data::Accelerator readAccelerator(Context &context) } accelerator.shortcut = toShortcut(event, isAscii, modifiers); if (accelerator.shortcut.isEmpty()) { - spdlog::warn("{}({}): parser unknown accelerator {}", context.fileName(), context.line(), event); + spdlog::warn("{}: {}({}): parser unknown accelerator {}", LOGFUNCTION(), context.fileName(), context.line(), + event); } return accelerator; } @@ -1025,11 +1027,11 @@ static MenuItem readMenuItem(Context &context) case Keywords::MFSENABLED: case Keywords::MFTSTRING: case Keywords::MFTRIGHTJUSTIFY: - spdlog::info("{}({}): parser unused token {}", context.fileName(), context.line(), + spdlog::info("{}: {}({}): parser unused token {}", LOGFUNCTION(), context.fileName(), context.line(), flagToken->prettyPrint()); break; default: - spdlog::warn("{}({}): parser unhandled token {}", context.fileName(), context.line(), + spdlog::warn("{}: {}({}): parser unhandled token {}", LOGFUNCTION(), context.fileName(), context.line(), flagToken->prettyPrint()); } @@ -1058,7 +1060,8 @@ static void readMenuChildren(Context &context, QList &children) children.append(readMenuItem(context)); break; default: - spdlog::warn("{}({}): parser unhandled token {}", context.fileName(), context.line(), token->prettyPrint()); + spdlog::warn("{}: {}({}): parser unhandled token {}", LOGFUNCTION(), context.fileName(), context.line(), + token->prettyPrint()); } token = lexer.next(); } @@ -1135,7 +1138,8 @@ static void readToolBar(Context &context, const QString &id) break; } default: - spdlog::warn("{}({}): parser unhandled token {}", context.fileName(), context.line(), token->prettyPrint()); + spdlog::warn("{}: {}({}): parser unhandled token {}", LOGFUNCTION(), context.fileName(), context.line(), + token->prettyPrint()); } lexer.skipLine(); token = lexer.next(); @@ -1181,7 +1185,8 @@ static Data::Control readControl(Context &context, const std::optional &t control.type = static_cast(controlType); if (!knownControls.contains(controlType)) { - spdlog::warn("{}({}): parser unknown control {}", context.fileName(), context.line(), token->prettyPrint()); + spdlog::warn("{}: {}({}): parser unknown control {}", LOGFUNCTION(), context.fileName(), context.line(), + token->prettyPrint()); return control; } @@ -1307,7 +1312,8 @@ static void readResource(Context &context, const std::optional &token, co case Keywords::HTML: case Keywords::MESSAGETABLE: case Keywords::REGISTRY: - spdlog::info("{}({}): parser unused token {}", context.fileName(), context.line(), token->prettyPrint()); + spdlog::info("{}: {}({}): parser unused token {}", LOGFUNCTION(), context.fileName(), context.line(), + token->prettyPrint()); lexer.skipLine(); break; case Keywords::AFX_DIALOG_LAYOUT: @@ -1350,11 +1356,13 @@ static void readResource(Context &context, const std::optional &token, co break; case Keywords::BEGIN: - spdlog::warn("{}({}): parser unhandled token {}", context.fileName(), context.line(), token->prettyPrint()); + spdlog::warn("{}: {}({}): parser unhandled token {}", LOGFUNCTION(), context.fileName(), context.line(), + token->prettyPrint()); lexer.skipScope(); break; default: - spdlog::warn("{}({}): parser unhandled token {}", context.fileName(), context.line(), token->prettyPrint()); + spdlog::warn("{}: {}({}): parser unhandled token {}", LOGFUNCTION(), context.fileName(), context.line(), + token->prettyPrint()); lexer.skipLine(); break; } @@ -1376,8 +1384,8 @@ static void readDirective(Context &context, const QString &directive) if (fullPath.value().endsWith(".h")) { QHash resourceMap = loadResourceFile(include.fileName); if (resourceMap.isEmpty()) { - spdlog::warn("{}({}): parser can't load resource file {}", context.fileName(), context.line(), - include.fileName); + spdlog::warn("{}: {}({}): parser can't load resource file {}", LOGFUNCTION(), context.fileName(), + context.line(), include.fileName); } else { context.rcFile.resourceMap.insert(resourceMap); } @@ -1420,15 +1428,15 @@ RcFile parse(const QString &fileName) case Token::Operator_Comma: case Token::Operator_Or: case Token::String: - spdlog::error("{}({}): parser error on token {}", context.fileName(), context.line(), + spdlog::error("{}: {}({}): parser error on token {}", LOGFUNCTION(), context.fileName(), context.line(), token->prettyPrint()); break; case Token::Integer: case Token::Word: // We can only read one integer/id/word if (previousToken) { - spdlog::error("{}({}): parser error on token {}", context.fileName(), context.line(), - token->prettyPrint()); + spdlog::error("{}: {}({}): parser error on token {}", LOGFUNCTION(), context.fileName(), + context.line(), token->prettyPrint()); } previousToken = token; break; @@ -1443,10 +1451,10 @@ RcFile parse(const QString &fileName) } } } catch (...) { - spdlog::critical("{}({}): parser general error", context.fileName(), context.line()); + spdlog::critical("{}: {}({}): parser general error", LOGFUNCTION(), context.fileName(), context.line()); return {}; } - spdlog::trace("{} ms for parsing {}", static_cast(time.elapsed()), context.fileName()); + spdlog::trace("{}: {} ms for parsing {}", LOGFUNCTION(), static_cast(time.elapsed()), context.fileName()); rcFile.isValid = true; return rcFile; } diff --git a/src/rccore/ribbon.cpp b/src/rccore/ribbon.cpp index ebea4469..b0567145 100644 --- a/src/rccore/ribbon.cpp +++ b/src/rccore/ribbon.cpp @@ -248,7 +248,7 @@ bool Ribbon::load() pugi::xml_parse_result result = document.load_file(fileName.toLatin1().constData()); if (!result) { - spdlog::critical("{}({}): {}", fileName, result.offset, result.description()); + spdlog::critical("{}: - {}({}): {}", LOGFUNCTION(), fileName, result.offset, result.description()); return false; } diff --git a/src/treesitter/node.cpp b/src/treesitter/node.cpp index 5de8a0db..90ee3161 100644 --- a/src/treesitter/node.cpp +++ b/src/treesitter/node.cpp @@ -54,7 +54,7 @@ QString Node::fieldNameForChild(const Node &child) const // result = name; // } // } else { - // spdlog::warn("Node::fieldNameForChild - given node is not a child!"); + // spdlog::warn("{}: given node is not a child!", LOGFUNCTION()); // } // // However, the code produces incorrect field names in a few cases. @@ -105,7 +105,7 @@ QString Node::fieldNameForChild(const Node &child) const ts_tree_cursor_delete(&cursor); if (!found) { - spdlog::warn("Node::fieldNameForChild - given node is not a child!"); + spdlog::warn("{}: given node is not a child!", LOGFUNCTION()); } return result; diff --git a/src/treesitter/predicates.cpp b/src/treesitter/predicates.cpp index 09613dbf..ca1f3a0d 100644 --- a/src/treesitter/predicates.cpp +++ b/src/treesitter/predicates.cpp @@ -193,13 +193,13 @@ bool Predicates::filter_eq_with(const QueryMatch &match, const QList(&arg)) { texts.emplace(textTransform(*string)); } else if (std::holds_alternative(arg)) { - spdlog::warn("Predicates: #eq? - Unmatched capture!"); + spdlog::warn("{}: Unmatched capture!", LOGFUNCTION()); // Insert an empty string into the set if we find an unmatched capture. // This likely means we have encountered a quantified capture that matched 0 times. // By inserting an empty string, we can check that all other things are also "empty". texts.emplace(""); } else { - spdlog::warn("Predicates: #eq? - Impossible argument type!"); + spdlog::warn("{}: Impossible argument type!", LOGFUNCTION()); return false; } } @@ -265,7 +265,7 @@ bool Predicates::filter_eq_except_with(const QueryMatch &match, const auto idCaptures = match.capturesWithId(capture.id); if (idCaptures.isEmpty()) { - spdlog::warn("Predicates: #eq_except? - No captures"); + spdlog::warn("{}: No captures", LOGFUNCTION()); // Insert an empty string into the set if we find an unmatched capture. // This likely means we have encountered a quantified capture that matched 0 times. // So check whether the expected string is also empty @@ -280,11 +280,11 @@ bool Predicates::filter_eq_except_with(const QueryMatch &match, return true; } else { - spdlog::warn("Predicates: #eq_except? - Expected Capture argument"); + spdlog::warn("{}: Expected Capture argument", LOGFUNCTION()); return false; } } else { - spdlog::warn("Predicates: #eq_except? - Non-string expected argument"); + spdlog::warn("{}: Non-string expected argument", LOGFUNCTION()); return false; } } @@ -392,7 +392,7 @@ bool Predicates::filter_match(const QueryMatch &match, if (const auto regexString = std::get_if(&matched.first())) { const QRegularExpression regex(*regexString); if (!regex.isValid()) { - spdlog::warn("Predicates: #match? - Invalid regex"); + spdlog::warn("{}: Invalid regex", LOGFUNCTION()); return false; } @@ -403,16 +403,16 @@ bool Predicates::filter_match(const QueryMatch &match, return false; } } else if (std::holds_alternative(argument)) { - spdlog::warn("Predicates: #match? - Unmatched capture argument"); + spdlog::warn("{}: Unmatched capture argument", LOGFUNCTION()); return false; } else { - spdlog::warn("Predicates: #match? - Argument is not a capture"); + spdlog::warn("{}: Argument is not a capture", LOGFUNCTION()); return false; } } } else { - spdlog::warn("Predicates: #match? - First argument is not a string"); + spdlog::warn("{}: First argument is not a string", LOGFUNCTION()); return false; } @@ -447,7 +447,7 @@ void Predicates::findMessageMap() const } if (!m_rootNode.has_value()) { - spdlog::warn("Predicates::findMessageMap: No rootNode!"); + spdlog::warn("{}: No rootNode!", LOGFUNCTION()); return; } @@ -514,14 +514,14 @@ bool Predicates::filter_in_message_map(const QueryMatch &match, const PredicateA return false; } } else { - spdlog::warn("Predicate: #in_message_map? - Non-Capture Argument!"); + spdlog::warn("{}: Non-Capture Argument!", LOGFUNCTION()); return false; } } return true; } else { - spdlog::warn("Predicate: #in_message_map? - No MESSAGE_MAP found!"); + spdlog::warn("{}: No MESSAGE_MAP found!", LOGFUNCTION()); return false; } } diff --git a/src/utils/log.h b/src/utils/log.h index eaefd5ef..c435a145 100644 --- a/src/utils/log.h +++ b/src/utils/log.h @@ -11,4 +11,75 @@ #pragma once #include "qt_fmt_format.h" +#include +#include #include + +/** + * Returns the full (local) path to the current file. + * e.g: /home/someone/knut/src/core/settings.cpp + */ +#define FILENAME std::source_location::current().file_name() + +/** + * Returns the current file line number. + * e.g: 175 + */ +#define LINE std::source_location::current().line() + +/** + * Format the std::source_location::current().file_name() return value + * to a simplified 'className::functionName' string value. + * The LOGFUNCTION() macro is meant to be called by spdlog to point to the function location. + * e.g: spdlog::error("{}: {} - cannot convert", LOGFUNCTION(), path); + */ +#define LOGFUNCTION() std::format("{}", LogUtils::formatToClassNameFunctionName(std::source_location::current())) + +// Convenience: namespace used by the LOGFUNCTION() macro. +// We could expand further on, to format the return values for FILENAME and LINE eventually. +namespace LogUtils { + +inline std::string formatToClassNameFunctionName(const std::source_location &location) +{ + // Get the functionName. + // str = e.g: "QVariant Core::Settings::value(QString, const QVariant&) const" + std::string str = location.function_name(); + + // Remove the return value + size_t pos = str.find(' '); + if (pos != std::string::npos) + str = str.substr(pos + 1); + + // Remove the leading symbol if any + if (str[0] == '*' || str[0] == '&') { + str = str.substr(1); + } + + // Find position of the arguments list + pos = str.find("("); + if (pos != std::string::npos) + // Extract the section before the arguments list. + // str= e.g: QVariant Core::Settings::value + str = str.substr(0, pos); + + size_t lastPos = str.rfind("::"); + // If there is at least one double column. + if (lastPos != std::string::npos) { + int occurrences = 0; + size_t index = 0; + // Count the number of occurrences. + while ((index = str.find("::", index)) != std::string::npos) { + ++occurrences; + index += 2; // Skip the found "::" + } + // Extract string and double column for all occurrences excepted for the last occurrence of "::". + while (occurrences > 1) { + pos = str.find("::"); + str = str.substr(pos + 2); // Skip the found "::" + occurrences -= 1; + } + } + return str; +} + +} // namespace LogUtils