-
Notifications
You must be signed in to change notification settings - Fork 2
Logging Systems #15
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Logging Systems #15
Changes from 5 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
d40b4d1
docs: clean up formatting and mkdocs configuration
S1M0N38 e9814a7
chore(dev): add CHANGELOG.md protection to Claude settings
S1M0N38 f7df990
refactor(log): rename params to arguments in logging system
S1M0N38 d7684c9
feat(log): add logging to BalatroClient connection and API calls
S1M0N38 86bcda2
docs: add comprehensive logging systems documentation
S1M0N38 bb5ba49
refactor(log): reduce verbosity of API request logging
S1M0N38 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,119 @@ | ||
| # Logging Systems | ||
|
|
||
| BalatroBot implements three distinct logging systems to support different aspects of development, debugging, and analysis: | ||
|
|
||
| 1. [**JSONL Run Logging**](#jsonl-run-logging) - Records complete game runs for replay and analysis | ||
| 2. [**Python SDK Logging**](#python-sdk-logging) - Future logging capabilities for the Python framework | ||
| 3. [**Mod Logging**](#mod-logging) - Traditional streamodded logging for mod development and debugging | ||
|
|
||
| ## JSONL Run Logging | ||
|
|
||
| The run logging system records complete game runs as JSONL (JSON Lines) files. Each line represents a single game action with its parameters, timestamp, and game state **before** the action. | ||
|
|
||
| The system hooks into these game functions: | ||
|
|
||
| - `start_run`: begins a new game run | ||
| - `skip_or_select_blind`: blind selection actions | ||
| - `play_hand_or_discard`: card play actions | ||
| - `cash_out`: end blind and collect rewards | ||
| - `shop`: shop interactions | ||
| - `go_to_menu`: return to main menu | ||
|
|
||
| The JSONL files are automatically created when: | ||
|
|
||
| - **Playing manually**: Starting a new run through the game interface | ||
| - **Using the API**: Interacting with the game through the TCP API | ||
|
|
||
| Files are saved as: `{mod_path}/runs/YYYYMMDDTHHMMSS.jsonl` | ||
|
|
||
| !!! tip "Replay runs" | ||
|
|
||
| The JSONL logs enable complete run replay for testing and analysis. | ||
|
|
||
| ```python | ||
| state = load_jsonl_run("20250714T145700.jsonl") | ||
| for step in state: | ||
| send_and_receive_api_message( | ||
| tcp_client, | ||
| step["function"]["name"], | ||
| step["function"]["arguments"] | ||
| ) | ||
| ``` | ||
|
|
||
| Examples for runs can be found in the [test suite](https://github.com/S1M0N38/balatrobot/tree/main/tests/runs). | ||
|
|
||
| ### Format Specification | ||
|
|
||
| Each log entry follows this structure: | ||
|
|
||
| ```json | ||
| { | ||
| "timestamp_ms": int, | ||
| "function": { | ||
| "name": "...", | ||
| "arguments": {...} | ||
| }, | ||
| "game_state": { ... } | ||
| } | ||
| ``` | ||
|
|
||
| - **`timestamp_ms`**: Unix timestamp in milliseconds when the action occurred | ||
| - **`function`**: The game function that was called | ||
| - `name`: Function name (e.g., "start_run", "play_hand_or_discard", "cash_out") | ||
| - `arguments`: Arguments passed to the function | ||
| - **`game_state`**: Complete game state **before** the function execution | ||
|
|
||
| ## Python SDK Logging | ||
|
|
||
| The Python SDK (`src/balatrobot/`) implements structured logging for bot development and debugging. The logging system provides visibility into client operations, API communications, and error handling. | ||
|
|
||
| ### What Gets Logged | ||
|
|
||
| The `BalatroClient` logs the following operations: | ||
|
|
||
| - **Connection events**: When connecting to and disconnecting from the game API | ||
| - **API requests**: Function names being called and their completion status | ||
| - **Errors**: Connection failures, socket errors, and invalid API responses | ||
|
|
||
| ### Configuration Example | ||
|
|
||
| The SDK uses Python's built-in `logging` module. Configure it in your bot code before using the client: | ||
|
|
||
| ```python | ||
| import logging | ||
| from balatrobot import BalatroClient | ||
|
|
||
| # Configure logging | ||
| log_format = '%(asctime)s [%(levelname)s] %(name)s: %(message)s' | ||
| console_handler = logging.StreamHandler() | ||
| console_handler.setLevel(logging.INFO) | ||
| file_handler = logging.FileHandler('balatrobot.log') | ||
| file_handler.setLevel(logging.DEBUG) | ||
|
|
||
| logging.basicConfig( | ||
| level=logging.DEBUG, | ||
| format=log_format, | ||
| handlers=[console_handler, file_handler] | ||
| ) | ||
|
|
||
| # Use the client | ||
| with BalatroClient() as client: | ||
| state = client.get_game_state() | ||
| client.start_run(deck="Red Deck", stake=1) | ||
| ``` | ||
|
|
||
| ## Mod Logging | ||
|
|
||
| BalatroBot uses Steamodded's built-in logging system for mod development and debugging. | ||
|
|
||
| - **Traditional logging**: Standard log levels (DEBUG, INFO, WARNING, ERROR) | ||
| - **Development focus**: Primarily for debugging mod functionality | ||
| - **Console output**: Displays in game console and log files | ||
|
|
||
| ```lua | ||
| -- Available through Steamodded | ||
| sendDebugMessage("This is a debug message") | ||
| sendInfoMessage("This is an info message") | ||
| sendWarningMessage("This is a warning message") | ||
| sendErrorMessage("This is an error message") | ||
| ``` |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
| @@ -1,6 +1,7 @@ | ||||||
| """Main BalatroBot client for communicating with the game.""" | ||||||
|
|
||||||
| import json | ||||||
| import logging | ||||||
| import socket | ||||||
| from typing import Any, Literal, Self | ||||||
|
|
||||||
|
|
@@ -18,6 +19,8 @@ | |||||
| StartRunRequest, | ||||||
| ) | ||||||
|
|
||||||
| logger = logging.getLogger(__name__) | ||||||
|
|
||||||
|
|
||||||
| class BalatroClient: | ||||||
| """Client for communicating with the BalatroBot game API.""" | ||||||
|
|
@@ -58,6 +61,7 @@ def connect(self) -> None: | |||||
| if self._connected: | ||||||
| return | ||||||
|
|
||||||
| logger.info(f"Connecting to BalatroBot API at {self.host}:{self.port}") | ||||||
| try: | ||||||
| self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | ||||||
| self._socket.settimeout(self.timeout) | ||||||
|
|
@@ -66,7 +70,11 @@ def connect(self) -> None: | |||||
| ) | ||||||
| self._socket.connect((self.host, self.port)) | ||||||
| self._connected = True | ||||||
| logger.info( | ||||||
| f"Successfully connected to BalatroBot API at {self.host}:{self.port}" | ||||||
| ) | ||||||
| except (socket.error, OSError) as e: | ||||||
| logger.error(f"Failed to connect to {self.host}:{self.port}: {e}") | ||||||
| raise ConnectionFailedError( | ||||||
| f"Failed to connect to {self.host}:{self.port}", | ||||||
| error_code="E008", | ||||||
|
|
@@ -76,6 +84,7 @@ def connect(self) -> None: | |||||
| def disconnect(self) -> None: | ||||||
| """Disconnect from the BalatroBot game API.""" | ||||||
| if self._socket: | ||||||
| logger.info(f"Disconnecting from BalatroBot API at {self.host}:{self.port}") | ||||||
| self._socket.close() | ||||||
| self._socket = None | ||||||
| self._connected = False | ||||||
|
|
@@ -106,6 +115,7 @@ def _send_request(self, name: str, arguments: dict[str, Any]) -> dict[str, Any]: | |||||
|
|
||||||
| # Create and validate request | ||||||
| request = APIRequest(name=name, arguments=arguments) | ||||||
| logger.info(f"Sending API request: {name}") | ||||||
|
|
||||||
| try: | ||||||
| # Send request | ||||||
|
|
@@ -118,17 +128,21 @@ def _send_request(self, name: str, arguments: dict[str, Any]) -> dict[str, Any]: | |||||
|
|
||||||
| # Check for error response | ||||||
| if "error" in response_data: | ||||||
| logger.error(f"API request {name} failed: {response_data.get('error')}") | ||||||
| raise create_exception_from_error_response(response_data) | ||||||
|
|
||||||
| logger.info(f"API request {name} completed successfully") | ||||||
|
||||||
| logger.info(f"API request {name} completed successfully") | |
| logger.debug(f"API request {name} completed successfully") |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
[nitpick] Consider lowering this to a debug-level log (
logger.debug) for routine API messages so INFO-level remains focused on higher-priority events.