Skip to content

feat: implement SimplePrintLogger for better debugging#176

Merged
conventoangelo merged 5 commits intomainfrom
feat/better-logging-timestamp
Feb 28, 2026
Merged

feat: implement SimplePrintLogger for better debugging#176
conventoangelo merged 5 commits intomainfrom
feat/better-logging-timestamp

Conversation

@conventoangelo
Copy link
Owner

@conventoangelo conventoangelo commented Feb 28, 2026

Summary by CodeRabbit

  • New Features

    • Added per-hotkey enable/disable controls so individual hotkeys can be toggled independently.
  • Chores

    • Replaced ad-hoc prints with a unified logging system across the app for improved diagnostics and consistent error/warning reporting.

@coderabbitai
Copy link

coderabbitai bot commented Feb 28, 2026

Warning

Rate limit exceeded

@conventoangelo has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 14 minutes and 34 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 895d672 and 9190542.

📒 Files selected for processing (1)
  • lib/utils/logger.dart
📝 Walkthrough

Walkthrough

Adds a SimplePrintLogger utility and replaces ad-hoc prints with structured logging across multiple services; expands HotKeyService setupHotKeys signature to include per-hotkey enable flags and a master switch; KanataService connection flow gains reconnection scheduling and explicit reconnect enabling.

Changes

Cohort / File(s) Summary
Logger Utility
lib/utils/logger.dart
New SimplePrintLogger class with debug, info, warning, error methods, timestamped output, and kDebugMode gating.
App & UI orchestration
lib/app.dart
Replaced debug prints with logger usage in preference/window error paths; added logger import and instance.
Configuration services
lib/services/config_service.dart, lib/services/configuration_loader.dart
Introduced local _log instances; replaced debugPrint/print with _log.error / _log.warning for config and loader error paths.
HotKey service
lib/services/hotkey_service.dart
Added _log; expanded setupHotKeys(...) signature with per-hotkey enable* booleans and hotKeysEnabled; conditional registration per-flag and master disable behavior; replaced prints with _log.debug.
Kanata service
lib/services/kanata_service.dart
Added _log; replaced prints with log calls across connection lifecycle; set _reconnectEnabled = true in connect(); added _scheduleReconnect() to manage reconnection timing.
Key & method handlers
lib/services/key_event_service.dart, lib/services/method_call_handler.dart
Added _log instances; replaced debug prints with _log.debug/_log.warning/_log.error and improved key/event logging messages.
Startup & hooks
lib/services/startup_service.dart, lib/utils/hooks.dart
Introduced _log; replaced catch-block prints with _log.error and error logging in hook registration paths.

Sequence Diagram(s)

sequenceDiagram
    participant App
    participant KanataService
    participant Socket
    participant ReconnectScheduler
    participant Logger

    App->>KanataService: connect()
    KanataService->>Logger: _log.info('connecting')
    KanataService->>Socket: open connection
    alt connection success
        Socket-->>KanataService: onConnected
        KanataService->>Logger: _log.info('connected')
        KanataService->>ReconnectScheduler: cancel pending reconnects
    else connection failure / socket error
        Socket-->>KanataService: onError / onDisconnected
        KanataService->>Logger: _log.error/_log.warning(...)
        KanataService->>ReconnectScheduler: _scheduleReconnect()
        ReconnectScheduler->>KanataService: trigger reconnect after delay
        KanataService->>Logger: _log.debug('reconnecting')
        KanataService->>Socket: reopen connection
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

Poem

🐇
I hop and whisper timestamps bright,
From scattered prints to logs at night.
Hotkeys tuned and sockets mend,
Reconnects planned around each bend,
A rabbit cheers — observability takes flight!

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main change: implementing a new SimplePrintLogger utility for structured logging with timestamps, which is the primary focus of this pull request across all modified files.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/better-logging-timestamp

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (4)
lib/services/startup_service.dart (1)

6-8: Minor: Missing blank line between doc comments.

The doc comment for the logger instance and the doc comment for the method run together without a blank line separator, which is slightly inconsistent with other files in this PR.

♻️ Add blank line for consistency
   /// Logger instance for this service
   final _log = SimplePrintLogger('StartupService');
