Skip to content

feat: categorize logs and register dynamic dconfig log watcher - #101

Merged
deepin-bot[bot] merged 1 commit into
linuxdeepin:masterfrom
add-uos:feat/ocr-debugsource
Nov 5, 2026
Merged

deepin-bot[bot] merged 1 commit into
linuxdeepin:masterfrom
add-uos:feat/ocr-debugsource

Conversation

@add-uos

@add-uos add-uos commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

概要:deepin-ocr 调试模式适配——Part 1/2:日志分类化 + 动态日志监听(10 个文件)

配套提交:Part 2/2(dconfig meta + 安装规则,3 个文件)单独一个 PR;deepin-debug-config 侧 json + shell 在 Gerrit develop/snipe 另行提交。

改动内容(本 PR 10 个文件)

  1. 日志分类化

    • 分类 dmOcr 由 deepin.ocr 规范为 org.deepin.ocr(src/util/log.cpp)
    • 补齐全部未分类日志(OCREngine / imageview / ocrinterface / mainwidget / resulttextview / main / dconfigmanager),按级别使用 qCDebug/qCInfo/qCWarning(dmOcr)
  2. 动态日志监听(src/util/logger.h/.cpp,参考 deepin-reader MLogger)

    • 新增 MLogger:DConfig::create("org.deepin.ocr", "org.deepin.ocr") 读取 log_rules 并 QLoggingCategory::setFilterRules 应用
    • 构造时先 qunsetenv("QT_LOGGING_RULES")(在任何日志打印之前),规则分隔符 ; → \n 后再设置
    • 连接 DConfig::valueChanged,运行中切换调试级别即时生效(无需重启)
    • main() 中在 Application 实例化之前创建,实例存活整个进程
  3. 编译宏排查:仓库无 QT_NO_DEBUG_OUTPUT / QT_NO_WARNING_OUTPUT 有效定义(Release 打包不受影响)

验证

  • ✅ 编译通过(最终合并态);SPDX 头检查 0 违规(CI 同款参数)
  • ✅ 四级切换实测(dde-dconfig --set + MLogger valueChanged,全程未重启进程):warning(默认)→ debug(全出)→ info(qCDebug 消失)→ warning(分类日志 0 条)
  • ✅ debug/info 规则限定 org.deepin.ocr*,无 Qt 框架日志混入

Summary by Sourcery

Enable categorized OCR logging with dynamically adjustable runtime log rules.

New Features:

  • Add a process-wide logger that applies application-specific DConfig rules and updates logging levels at runtime.

Enhancements:

  • Standardize OCR application logging under the org.deepin.ocr category and classify previously unscoped messages by severity.

@github-actions

Copy link
Copy Markdown
  • 检测到敏感词unset变动
详情
    {
    "unset": {
        "src/main.cpp": {
            "b": [
                "    // \u52a8\u6001\u65e5\u5fd7\u76d1\u542c\u5fc5\u987b\u5728\u4efb\u4f55\u65e5\u5fd7\u6253\u5370\u4e4b\u524d\u521b\u5efa\uff08qunsetenv \u624d\u80fd\u751f\u6548\uff09\uff0c"
            ]
        },
        "src/util/logger.cpp": {
            "b": [
                "    // qunsetenv \u4e4b\u524d\u4e00\u5b9a\u4e0d\u8981\u6709\u4efb\u4f55\u65e5\u5fd7\u6253\u5370\uff0c\u5426\u5219\u53d6\u6d88\u73af\u5883\u53d8\u91cf\u8bbe\u7f6e\u4e0d\u4f1a\u751f\u6548",
                "    qunsetenv(\"QT_LOGGING_RULES\");"
            ]
        }
    }
}

@github-actions

Copy link
Copy Markdown

TAG Bot

TAG: 6.5.17
EXISTED: no
DISTRIBUTION: unstable

@sourcery-ai

sourcery-ai Bot commented Oct 29, 2026

Copy link
Copy Markdown

Reviewer's Guide

