# ChatMCP Logging Mechanism: How It Works and Where Logs Are Stored

> Explore the ChatMCP logging mechanism using Dart logging and a custom file logger. Discover where daily log files are stored in application data directories.

- Repository: [刀刀/chatmcp](https://github.com/daodao97/chatmcp)
- Tags: how-to-guide
- Published: 2026-02-28

---

**ChatMCP uses the Dart `logging` package combined with a custom file logger to capture application events, storing daily log files in platform-specific application data directories.**

The ChatMCP application implements a hierarchical logging system that routes messages to both the console (during development) and rotating log files (in production). Understanding this ChatMCP logging mechanism is essential for debugging issues, monitoring application health, and exporting diagnostic data across different operating systems.

## How ChatMCP Initializes the Logging System

### The Logger Entry Point (`lib/logger.dart`)

The logging infrastructure begins in `lib/logger.dart` with the `initializeLogger()` function. This method performs four critical setup operations:

1. **File Logger Initialization** – Invokes `FileLogger.initLogFile()` to prepare the on-disk storage backend.
2. **Root Logger Configuration** – Sets `Logger.root.level` to capture all log levels (from `FINEST` to `SHOUT`).
3. **Record Processing** – Subscribes to `Logger.root.onRecord` to handle every `LogRecord` emitted during execution.
4. **Output Routing** – For each record, the system:
   - Parses the stack trace to determine the source file and line number.
   - Applies level-specific ANSI color formatting for console visibility.
   - Writes to `stdout` in debug builds.
   - Persists to the log file via `FileLogger.writeToFile()` in release builds.

## File-Based Logging Implementation

### Platform-Specific File Logger (`lib/file_logger_io.dart`)

The actual file I/O implementation resides in `lib/file_logger_io.dart`, which is conditionally imported for Flutter IO platforms (mobile and desktop). This module handles log rotation, directory management, and cleanup policies.

**Directory Resolution**

The logger determines the storage location by calling `StorageManager.getAppDataDirectory()` from `lib/utils/storage_manager.dart`. This utility returns platform-specific application data directories, ensuring logs are stored in appropriate system locations rather than temporary folders.

**Daily Log Rotation**

Once the base directory is established, the file logger:

1. Creates a `logs` subdirectory if it does not exist.
2. Generates a daily log file named `app_YYYY-M-D.log` (for example, `app_2026-2-28.log`).
3. Opens the file in **append** mode to preserve historical entries across application restarts.
4. Exposes `writeToFile(message)` to append formatted log lines atomically.

**Automatic Cleanup**

The system includes a `cleanupOldLogs()` routine that removes log files older than **3 days** (configurable). This prevents unbounded disk usage on long-running installations while retaining recent diagnostic history.

## Where ChatMCP Stores Log Files

The exact log file location varies by operating system, as determined by `StorageManager.getAppDataDirectory()`:

| Platform | Directory | Example Log Path |
|----------|-----------|------------------|
| **Android / iOS** | `<appDocumentsDir>/ChatMcp` | `/data/user/0/com.example.app/files/ChatMcp/logs/app_2026-2-28.log` |
| **Linux** | `$XDG_DATA_HOME/ChatMcp` (or `$HOME/.local/share/ChatMcp`) | `$HOME/.local/share/ChatMcp/logs/app_2026-2-28.log` |
| **Windows** | `%APPDATA%\ChatMcp` | `C:\Users\Alice\AppData\Roaming\ChatMcp\logs\app_2026-2-28.log` |
| **macOS** | `$HOME/Library/Application Support/ChatMcp` | `/Users/Alice/Library/Application Support/ChatMcp/logs/app_2026-2-28.log` |
| **Other platforms** | `path_provider` temporary directory | `<tempDir>/ChatMcp/logs/app_2026-2-28.log` |

The `logs` folder is created automatically on first startup, and old files are pruned without user intervention.

## Working with ChatMCP Logs (Code Examples)

### Initializing the Logger

Call `initializeLogger()` early in the application lifecycle, typically within `main()`:

```dart
import 'package:chatmcp/logger.dart';

Future<void> main() async {
  // Initialise the logger before any other code runs
  initializeLogger();

  // Example log statements
  Logger('MyApp').info('Application started');
  Logger('MyApp').warning('Low memory warning');
  Logger('MyApp').severe('Unexpected error occurred');
}

```

*Source:* `lib/logger.dart` (lines 34‑40).

### Writing Custom Log Entries

Any class can emit logs by instantiating a named `Logger`:

```dart
import 'package:logging/logging.dart';

final _log = Logger('NetworkSyncService');

void syncData() {
  _log.fine('Starting data sync...');
  // ... sync logic ...
  _log.info('Data sync completed successfully');
}

```

The `Logger` instance automatically routes messages through the root listener established in `initializeLogger()`.

### Accessing Log Files Programmatically

To read or export logs, resolve the file path using the same logic as the internal logger:

```dart
import 'package:chatmcp/utils/storage_manager.dart';
import 'package:path/path.dart' as p;

Future<String> getCurrentLogPath() async {
  final appDir = await StorageManager.getAppDataDirectory();
  final now = DateTime.now();
  final fileName = 'app_${now.year}-${now.month}-${now.day}.log';
  return p.join(appDir, 'logs', fileName);
}

```

*This mirrors the filename logic in `lib/file_logger_io.dart` (lines 24‑30).*

## Key Files in the ChatMCP Logging System

| File | Role |
|------|------|
| `lib/logger.dart` | Sets up the `logging` package, formats console output, forwards messages to the file logger. |
| `lib/file_logger.dart` | Export-conditional stub that selects the correct implementation (`file_logger_io.dart` on mobile/desktop). |
| `lib/file_logger_io.dart` | Implements the file-based logger: creates the log directory, rotates daily files, cleans up old logs. |
| `lib/utils/storage_manager.dart` | Determines the platform-specific application data directory used by the file logger. |
| [`pubspec.yaml`](https://github.com/daodao97/chatmcp/blob/main/pubspec.yaml) | Declares the `logging` dependency (`logging: ^1.2.0`). |

These files together constitute the full logging stack used by ChatMCP.

## Summary

- ChatMCP uses the Dart **`logging`** package (version ^1.2.0) for hierarchical log management.
- Log initialization happens in `lib/logger.dart` via `initializeLogger()`, which configures root-level capture and dual output (console + file).
- File persistence is handled by `lib/file_logger_io.dart`, creating daily rotating files named `app_YYYY-M-D.log`.
- Logs are stored in platform-specific application data directories under a `logs` subdirectory (e.g., `%APPDATA%\ChatMcp\logs` on Windows).
- Automatic cleanup removes log files older than three days to manage disk usage.

## Frequently Asked Questions

### What logging package does ChatMCP use?

ChatMCP uses the standard Dart **`logging`** package (version ^1.2.0 as declared in [`pubspec.yaml`](https://github.com/daodao97/chatmcp/blob/main/pubspec.yaml)). This provides a hierarchical logging framework where loggers are organized by name, allowing fine-grained control over log levels and output destinations.

### Where are ChatMCP log files stored on Windows?

On Windows, ChatMCP stores logs in `%APPDATA%\ChatMcp\logs\` (typically resolving to `C:\Users\<Username>\AppData\Roaming\ChatMcp\logs\`). The current day's log file follows the naming convention `app_YYYY-M-D.log` (for example, `app_2026-2-28.log`).

### How long does ChatMCP keep log files?

By default, ChatMCP automatically cleans up log files older than **three days**. This retention policy is implemented in `lib/file_logger_io.dart` via the `cleanupOldLogs()` method, which runs periodically to prevent unbounded disk usage while preserving recent diagnostic history.

### Can I access ChatMCP logs programmatically?

Yes. You can resolve the current log file path by importing `StorageManager` from `lib/utils/storage_manager.dart` and constructing the path using `p.join(appDir, 'logs', 'app_${now.year}-${now.month}-${now.day}.log')`. This allows you to read, export, or upload logs for remote debugging purposes.