+
   /// Enables or disables the application from launching at system startup
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/services/startup_service.dart` around lines 6 - 8, The two doc comments
run together for the logger and the following member; insert a single blank line
between the doc comment above the field "_log" (type SimplePrintLogger in class
StartupService) and the next doc comment so the logger doc and the "Enables or
disables the application..." doc are separated for consistency with other files.
lib/services/hotkey_service.dart (1)

2-2: Potentially unused import.

The flutter/foundation.dart import appears to be unused in this file. The kDebugMode check is handled internally by SimplePrintLogger.

♻️ Remove unused import
 import 'package:hotkey_manager/hotkey_manager.dart';
-import 'package:flutter/foundation.dart';
 import '../utils/logger.dart';
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/services/hotkey_service.dart` at line 2, Remove the unused import of
flutter/foundation.dart: delete the import line and ensure no direct references
to kDebugMode remain in HotkeyService; rely on SimplePrintLogger's internal
kDebugMode handling, then run the analyzer/format to confirm no unused-import
warnings.
lib/services/config_service.dart (1)

120-122: Consider reducing log level for missing customFont.

When customFont is not defined in the config file, this is likely an expected condition (user hasn't configured a custom font yet) rather than a warning-worthy situation. Using warning level here may create noise in debug logs.

♻️ Use debug level or remove the log
    if (config.customFont == null) {
-     _log.warning(
-         'Cannot get custom font: customFont is not defined in the config file');
+     _log.debug('customFont not defined in config file');
      return null;
    }

Alternatively, simply remove the log since returning null is a valid and expected response.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/services/config_service.dart` around lines 120 - 122, This warning-level
log for a missing customFont is noisy; replace the _log.warning call with a
lower-severity debug/fine log (e.g., _log.fine(...)) or remove the log entirely
since returning null is an expected outcome when customFont is absent; update
the call to _log.fine('customFont not defined in config') (or delete the log
line) in the method that returns null for customFont (the location calling
_log.warning and returning null) so the behavior remains the same but without a
warning-level entry.
lib/utils/logger.dart (1)

26-27: Consider consistent formatting for error details.

The Error: and StackTrace: lines are printed without timestamps or logger names, which may make it harder to correlate them with the main log message when multiple services are logging concurrently.

♻️ Optional: Add context to error/stackTrace lines
  void warning(String message, {Object? error, StackTrace? stackTrace}) {
    if (kDebugMode) {
      print('[${_timestamp()}] [$name] ⚠️ $message');
-      if (error != null) print('Error: $error');
-      if (stackTrace != null) print('StackTrace: $stackTrace');
+      if (error != null) print('[${_timestamp()}] [$name]   Error: $error');
+      if (stackTrace != null) print('[${_timestamp()}] [$name]   StackTrace: $stackTrace');
    }
  }

  void error(String message, {Object? error, StackTrace? stackTrace}) {
    if (kDebugMode) {
      print('[${_timestamp()}] [$name] ❌ $message');
-      if (error != null) print('Error: $error');
-      if (stackTrace != null) print('StackTrace: $stackTrace');
+      if (error != null) print('[${_timestamp()}] [$name]   Error: $error');
+      if (stackTrace != null) print('[${_timestamp()}] [$name]   StackTrace: $stackTrace');
    }
  }

Also applies to: 34-35

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/utils/logger.dart` around lines 26 - 27, The error/stackTrace prints
currently output raw lines "Error: $error" and "StackTrace: $stackTrace" which
lack the timestamp/logger context; change these branches (the null-checks that
print those lines) to emit the same formatted log prefix as the main message
(include timestamp, logger name and level) instead of plain prints—e.g., reuse
the existing timestamp/label formatter used elsewhere in this file and prepend
it to the "Error:" and "StackTrace:" text so they can be correlated with the
primary log entry.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@lib/utils/hooks.dart`:
- Around line 68-69: The critical-error logging currently uses _log.error
(SimplePrintLogger) right before calling exit(1), which is gated by kDebugMode
and will be invisible in release builds; update those places (the _log.error +
exit(1) occurrences and the other instances referenced) to either call
print(...) immediately before exit(1) or use a non-debug-gated logger so the
message is always emitted in production; locate the calls by searching for
_log.error followed by exit(1) in hooks.dart and replace or supplement them with
an unconditional print or a production-capable logger call.

---

Nitpick comments:
In `@lib/services/config_service.dart`:
- Around line 120-122: This warning-level log for a missing customFont is noisy;
replace the _log.warning call with a lower-severity debug/fine log (e.g.,
_log.fine(...)) or remove the log entirely since returning null is an expected
outcome when customFont is absent; update the call to _log.fine('customFont not
defined in config') (or delete the log line) in the method that returns null for
customFont (the location calling _log.warning and returning null) so the
behavior remains the same but without a warning-level entry.

In `@lib/services/hotkey_service.dart`:
- Line 2: Remove the unused import of flutter/foundation.dart: delete the import
line and ensure no direct references to kDebugMode remain in HotkeyService; rely
on SimplePrintLogger's internal kDebugMode handling, then run the
analyzer/format to confirm no unused-import warnings.

In `@lib/services/startup_service.dart`:
- Around line 6-8: The two doc comments run together for the logger and the
following member; insert a single blank line between the doc comment above the
field "_log" (type SimplePrintLogger in class StartupService) and the next doc
comment so the logger doc and the "Enables or disables the application..." doc
are separated for consistency with other files.

In `@lib/utils/logger.dart`:
- Around line 26-27: The error/stackTrace prints currently output raw lines
"Error: $error" and "StackTrace: $stackTrace" which lack the timestamp/logger
context; change these branches (the null-checks that print those lines) to emit
the same formatted log prefix as the main message (include timestamp, logger
name and level) instead of plain prints—e.g., reuse the existing timestamp/label
formatter used elsewhere in this file and prepend it to the "Error:" and
"StackTrace:" text so they can be correlated with the primary log entry.

ℹ️ Review info

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 902bf48 and 8c0b86d.

📒 Files selected for processing (10)
  • lib/app.dart
  • lib/services/config_service.dart
  • lib/services/configuration_loader.dart
  • lib/services/hotkey_service.dart
  • lib/services/kanata_service.dart
  • lib/services/key_event_service.dart
  • lib/services/method_call_handler.dart
  • lib/services/startup_service.dart
  • lib/utils/hooks.dart
  • lib/utils/logger.dart

Comment on lines +68 to 69
_log.error('Failed to register session notification');
exit(1);
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Critical errors logged only in debug mode.

These _log.error calls are followed by exit(1), indicating critical failures that terminate the application. However, SimplePrintLogger only outputs in kDebugMode, meaning these error messages won't appear in release builds before the app exits.

Consider using print() directly (or a logger that isn't gated by kDebugMode) for truly critical errors that cause immediate termination, to aid in diagnosing production issues.

💡 Example: Use print for critical errors
  if (result == 0) {
-   _log.error('Failed to register session notification');
+   // Use print directly for critical errors that cause exit
+   print('[Hooks] ❌ Failed to register session notification');
    exit(1);
  }

Also applies to: 100-102, 117-119

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/utils/hooks.dart` around lines 68 - 69, The critical-error logging
currently uses _log.error (SimplePrintLogger) right before calling exit(1),
which is gated by kDebugMode and will be invisible in release builds; update
those places (the _log.error + exit(1) occurrences and the other instances
referenced) to either call print(...) immediately before exit(1) or use a
non-debug-gated logger so the message is always emitted in production; locate
the calls by searching for _log.error followed by exit(1) in hooks.dart and
replace or supplement them with an unconditional print or a production-capable
logger call.

@codecov-commenter
Copy link

⚠️ Please install the 'codecov app svg image' to ensure uploads and comments are reliably processed by Codecov.

Codecov Report

❌ Patch coverage is 4.00000% with 24 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
lib/utils/logger.dart 7.14% 13 Missing ⚠️
lib/services/kanata_service.dart 0.00% 7 Missing ⚠️
lib/services/config_service.dart 0.00% 3 Missing ⚠️
lib/services/startup_service.dart 0.00% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

@conventoangelo conventoangelo merged commit 26650b8 into main Feb 28, 2026
5 checks passed
@conventoangelo conventoangelo deleted the feat/better-logging-timestamp branch February 28, 2026 05:52
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.

2 participants