Adapts deepin-ocr to dynamic, category-scoped logging by introducing a process-lifetime DConfig-backed filter, migrating diagnostics to the org.deepin.ocr category, and installing matching DConfig metadata and CMake support.

Sequence diagram for dynamic OCR logging configuration

sequenceDiagram
    participant Main
    participant MLogger
    participant DConfig
    participant QLoggingCategory

    Main->>MLogger: MLogger()
    MLogger->>MLogger: qunsetenv(QT_LOGGING_RULES)
    MLogger->>DConfig: create(org.deepin.ocr, org.deepin.ocr)
    MLogger->>DConfig: value(log_rules)
    MLogger->>QLoggingCategory: setFilterRules(log_rules)
    DConfig-->>MLogger: valueChanged(log_rules)
    MLogger->>DConfig: value(log_rules)
    MLogger->>QLoggingCategory: setFilterRules(log_rules)
Loading

File-Level Changes

Change Details Files
Introduces a process-lifetime logger that loads and applies DConfig rules before Qt application initialization and updates logging filters when the configuration changes.
  • Adds MLogger with QT_LOGGING_RULES cleanup, semicolon-to-newline rule conversion, and DConfig valueChanged handling.
  • Creates the logger before QApplication/Application construction so early messages use the configured filters.
  • Retains existing environment rules while merging them with DConfig rules during initialization.
src/util/logger.h
src/util/logger.cpp
src/main.cpp
Converts application diagnostics to the org.deepin.ocr logging category and assigns existing messages to Qt debug, info, and warning levels.
  • Renames dmOcr from deepin.ocr to org.deepin.ocr.
  • Replaces uncategorized qDebug/qInfo/qWarning calls across engine, UI, DBus, and DConfig code with categorized logging macros.
  • Adds required logging-category includes to affected sources.
src/util/log.cpp
src/engine/OCREngine.cpp
src/main.cpp
src/mainwidget.cpp
src/resulttextview.cpp
src/service/ocrinterface.h
src/utils/dconfigmanager.cpp
src/view/imageview.cpp
Adds installable DConfig metadata and makes the CMake helper support configurable application IDs.
  • Adds org.deepin.ocr log_rules defaults with warning enabled and debug/info disabled.
  • Extends INSTALL_DCONFIG with an optional APPID argument while preserving the deepin-ocr default.
  • Updates installation wiring and documents the intended app/config identifier alignment.
assets/configs/org.deepin.ocr.json
install_dconfig.cmake
src/CMakeLists.txt
Updates package metadata and SPDX copyright ranges for the modified implementation files.
  • Adds the release changelog entry.
  • Refreshes copyright year ranges in touched source files.
debian/changelog
src/engine/OCREngine.cpp
src/main.cpp
src/resulttextview.cpp
src/service/ocrinterface.h
src/utils/dconfigmanager.cpp
src/view/imageview.cpp

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 4 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="src/util/logger.cpp" line_range="31-32" />
<code_context>
+
+#ifdef DTKCORE_CLASS_DConfig
+    // set dconfig
+    m_config = DConfig::create("org.deepin.ocr", "org.deepin.ocr");
+    logRules = m_config->value("log_rules").toByteArray();
+    appendRules(logRules);
+    setRules(m_rules);
</code_context>
<issue_to_address>
**Application exits during startup**

When DConfig::create returns null, `MLogger` immediately dereferences `m_config` to read `log_rules`, so construction terminates the process before the application starts.

Check `m_config` before reading `log_rules` and continue with the captured environment rules when creation fails.
</issue_to_address>

### Comment 2
<location path="src/util/logger.cpp" line_range="39" />
<code_context>
+    // watch dconfig
+    connect(m_config, &DConfig::valueChanged, this, [this](const QString &key) {
+        if (key == "log_rules") {
+            setRules(m_config->value(key).toByteArray());
+        }
+    });
</code_context>
<issue_to_address>
**Environment filters stop applying**

When environment rules are set and `log_rules` changes at runtime, `setRules()` replaces the initially merged filter set with only the DConfig value, so environment-configured filters stop applying and logging behavior changes.

Rebuild the active rules from both the environment rules and the updated DConfig value before calling `setRules()`.
</issue_to_address>

