# How the nGPT Logging System Records Conversations and Debug Information

> Learn how the nazdridoy nGPT logging system captures conversations and debug info using specialized classes and factories. Understand its detailed recording capabilities.

- Repository: [nazDridoy/ngpt](https://github.com/nazdridoy/ngpt)
- Tags: internals
- Published: 2026-03-07

---

**The nGPT logging system uses two specialized classes—`Logger` for interactive sessions and `GitCommsgLogger` for git commit workflows—to capture every interaction with timestamps, roles, and full command context via factories in [`ngpt/core/log.py`](https://github.com/nazdridoy/ngpt/blob/main/ngpt/core/log.py) and CLI handlers in [`ngpt/cli/handlers/log_handler.py`](https://github.com/nazdridoy/ngpt/blob/main/ngpt/cli/handlers/log_handler.py).**

nGPT is an open-source CLI tool for interacting with AI models. Its logging system is designed to audit conversations and debug issues by writing structured transcripts to disk. The implementation relies on a custom `Logger` class for standard chat modes and a `GitCommsgLogger` wrapper for automated git operations, both exposed through convenience factories.

## Core Architecture of the nGPT Logging System

The system splits responsibilities between two distinct components. Each component handles a specific CLI mode and writes to disk using different formatting strategies.

### The Conversation Logger

The `ngpt.core.log.Logger` class manages standard interactive sessions. It creates plain-text transcripts that include ISO-8601 timestamps, role labels (such as `USER`, `ASSISTANT`, or `SYSTEM`), and the full message content. The class handles file path expansion, directory creation, and automatic temporary file generation when no path is provided.

### The Git Commit Message Logger

When running in `gitcommsg` mode, nGPT uses `GitCommsgLogger`, which wraps Python’s standard `logging` module. This class adds file handlers and formatters to produce structured debug logs. It captures not only the final AI response but also system prompts, user prompts, git diffs, and chunked processing steps. This granularity helps debug commit-message generation failures.

## Creating and Configuring Loggers

nGPT exposes logger creation through factory functions to ensure consistent initialization across the CLI and programmatic use.

### Factory Functions

The primary entry points are `create_logger()` and `create_gitcommsg_logger()` in [`ngpt/core/log.py`](https://github.com/nazdridoy/ngpt/blob/main/ngpt/core/log.py).

```python
from ngpt.core.log import create_logger, create_gitcommsg_logger

# Explicit path for conversation logging

conversation_log = create_logger("/tmp/my_session.log")

# Auto-generated temporary file

temp_log = create_logger()  # Creates /tmp/ngpt-{timestamp}.log

# Git commit message debug logger

git_log = create_gitcommsg_logger()

```

`create_logger()` accepts an optional path argument. When omitted, it generates a timestamped temporary file in the system temp directory. `create_gitcommsg_logger()` instantiates a preconfigured logger named `"gitcommsg"` ready for file handler attachment.

### CLI Integration

The `--log` flag is wired through [`ngpt/cli/handlers/log_handler.py`](https://github.com/nazdridoy/ngpt/blob/main/ngpt/cli/handlers/log_handler.py). The `setup_logger()` function inspects `args.log` to determine whether to use a user-supplied path or a temporary file.

```python
def setup_logger(args):
    if not args.gitcommsg:
        log_path = None if args.log is True else args.log
        logger = create_logger(log_path)
        logger.open()
        print(f"{COLORS['green']}Logging session to: {logger.get_log_path()}{COLORS['reset']}")
        if logger.is_temporary():
            print(f"{COLORS['green']}Created temporary log file.{COLORS['reset']}")
    return logger

```

This handler also detects when the value passed to `--log` is actually a prompt string (e.g., `"Tell me a joke?"`), automatically correcting the argument so the prompt is processed normally while a temporary log file is still created.

## Log File Lifecycle and Format

The `Logger` class in [`ngpt/core/log.py`](https://github.com/nazdridoy/ngpt/blob/main/ngpt/core/log.py) manages the complete lifecycle of a session log, from header generation to final closure.

### Opening and Header Generation

Calling `logger.open()` (lines 49-86 in [`ngpt/core/log.py`](https://github.com/nazdridoy/ngpt/blob/main/ngpt/core/log.py)) expands the tilde character (`~`), creates missing directories, and falls back to a temporary file if the specified path is invalid. It then writes a header containing the start timestamp, the full command line, and the absolute log file path:

```

--- nGPT Session Log ---
Started at: 2024-10-12 14:23:40
Command: ngpt -i --log conversation.log
Log file: /tmp/ngpt-20241012-142340.log

```

### Writing Messages

The core `log(role, content)` method (lines 27-45) records each interaction with an ISO-8601 timestamp and a role prefix. Convenience methods `info()`, `debug()`, `warning()`, and `error()` proxy to `log()` with appropriate level tags.

```python
logger.log("USER", "Explain the concept of recursion.")
logger.info("Session started")
logger.error("Connection timeout")

```

A typical transcript appears as:

```

2024-10-12 14:23:45: USER: Tell me a joke?
2024-10-12 14:23:46: ASSISTANT: Why did the programmer quit his job? Because he didn't get arrays.

```

### Closing and Context Managers

The `close()` method (lines 16-25) appends a final timestamp and closes the file handle. The class supports context-manager protocol via `__enter__` and `__exit__` (lines 40-48), ensuring resources are released even if exceptions occur.

```python
from ngpt.core.log import Logger

with Logger() as log:
    log.info("Session started")
    log.log("USER", "Analyze this data.")
    # AI interaction happens here

    log.log("ASSISTANT", "Here is the analysis...")

# File automatically closed with footer timestamp

```

## GitCommsg-Specific Debug Logging

When `--gitcommsg` is active, `GitCommsgLogger.setup()` (lines 10-42 in [`ngpt/core/log.py`](https://github.com/nazdridoy/ngpt/blob/main/ngpt/core/log.py)) configures a standard `logging.Logger` with a `FileHandler`. It logs the mode start and full CLI command immediately upon initialization.

### Structured Helper Methods

`GitCommsgLogger` provides specialized methods for logging structured data:

- **`log_prompt(level, system_prompt, user_prompt)`**: Logs the complete AI request including both system and user components.
- **`log_response(level, response)`**: Records the raw AI response text.
- **`log_diff(level, diff_content)`**: Captures the git diff provided as context for commit message generation.
- **`log_content(level, description, content)`**: Writes arbitrary multi-line content via a temporary file to ensure clean line-by-line logging.
- **`log_chunks()` and `log_template()`**: Log intermediate processing steps for chunked diff handling.

All helpers ultimately call the underlying `logging.Logger` methods (`debug`, `info`, `warning`, `error`), producing output like:

```

2024-10-12 14:23:45,123 - INFO - GitCommitMsg mode started
2024-10-12 14:23:45,124 - INFO - Command: ngpt --gitcommsg --log commit.log
2024-10-12 14:23:45,200 - DEBUG - AI Request:
2024-10-12 14:23:45,201 - DEBUG - ===== BEGIN SYSTEM_PROMPT: ...

```

## Summary

- The nGPT logging system separates concerns between `Logger` for conversational transcripts and `GitCommsgLogger` for debug-heavy git workflows.
- `create_logger()` and `create_gitcommsg_logger()` in [`ngpt/core/log.py`](https://github.com/nazdridoy/ngpt/blob/main/ngpt/core/log.py) provide factory-based instantiation.
- The CLI handler in [`ngpt/cli/handlers/log_handler.py`](https://github.com/nazdridoy/ngpt/blob/main/ngpt/cli/handlers/log_handler.py) manages `--log` flag integration and temporary file creation.
- Conversation logs use ISO-8601 timestamps and role prefixes, while git logs use standard Python logging formats with detailed debug context.
- Both loggers support context-manager usage for safe resource cleanup.

## Frequently Asked Questions

### How do I enable conversation logging in nGPT?

Pass the `--log` flag followed by a filename, or use `--log` alone to create a timestamped temporary file. For example, `ngpt -i --log chat.log` records an interactive session, while `ngpt -i --log` automatically generates a file in `/tmp/` (or `%TEMP%` on Windows).

### What is the difference between Logger and GitCommsgLogger?

`Logger` writes plain-text transcripts with custom formatting suitable for reading chat history, while `GitCommsgLogger` wraps Python’s standard `logging` module to produce structured debug output including diffs, prompts, and chunked processing details for the `gitcommsg` mode.

### Where are temporary log files stored?

When `create_logger()` is called without a path argument, or when `--log` is passed without a file value, the system creates a temporary file in the operating system’s default temp directory using the pattern `ngpt-{timestamp}.log`.

### Can I use the logger programmatically outside the CLI?

Yes. Import `Logger` from `ngpt.core.log` and instantiate it directly, or use `create_logger()` with an explicit path. The class supports context-manager syntax (`with Logger() as log:`) for automatic open/close handling, making it suitable for scripting and testing environments.