docs: update README and ccStructLog documentation

This commit is contained in:
2025-11-21 14:56:25 +08:00
parent cf7ddefc2e
commit 94f0de4c90
2 changed files with 138 additions and 85 deletions

View File

@@ -5,6 +5,7 @@ A collection of advanced utilities and libraries for Minecraft ComputerCraft, wr
## Features ## Features
### 1. Access Control System ### 1. Access Control System
A comprehensive system for managing player access to a specific area. It uses a `playerDetector` to monitor for players in range and a `chatBox` to interact with them and administrators. A comprehensive system for managing player access to a specific area. It uses a `playerDetector` to monitor for players in range and a `chatBox` to interact with them and administrators.
- **Player Detection:** Monitors a configurable range for players. - **Player Detection:** Monitors a configurable range for players.
@@ -15,6 +16,7 @@ A comprehensive system for managing player access to a specific area. It uses a
- **Logging:** Detailed logging of events, viewable with the included `logviewer` program. - **Logging:** Detailed logging of events, viewable with the included `logviewer` program.
### 2. AutoCraft System ### 2. AutoCraft System
An automated crafting solution designed to work with the Create mod's packaged recipes. An automated crafting solution designed to work with the Create mod's packaged recipes.
- **Automated Crafting:** Detects cardboard packages in a chest and automatically crafts the recipes they contain. - **Automated Crafting:** Detects cardboard packages in a chest and automatically crafts the recipes they contain.
@@ -22,6 +24,7 @@ An automated crafting solution designed to work with the Create mod's packaged r
- **Inventory Management:** Manages pulling ingredients from a source inventory and pushing crafted items to a destination. - **Inventory Management:** Manages pulling ingredients from a source inventory and pushing crafted items to a destination.
### 3. ccTUI Framework ### 3. ccTUI Framework
A declarative, reactive TUI (Terminal User Interface) framework inspired by [SolidJS](https://www.solidjs.com/) for building complex and interactive interfaces in ComputerCraft. A declarative, reactive TUI (Terminal User Interface) framework inspired by [SolidJS](https://www.solidjs.com/) for building complex and interactive interfaces in ComputerCraft.
- **Declarative Syntax:** Build UIs with simple, composable functions like `div`, `label`, `button`, and `input`. - **Declarative Syntax:** Build UIs with simple, composable functions like `div`, `label`, `button`, and `input`.
@@ -31,6 +34,7 @@ A declarative, reactive TUI (Terminal User Interface) framework inspired by [Sol
- **Component-Based:** Structure your UI into reusable components. See `src/tuiExample/main.ts` for a demo. - **Component-Based:** Structure your UI into reusable components. See `src/tuiExample/main.ts` for a demo.
### 4. ccCLI Framework ### 4. ccCLI Framework
A lightweight, functional-style framework for building command-line interfaces (CLIs) within CC:Tweaked. It supports nested commands, arguments, options, and automatic help generation. See the [ccCLI Documentation](./docs/ccCLI.md) for more details. A lightweight, functional-style framework for building command-line interfaces (CLIs) within CC:Tweaked. It supports nested commands, arguments, options, and automatic help generation. See the [ccCLI Documentation](./docs/ccCLI.md) for more details.
- **Declarative API:** Define commands, arguments, and options using a simple, object-based structure. - **Declarative API:** Define commands, arguments, and options using a simple, object-based structure.
@@ -40,6 +44,7 @@ A lightweight, functional-style framework for building command-line interfaces (
- **Type-Safe:** Built with TypeScript for robust development. - **Type-Safe:** Built with TypeScript for robust development.
### 5. Core Libraries ### 5. Core Libraries
- **`ChatManager`:** A powerful manager for `chatBox` peripherals that handles message queuing, cooldowns, and asynchronous sending/receiving. See the [ChatManager Documentation](./docs/ChatManager.md) for more details. - **`ChatManager`:** A powerful manager for `chatBox` peripherals that handles message queuing, cooldowns, and asynchronous sending/receiving. See the [ChatManager Documentation](./docs/ChatManager.md) for more details.
- **`ccStructLog`:** A modern, structured logging library inspired by Python's `structlog`. It provides a flexible, extensible framework based on processors, renderers, and streams, designed for CC:Tweaked. See the [ccStructLog Documentation](./docs/ccStructLog.md) for more details. - **`ccStructLog`:** A modern, structured logging library inspired by Python's `structlog`. It provides a flexible, extensible framework based on processors, renderers, and streams, designed for CC:Tweaked. See the [ccStructLog Documentation](./docs/ccStructLog.md) for more details.
- **`PeripheralManager`:** A utility for easily finding and requiring peripherals by name or type. - **`PeripheralManager`:** A utility for easily finding and requiring peripherals by name or type.
@@ -54,6 +59,7 @@ A lightweight, functional-style framework for building command-line interfaces (
## Setup & Installation ## Setup & Installation
1. **Clone the repository:** 1. **Clone the repository:**
```sh ```sh
git clone <repository-url> git clone <repository-url>
cd cc-utils cd cc-utils
@@ -69,6 +75,7 @@ A lightweight, functional-style framework for building command-line interfaces (
This project uses `just` to manage build tasks. The compiled Lua files will be placed in the `build/` directory. This project uses `just` to manage build tasks. The compiled Lua files will be placed in the `build/` directory.
- **Build all modules:** - **Build all modules:**
```sh ```sh
just build just build
``` ```
@@ -105,44 +112,30 @@ To deploy the built programs to your in-game computer, you need to configure the
### Access Control ### Access Control
- **Start the system:** - **Start the system:**
```sh ```sh
accesscontrol start accesscontrol start
``` ```
- **Open the configuration TUI:** - **Open the configuration TUI:**
```sh ```sh
accesscontrol config accesscontrol config
``` ```
Alternatively, press `c` while the main program is running.
- **View logs:** Alternatively, press `c` while the main program is running.
```sh
logviewer accesscontrol.log
```
- **Admin Commands (in-game chat):** - **Admin Commands (in-game chat):**
``` ```
@AC /help @AC help
@AC /add user Notch @AC add user Notch
@AC /list @AC list
``` ```
### AutoCraft ### AutoCraft
The autocraft program runs in the background. Simply run it on a turtle with the correct peripheral setup (see `src/autocraft/main.ts`). It will automatically process packages placed in the designated chest. The autocraft program runs in the background. Simply run it on a turtle with the correct peripheral setup (see `src/autocraft/main.ts`). It will automatically process packages placed in the designated chest.
```sh
autocraft
```
### TUI Example
Run the example program to see a demonstration of the `ccTUI` framework.
```sh
tuiExample
```
## Development ## Development
- **Lint and format the code:** - **Lint and format the code:**

View File

@@ -11,16 +11,37 @@ A modern, structured logging library for CC:Tweaked, inspired by Python's struct
## Quick Start ## Quick Start
```typescript The easiest way to get started is to create a `Logger` instance and configure it with processors, a renderer, and streams.
import { createDevLogger } from "@/lib/ccStructLog";
// Create a development logger Here's a simple example of a logger that prints colored, human-readable messages to the console:
const logger = createDevLogger();
```typescript
import {
Logger,
LogLevel,
processor,
textRenderer,
ConsoleStream,
} from "@/lib/ccStructLog";
// Create a logger
const logger = new Logger({
processors: [
processor.addTimestamp({ format: "%T" }), // Add HH:MM:SS timestamp
processor.filterByLevel(LogLevel.Info), // Log Info and higher
processor.addSource("MyApp"),
],
renderer: textRenderer,
streams: [new ConsoleStream()],
});
// Log messages with context // Log messages with context
logger.info("Server started", { port: 8080, version: "1.0.0" }); logger.info("Server started", { port: 8080, version: "1.0.0" });
logger.warn("Low disk space", { available: 1024, threshold: 2048 }); logger.warn("Low disk space", { available: 1024, threshold: 2048 });
logger.error("Connection failed", { host: "example.com", retries: 3 }); logger.error("Connection failed", { host: "example.com", retries: 3 });
// This debug message will be filtered out by `filterByLevel`
logger.debug("This is a debug message.");
``` ```
## Core Concepts ## Core Concepts
@@ -46,48 +67,69 @@ export enum LogLevel {
4. **Render**: The final event is converted to a string by a renderer (e.g., `textRenderer`, `jsonRenderer`). 4. **Render**: The final event is converted to a string by a renderer (e.g., `textRenderer`, `jsonRenderer`).
5. **Output**: The string is sent to one or more streams (e.g., console, file). 5. **Output**: The string is sent to one or more streams (e.g., console, file).
## Pre-configured Loggers ## Common Configurations
### Development Logger ### Development Logger
Optimized for development and debugging with human-readable console output. A typical development logger is configured for human-readable console output with timestamps and colors.
```typescript ```typescript
import { createDevLogger, LogLevel } from "@/lib/ccStructLog"; import {
Logger,
processor,
textRenderer,
ConsoleStream,
} from "@/lib/ccStructLog";
const logger = createDevLogger({ const devLogger = new Logger({
source: "MyApp", processors: [
includeComputerId: true, processor.addTimestamp({ format: "%F %T" }), // YYYY-MM-DD HH:MM:SS
processor.addSource("DevApp"),
processor.addComputerId(),
],
renderer: textRenderer,
streams: [new ConsoleStream()],
}); });
logger.debug("This is a debug message."); devLogger.debug("This is a debug message.", { user: "dev" });
``` ```
### Production Logger ### Production Logger
Optimized for production with JSON-formatted file output and daily rotation. A production logger is often configured to write machine-readable JSON logs to a file with daily rotation.
```typescript
import { createProdLogger, DAY } from "@/lib/ccStructLog";
const logger = createProdLogger("app.log", {
source: "MyApp",
rotationInterval: DAY, // Rotate daily
includeConsole: false, // Don't log to console
});
logger.info("Application is running in production.");
```
## Custom Configuration
You can create a logger with a completely custom setup.
```typescript ```typescript
import { import {
Logger, Logger,
LogLevel, LogLevel,
addFullTimestamp, processor,
addComputerId, jsonRenderer,
addSource, FileStream,
DAY,
} from "@/lib/ccStructLog";
const prodLogger = new Logger({
processors: [
processor.addTimestamp(), // Default format is %F %T
processor.filterByLevel(LogLevel.Info),
processor.addSource("ProdApp"),
processor.addComputerId(),
],
renderer: jsonRenderer,
streams: [
new FileStream("app.log", DAY), // Rotate daily
],
});
prodLogger.info("Application is running in production.");
```
## Custom Configuration
You can create a logger with any combination of processors, renderers, and streams.
```typescript
import {
Logger,
processor,
jsonRenderer, jsonRenderer,
FileStream, FileStream,
ConsoleStream, ConsoleStream,
@@ -96,9 +138,9 @@ import {
const logger = new Logger({ const logger = new Logger({
processors: [ processors: [
addFullTimestamp(), processor.addTimestamp(),
addComputerId(), processor.addComputerId(),
addSource("MyApplication"), processor.addSource("MyApplication"),
], ],
renderer: jsonRenderer, renderer: jsonRenderer,
streams: [ streams: [
@@ -112,31 +154,40 @@ logger.info("Custom logger reporting for duty.", { user: "admin" });
## Processors ## Processors
Processors are functions that modify, enrich, or filter log events before they are rendered. Processors are functions that modify, enrich, or filter log events before they are rendered. They are all available under the `processor` namespace.
### Built-in Processors ### Built-in Processors
```typescript ```typescript
import { import { Logger, LogLevel, processor } from "@/lib/ccStructLog";
addTimestamp, // Add structured timestamp
addFormattedTimestamp, // Add HH:MM:SS string
addFullTimestamp, // Add YYYY-MM-DD HH:MM:SS string
filterByLevel, // Filter by minimum level
filterBy, // Filter based on a custom predicate
addSource, // Add source/logger name
addComputerId, // Add computer ID
addComputerLabel, // Add computer label
addStaticFields, // Add static fields to all events
transformField, // Transform a specific field's value
removeFields, // Remove sensitive fields
} from "@/lib/ccStructLog";
// Usage example // Usage example
const logger = new Logger({ const logger = new Logger({
processors: [ processors: [
addTimestamp(), // Adds a timestamp. Format is compatible with os.date().
addSource("MyApp"), // Default: "%F %T" (e.g., "2023-10-27 15:30:00")
filterByLevel(LogLevel.Warn), // Only allow Warn, Error, Fatal processor.addTimestamp({ format: "%T" }), // e.g., "15:30:00"
removeFields(["password", "token"]),
// Filter by minimum level
processor.filterByLevel(LogLevel.Warn), // Only allow Warn, Error, Fatal
// Filter based on a custom predicate
processor.filterBy((event) => event.get("user") === "admin"),
// Add source/logger name
processor.addSource("MyApp"),
// Add computer ID or label
processor.addComputerId(),
processor.addComputerLabel(),
// Add static fields to all events
processor.addStaticFields({ env: "production", version: "1.2.3" }),
// Transform a specific field's value
processor.transformField("user_id", (id) => `user_${id}`),
// Remove sensitive fields
processor.removeFields(["password", "token"]),
], ],
// ... other config // ... other config
}); });
@@ -172,10 +223,10 @@ Renderers convert the final `LogEvent` object into a string.
import { textRenderer, jsonRenderer } from "@/lib/ccStructLog"; import { textRenderer, jsonRenderer } from "@/lib/ccStructLog";
// textRenderer: Human-readable, colored output for the console. // textRenderer: Human-readable, colored output for the console.
// Example: 15:30:45 [INFO] Message key=value // Example: [15:30:45] [INFO] Message key=value
// jsonRenderer: Machine-readable JSON output. // jsonRenderer: Machine-readable JSON output.
// Example: {"level":"info","message":"Message","key":"value","timestamp":"..."} // Example: {"level":2,"message":"Message","key":"value","timestamp":"15:30:45"}
``` ```
## Streams ## Streams
@@ -185,12 +236,14 @@ Streams handle the final output destination. You can use multiple streams to sen
### Built-in Streams ### Built-in Streams
```typescript ```typescript
import { import {
ConsoleStream, // Output to CC:Tweaked terminal with colors ConsoleStream,
FileStream, // Output to file with rotation support FileStream,
BufferStream, // Store in an in-memory buffer BufferStream,
NullStream, // Discard all output NullStream,
ConditionalStream,
LogLevel,
DAY,
} from "@/lib/ccStructLog"; } from "@/lib/ccStructLog";
import { ConditionalStream } from "@/lib/ccStructLog/streams"; // Note direct import
// File stream with daily rotation // File stream with daily rotation
const fileStream = new FileStream("app.log", DAY); const fileStream = new FileStream("app.log", DAY);
@@ -207,7 +260,7 @@ const errorStream = new ConditionalStream(
## File Rotation ## File Rotation
`FileStream` supports automatic file rotation based on time intervals. `FileStream` supports automatic file rotation based on time intervals. The rotation interval is specified in seconds as the second argument to the constructor.
```typescript ```typescript
import { FileStream, HOUR, DAY, WEEK } from "@/lib/ccStructLog"; import { FileStream, HOUR, DAY, WEEK } from "@/lib/ccStructLog";
@@ -221,7 +274,7 @@ const dailyLog = new FileStream("app_daily.log", DAY);
// Rotate weekly // Rotate weekly
const weeklyLog = new FileStream("app_weekly.log", WEEK); const weeklyLog = new FileStream("app_weekly.log", WEEK);
// No rotation // No rotation (pass 0 or undefined)
const permanentLog = new FileStream("permanent.log", 0); const permanentLog = new FileStream("permanent.log", 0);
``` ```
@@ -243,15 +296,22 @@ const permanentLog = new FileStream("permanent.log", 0);
- `error`: Errors that affect a single operation but not the whole app. - `error`: Errors that affect a single operation but not the whole app.
- `fatal`: Critical errors that require the application to shut down. - `fatal`: Critical errors that require the application to shut down.
3. **Use a `source`**: Identify which component generated the log. 3. **Use a `source`**: Identify which component generated the log using `processor.addSource`.
```typescript ```typescript
const logger = createDevLogger({ source: "UserService" }); import { Logger, processor } from "@/lib/ccStructLog";
const logger = new Logger({
processors: [processor.addSource("UserService")],
// ...
});
``` ```
4. **Sanitize Sensitive Data**: Use a processor to remove passwords, API keys, etc. 4. **Sanitize Sensitive Data**: Use a processor to remove passwords, API keys, etc.
```typescript ```typescript
import { Logger, processor } from "@/lib/ccStructLog";
const secureLogger = new Logger({ const secureLogger = new Logger({
processors: [ removeFields(["password", "token"]) ], processors: [ processor.removeFields(["password", "token"]) ],
//... //...
}); });
``` ```