### Comment 3
<location path="src/util/logger.cpp" line_range="70" />
<code_context>
+    tmpRules = tmpRules.replace(";", "\n");
+    auto tmplist = tmpRules.split('\n');
+    for (int i = 0; i < tmplist.count(); i++)
+        if (m_rules.contains(tmplist.at(i))) {
+            tmplist.removeAt(i);
+            i--;
</code_context>
<issue_to_address>
**Substring match suppresses DConfig rules**

When an environment rule contains a DConfig rule as a substring but is not the same rule, `m_rules.contains` treats any substring match as a duplicate, so an environment rule such as `xorg.deepin.ocr*.debug=false` suppresses the distinct DConfig rule `org.deepin.ocr*.debug=false`. The DConfig policy is then not applied, and the application category follows other matching rules or Qt defaults instead.

Compare normalized individual rules for exact equality rather than using substring containment.
</issue_to_address>

### Comment 4
<location path="src/util/logger.cpp" line_range="61" />
<code_context>
+    auto tmpRules = rules;
+    // Qt 限制:setFilterRules 的规则分隔符必须为 \n,不能是 ;
+    m_rules = tmpRules.replace(";", "\n");
+    QLoggingCategory::setFilterRules(m_rules);
+}
+
</code_context>
<issue_to_address>
**Framework debug logs remain enabled**

When A Qt/framework category emits debug or info messages while the app’s logging rules are active, `setFilterRules` applies only the app-category rules from DConfig; Qt categories that do not match them retain Qt’s default filter, so their debug and info messages appear alongside app logs instead of remaining excluded.

Add explicit wildcard rules to disable debug/info for unmatched categories, then enable the requested levels for `org.deepin.ocr*`.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread src/util/logger.cpp
Comment on lines +31 to +32
m_config = DConfig::create("org.deepin.ocr", "org.deepin.ocr");
logRules = m_config->value("log_rules").toByteArray();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 High · Application exits during startup

When DConfig::create returns null, MLogger immediately dereferences m_config to read log_rules, so construction terminates the process before the application starts.

Check m_config before reading log_rules and continue with the captured environment rules when creation fails.

Prompt for AI agents
In `src/util/logger.cpp` at lines 31-32:

**Application exits during startup**

When DConfig::create returns null, `MLogger` immediately dereferences `m_config` to read `log_rules`, so construction terminates the process before the application starts.

Check `m_config` before reading `log_rules` and continue with the captured environment rules when creation fails.

Comment thread src/util/logger.cpp
// watch dconfig
connect(m_config, &DConfig::valueChanged, this, [this](const QString &key) {
if (key == "log_rules") {
setRules(m_config->value(key).toByteArray());

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Environment filters stop applying

When environment rules are set and log_rules changes at runtime, setRules() replaces the initially merged filter set with only the DConfig value, so environment-configured filters stop applying and logging behavior changes.

Rebuild the active rules from both the environment rules and the updated DConfig value before calling setRules().

Prompt for AI agents
In `src/util/logger.cpp` at line 39:

**Environment filters stop applying**

When environment rules are set and `log_rules` changes at runtime, `setRules()` replaces the initially merged filter set with only the DConfig value, so environment-configured filters stop applying and logging behavior changes.

Rebuild the active rules from both the environment rules and the updated DConfig value before calling `setRules()`.

Comment thread src/util/logger.cpp
tmpRules = tmpRules.replace(";", "\n");
auto tmplist = tmpRules.split('\n');
for (int i = 0; i < tmplist.count(); i++)
if (m_rules.contains(tmplist.at(i))) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Substring match suppresses DConfig rules

When an environment rule contains a DConfig rule as a substring but is not the same rule, m_rules.contains treats any substring match as a duplicate, so an environment rule such as xorg.deepin.ocr*.debug=false suppresses the distinct DConfig rule org.deepin.ocr*.debug=false. The DConfig policy is then not applied, and the application category follows other matching rules or Qt defaults instead.

Compare normalized individual rules for exact equality rather than using substring containment.

Prompt for AI agents
In `src/util/logger.cpp` at line 70:

**Substring match suppresses DConfig rules**

When an environment rule contains a DConfig rule as a substring but is not the same rule, `m_rules.contains` treats any substring match as a duplicate, so an environment rule such as `xorg.deepin.ocr*.debug=false` suppresses the distinct DConfig rule `org.deepin.ocr*.debug=false`. The DConfig policy is then not applied, and the application category follows other matching rules or Qt defaults instead.

Compare normalized individual rules for exact equality rather than using substring containment.

Comment thread src/util/logger.cpp
auto tmpRules = rules;
// Qt 限制:setFilterRules 的规则分隔符必须为 \n,不能是 ;
m_rules = tmpRules.replace(";", "\n");
QLoggingCategory::setFilterRules(m_rules);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Framework debug logs remain enabled

When A Qt/framework category emits debug or info messages while the app’s logging rules are active, setFilterRules applies only the app-category rules from DConfig; Qt categories that do not match them retain Qt’s default filter, so their debug and info messages appear alongside app logs instead of remaining excluded.

Add explicit wildcard rules to disable debug/info for unmatched categories, then enable the requested levels for org.deepin.ocr*.

Prompt for AI agents
In `src/util/logger.cpp` at line 61:

**Framework debug logs remain enabled**

When A Qt/framework category emits debug or info messages while the app’s logging rules are active, `setFilterRules` applies only the app-category rules from DConfig; Qt categories that do not match them retain Qt’s default filter, so their debug and info messages appear alongside app logs instead of remaining excluded.

Add explicit wildcard rules to disable debug/info for unmatched categories, then enable the requested levels for `org.deepin.ocr*`.

@add-uos
add-uos force-pushed the feat/ocr-debugsource branch from f93e198 to d6ce535 Compare October 30, 2026 02:15
@github-actions

Copy link
Copy Markdown
  • 检测到敏感词unset变动
详情
    {
    "unset": {
        "src/main.cpp": {
            "b": [
                "    // \u52a8\u6001\u65e5\u5fd7\u76d1\u542c\u5fc5\u987b\u5728\u4efb\u4f55\u65e5\u5fd7\u6253\u5370\u4e4b\u524d\u521b\u5efa\uff08qunsetenv \u624d\u80fd\u751f\u6548\uff09\uff0c"
            ]
        },
        "src/util/logger.cpp": {
            "b": [
                "    // qunsetenv \u4e4b\u524d\u4e00\u5b9a\u4e0d\u8981\u6709\u4efb\u4f55\u65e5\u5fd7\u6253\u5370\uff0c\u5426\u5219\u53d6\u6d88\u73af\u5883\u53d8\u91cf\u8bbe\u7f6e\u4e0d\u4f1a\u751f\u6548",
                "    qunsetenv(\"QT_LOGGING_RULES\");"
            ]
        }
    }
}

@add-uos add-uos changed the title feat: adapt debug mode with dynamic logging via dconfig feat: categorize logs and register dynamic dconfig log watcher Oct 30, 2026
@add-uos
add-uos force-pushed the feat/ocr-debugsource branch 2 times, most recently from 80e1e48 to 30bdbd3 Compare November 2, 2026 14:11
- Rename logging category dmOcr from deepin.ocr to org.deepin.ocr
- Replace remaining qDebug/qInfo/qWarning with qC* category macros
- Add MLogger to read dconfig log_rules (appId org.deepin.ocr) and
  apply Qt filter rules dynamically via valueChanged, created before
  Application instance
@add-uos
add-uos force-pushed the feat/ocr-debugsource branch from 30bdbd3 to 12d0fa5 Compare November 2, 2026 14:22
@deepin-ci-robot

Copy link
Copy Markdown

deepin pr auto review

🤖 AI 代码审查报告

总体评分: 82 分 (通过阈值: 70分)

Pass


📊 总体评价

项目 结果
审查结论 代码审查通过
评分详情 本次提交实现了日志分类化(qCDebug/qCWarning/qCInfo 替换 qDebug/qWarning/qInfo)和 DConfig 动态日志规则监听(MLogger),整体架构清晰、注释完善。代码安全维度无漏洞, 性能维度无瓶颈,代码质量良好。语法逻辑维度存在 3 个问题:valueChanged 回调中 setRules 直接替换而非合并导致环境变量规则丢失(一般逻辑错误)、析构函数中 deleteLater 在事件循环停止后无法执行(轻微问题)、appendRules 使用 substring 匹配做去重可能误删规则(轻微问题),合计扣 14 分。综合评分 82 分,审查通过。

🔍 详细分析

1. 语法逻辑 ❌

评价: 存在逻辑缺陷 ❌ 不通过

潜在问题:
✅ 未发现明显问题

建议: ['valueChanged 回调中应先重置 m_rules 为环境变量规则,再调用 appendRules 合并新的 DConfig 规则,最后 setRules,与构造函数保持一致', '析构函数中应使用 delete m_config 并置空指针,而非 deleteLater(),确保在事件循环停止后仍能正确释放', 'appendRules 中应将 m_rules 按行拆分为 QStringList 后使用精确匹配去重,而非 substring contains']


2. 代码质量 ✅

评价: 代码结构清晰,注释完整 ✅ 通过

潜在问题:
✅ 未发现明显问题

建议: ['将', '将三元运算符赋值改为 if/else 语句提升可读性']


3. 代码性能 ✅

评价: 性能良好,资源使用合理 ✅ 通过

潜在问题:
✅ 未发现明显问题

建议: []


4. 代码安全 🔒

评价: 存在0个安全漏洞 ✅ 通过

🔐 发现 0 个安全漏洞

安全漏洞详情:
✅ 未发现安全漏洞

建议: []


💡 改进建议代码示例

// === src/util/logger.cpp 修复示例 ===

// 修复1: valueChanged 回调应保持与构造函数一致的合并语义
// 修复前:
//     connect(m_config, &DConfig::valueChanged, this, [this](const QString &key) {
//         if (key == "log_rules") {
//             setRules(m_config->value(key).toByteArray());
//         }
//     });
// 修复后:
connect(m_config, &DConfig::valueChanged, this, [this](const QString &key) {
    if (key == "log_rules") {
        // 重置为环境变量规则,再合并新的 DConfig 规则,保持与构造函数一致
        m_rules = qgetenv("QT_LOGGING_RULES");
        appendRules(m_config->value(key).toByteArray());
        setRules(m_rules);
    }
});

// 修复2: 析构函数使用 delete 替代 deleteLater
MLogger::~MLogger()
{
#ifdef DTKCORE_CLASS_DConfig
    if (m_config) {
        delete m_config;
        m_config = nullptr;
    }
#endif
}

// 修复3: appendRules 使用精确行匹配替代 substring contains
void MLogger::appendRules(const QString &rules)
{
    QString tmpRules = rules;
    tmpRules = tmpRules.replace(";", "\n");
    auto tmplist = tmpRules.split('\n');
    auto existingRules = m_rules.split('\n');  // 精确行匹配
    for (int i = 0; i < tmplist.count(); i++) {
        if (existingRules.contains(tmplist.at(i))) {
            tmplist.removeAt(i);
            i--;
        }
    }
    if (tmplist.isEmpty())
        return;
    if (m_rules.isEmpty()) {
        m_rules = tmplist.join("\n");
    } else {
        m_rules += "\n" + tmplist.join("\n");
    }
}

// === src/util/logger.h 修复示例 ===
// 修复4: #endif 注释与 include guard 一致
// 修复前: #endif   // LOGGER_H
// 修复后:
#endif   // DEEPIN_OCR_LOGGER_H

本报告由 AI 代码审查工具自动生成

@deepin-ci-robot

Copy link
Copy Markdown

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by: add-uos, lzwind

The full list of commands accepted by this bot can be found here.

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@add-uos

add-uos commented Nov 5, 2026

Copy link
Copy Markdown
Contributor Author

/merge

@deepin-bot
deepin-bot Bot merged commit a39fd61 into linuxdeepin:master Nov 5, 2026
17 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants