docs(phase 105): Logger Box Framework設計&ドキュメント整備

- Create logger_box_design.md: comprehensive Logger Box framework design
- Define 3 reference patterns (Lightweight/Structured/Contextual)
- Add pseudo-code examples for each pattern (reference only)
- Update logging_policy.md: add Logger Box reference
- Update hako_logging_design.md: Logger Box integration with Phase 104
- Update ring0-inventory.md: Phase 105 entry
- Update CURRENT_TASK.md: Phase 105 completion + Phase 106+ backlog

Design principles:
- Logger Box provides level-based logging (DEBUG/INFO/WARN/ERROR)
- Phase 105 scope: ConsoleBox output only
- Phase 106 scope: output redirection (FileBox/NetworkBox)
- Reference examples for documentation (execution testing Phase 106+)

This completes the structured logging framework design, building on
Phase 99 (logging policy), Phase 100-101 (Rust logging), Phase 104
(.hako patterns), and Phase 105.5 (console macro unification).
This commit is contained in:
nyash-codex
2025-12-03 14:33:04 +09:00
parent ea4c164dae
commit f8790b13cc
5 changed files with 542 additions and 1 deletions

View File

@ -263,6 +263,21 @@
- ✅ internal/dev println!/eprintln! 113箇所を Ring0.log に移行provider_lock / plugin_loader_unified / type_meta / deprecations / leak_tracker / provider_verify / scheduler / gc_controller / box_registry / plugin_loader_v2 周辺 / runner trace / mir verifier / mir core basic_block/control_form/hints/effect/printer/optimizer / loop_builder/phi_ops / builder/type_registry / region/observer / extern_functions / plugin types finalize trace / joinir_if_phi_selector / observe/types+resolve / join_ir_vm_bridge_dispatch run_generic / loop_builder/control など) - ✅ internal/dev println!/eprintln! 113箇所を Ring0.log に移行provider_lock / plugin_loader_unified / type_meta / deprecations / leak_tracker / provider_verify / scheduler / gc_controller / box_registry / plugin_loader_v2 周辺 / runner trace / mir verifier / mir core basic_block/control_form/hints/effect/printer/optimizer / loop_builder/phi_ops / builder/type_registry / region/observer / extern_functions / plugin types finalize trace / joinir_if_phi_selector / observe/types+resolve / join_ir_vm_bridge_dispatch run_generic / loop_builder/control など)
- ✅ logging_policy.md / ring0-inventory.md にテスト出力許容ポリシーと残件概算を追記(残 ~475495 - ✅ logging_policy.md / ring0-inventory.md にテスト出力許容ポリシーと残件概算を追記(残 ~475495
- ⏭️ 残り internal/dev ログは Phase 101-C 以降で段階的に処理user-facing/.hako は別ライン) - ⏭️ 残り internal/dev ログは Phase 101-C 以降で段階的に処理user-facing/.hako は別ライン)
- **Phase 104: .hako側ロギング設計**2025-12-04
- ✅ ConsoleBox適切な使い方ガイド作成
- ✅ 4つのロギングカテゴリ確立user-facing/dev-debug/monitoring/internal Rust
- ✅ 3つのロギングBoxパターン設計Lightweight/Structured/Contextual
- ✅ hako_logging_design.md 作成、logging_policy.md 更新
- **スコープ**: .hako アプリケーション側のロギングベストプラクティス確立
- **Phase 105: Logger Box Framework設計**2025-12-04← NEW
- ✅ Logger Box インターフェース設計(ログレベル: DEBUG/INFO/WARN/ERROR
- ✅ 3つの設計パターン文書化Lightweight/Structured/Contextual
- ✅ リファレンス実装例作成pseudo-code、実行テストは Phase 106+
- ✅ logger_box_design.md 作成500+ lines
- ✅ logging_policy.md / hako_logging_design.md / ring0-inventory.md にクロスリファレンス追加
- **スコープ**: 設計ドキュメントのみRust実装なし、Phase 106+で実装)
- **成果**: ConsoleBox基盤の構造化ロギングフレームワーク確立
- **次のステップ**: Phase 106FileBox/NetworkBox出力リダイレクト、Phase 107アプリ移行
12. **Phase 86: BoxFactory Priority 正常化****完了**2025-12-02 12. **Phase 86: BoxFactory Priority 正常化****完了**2025-12-02
- **目的**: BoxFactory のデフォルトポリシーを `BuiltinFirst` から `StrictPluginFirst` に変更し、プラグイン版 Box が正常に使用できるよう正常化。 - **目的**: BoxFactory のデフォルトポリシーを `BuiltinFirst` から `StrictPluginFirst` に変更し、プラグイン版 Box が正常に使用できるよう正常化。
@ -280,6 +295,25 @@
### バックログ ### バックログ
#### ロギングフレームワーク拡張Phase 106+
- **Phase 106: Logger Box 出力リダイレクト**
- Logger Box から FileBox へのログ出力機能実装
- Logger Box から NetworkBox へのリモートログ送信機能実装
- Phase 105 で設計した interface 互換性維持
- **Phase 107: アプリケーション移行**
- hako_check を Logger Box 使用に移行
- selfhost-compiler を Logger Box 使用に移行
- Nyash ツール全体のロギング標準化
- **Phase 108+: 高度ロギング機能**
- 構造化ロギングJSON format
- ログアグリゲーション
- パフォーマンスメトリクス
#### その他
- StageB/selfhost smokes の扱い整理Phase 30.1 フォロー) - StageB/selfhost smokes の扱い整理Phase 30.1 フォロー)
- quick プロファイルで `stage1_launcher_*` / `phase251*` 系が Stage3 デフォルト環境で不安定。今後、quick では SKIP にするか、StageB emit 抽出ロジックを安定化するかを決める。 - quick プロファイルで `stage1_launcher_*` / `phase251*` 系が Stage3 デフォルト環境で不安定。今後、quick では SKIP にするか、StageB emit 抽出ロジックを安定化するかを決める。
- `MirFunction.blocks: HashMap``BTreeMap` で非決定的テスト解消 - `MirFunction.blocks: HashMap``BTreeMap` で非決定的テスト解消

View File

@ -324,8 +324,30 @@ box RequestHandler {
- [ ] テストコード内の println! は許容 - [ ] テストコード内の println! は許容
- [ ] 本番環境での不要なログを削除した - [ ] 本番環境での不要なログを削除した
## Phase 105: Logger Box Framework Integration
Phase 105 で Logger Box フレームワークが導入され、以下のパターンが正式化されました:
- **LightweightLoggerBox**: メッセージのみの単純ロギング
- **StructuredLoggerBox**: DEBUG/INFO/WARN/ERROR レベル付きロギング
- **ContextualLoggerBox**: contextrequest ID等付きロギング
詳細な設計と実装例は [Logger Box Design](logger_box_design.md) を参照してください。
### Integration with Phase 104 Categories
Logger Box は以下のカテゴリに対応:
| Phase 104 Category | Logger Box Pattern | Use Case |
|-------------------|-------------------|----------|
| user-facing | Direct ConsoleBox (no Logger Box needed) | 単純なユーザーメッセージ |
| dev-debug | StructuredLogger (DEBUG level) | デバッグ出力 |
| monitoring | StructuredLogger (INFO level) | 監視情報 |
| internal Rust | Ring0.log | Rust側の内部ログ |
## 関連ドキュメント ## 関連ドキュメント
- [logger_box_design.md](logger_box_design.md) - Phase 105 Logger Box フレームワーク
- [logging_policy.md](logging_policy.md) - Rust/Ring0.log側方針 - [logging_policy.md](logging_policy.md) - Rust/Ring0.log側方針
- [ring0-inventory.md](ring0-inventory.md) - println!分類在庫 - [ring0-inventory.md](ring0-inventory.md) - println!分類在庫
- [core_optional_design.md](core_optional_design.md) - Optional化設計 - [core_optional_design.md](core_optional_design.md) - Optional化設計

View File

@ -0,0 +1,464 @@
# Phase 105: Logger Box Design & Framework
## 1. Overview
Logger Box provides a structured, level-based logging interface for Nyash applications, built on top of ConsoleBox (Phase 104). It enables developers to:
- Use DEBUG/INFO/WARN/ERROR log levels
- Filter logs by level at runtime
- Compose logger boxes for specific use cases
- Prepare for future output redirection (FileBox/NetworkBox in Phase 106+)
## 2. Design Principles
1. **Single Responsibility**: Each Logger Box has one logging purpose
2. **ConsoleBox Centered**: Phase 105 scope: all output via ConsoleBox
3. **Future-Proof**: Interface designed to support FileBox/NetworkBox in Phase 106+
4. **Composable**: Logger boxes can be combined or wrapped
5. **No Duplication**: Single ConsoleBox instance per logger
## 3. Log Levels
```
Priority (High → Low):
ERROR - Critical errors requiring immediate attention
WARN - Warnings that might indicate problems
INFO - General informational messages
DEBUG - Detailed debugging information
```
Level numeric mapping:
- DEBUG = 0
- INFO = 1
- WARN = 2
- ERROR = 3
## 4. Core Logger Box Interface (Reference Design)
This is a **reference design** showing the conceptual interface. Implementations may vary based on specific needs.
### Pseudo-Code Example
```nyash
box LoggerBox {
// State
console: ConsoleBox
min_level: IntegerBox // Minimum level to output (0=DEBUG, 1=INFO, 2=WARN, 3=ERROR)
// Constants (reference levels)
// DEBUG=0, INFO=1, WARN=2, ERROR=3
birth(min_level: IntegerBox) {
me.console = new ConsoleBox()
me.min_level = min_level
}
// Helper: check if message should be logged
fn enabled?(level: IntegerBox) -> BoolBox {
return level >= me.min_level
}
// Public methods: log at each level
debug(msg: StringBox) {
if me.enabled?(0) { // 0 = DEBUG level
me.console.println("[DEBUG] " + msg)
}
}
info(msg: StringBox) {
if me.enabled?(1) { // 1 = INFO level
me.console.println("[INFO] " + msg)
}
}
warn(msg: StringBox) {
if me.enabled?(2) { // 2 = WARN level
me.console.println("[WARN] " + msg)
}
}
error(msg: StringBox) {
if me.enabled?(3) { // 3 = ERROR level
me.console.println("[ERROR] " + msg)
}
}
}
```
### Design Notes
- **Level comparison**: Use integers (0-3) for simplicity in Nyash
- **Optional optimization**: Environments could add bitwise filtering or enum-based levels in Phase 106+
- **ConsoleBox fixed**: Phase 105 always outputs to ConsoleBox
- **Future extensibility**: Interface design allows swapping ConsoleBox for FileBox/NetworkBox in Phase 106+
## 5. Three Design Patterns
### Pattern 1: Lightweight Logger Box
**Purpose**: Minimal logging for simple tools
**Conceptual design**:
```nyash
box SimpleLoggerBox {
console: ConsoleBox
birth() {
me.console = new ConsoleBox()
}
log(msg: StringBox) {
me.console.println(msg)
}
}
```
**Use case**: Progress tracking, simple tools
**Key feature**: No levels, just output
### Pattern 2: Structured Logger Box
**Purpose**: Level-based logging with standard prefixes
**Conceptual design**:
```nyash
box StructuredLoggerBox {
console: ConsoleBox
min_level: IntegerBox
birth(min_level: IntegerBox) {
me.console = new ConsoleBox()
me.min_level = min_level
}
debug(msg: StringBox) {
if me.min_level <= 0 {
me.console.println("[DEBUG] " + msg)
}
}
info(msg: StringBox) {
if me.min_level <= 1 {
me.console.println("[INFO] " + msg)
}
}
warn(msg: StringBox) {
if me.min_level <= 2 {
me.console.println("[WARN] " + msg)
}
}
error(msg: StringBox) {
if me.min_level <= 3 {
me.console.println("[ERROR] " + msg)
}
}
}
```
**Use case**: General applications
**Key feature**: ERROR/WARN/INFO/DEBUG methods
### Pattern 3: Contextual Logger Box
**Purpose**: Logging with context information (request ID, operation name, etc.)
**Conceptual design**:
```nyash
box ContextualLoggerBox {
console: ConsoleBox
context: StringBox // Request ID, operation name, etc.
min_level: IntegerBox
birth(context: StringBox, min_level: IntegerBox) {
me.console = new ConsoleBox()
me.context = context
me.min_level = min_level
}
debug(msg: StringBox) {
if me.min_level <= 0 {
me.console.println("[" + me.context + "][DEBUG] " + msg)
}
}
info(msg: StringBox) {
if me.min_level <= 1 {
me.console.println("[" + me.context + "][INFO] " + msg)
}
}
warn(msg: StringBox) {
if me.min_level <= 2 {
me.console.println("[" + me.context + "][WARN] " + msg)
}
}
error(msg: StringBox) {
if me.min_level <= 3 {
me.console.println("[" + me.context + "][ERROR] " + msg)
}
}
}
```
**Use case**: Multi-tenant systems, request handlers
**Key feature**: Context prefix in all messages
## 6. Implementation Guidance
### For Users Implementing Logger Box
When creating your own Logger Box implementation:
1. **Initialize once**: Create logger box once, reuse for all logging
2. **Level filtering**: Implement early exit for disabled levels
3. **Message formatting**: Consider prefix convention ([LEVEL])
4. **ConsoleBox encapsulation**: Keep ConsoleBox as internal detail
### Recommended Base Implementation
Start with Pattern 2 (StructuredLoggerBox) as it covers most use cases. Extend with Pattern 3 when context becomes important.
## 7. Integration with Phase 99-104 Logging Policy
### Mapping to Logging Categories
| Category | Logger Box Role | Phase 105 Support |
|----------|-----------------|-------------------|
| user-facing | Could use SimpleLogger + ConsoleBox directly (no Logger Box needed) | Simple messages only |
| dev-debug | StructuredLogger + DEBUG level | Supported |
| monitoring | StructuredLogger + INFO level | Supported |
| internal Rust | Ring0.log (not Logger Box) | N/A |
### Notes
- **User-facing messages**: Often don't need Logger Box (direct ConsoleBox sufficient)
- **Dev-debug**: Use StructuredLogger with DEBUG level enabled
- **Monitoring**: Use StructuredLogger with INFO level enabled
- **Rust internal**: Ring0.log handles this (separate from Logger Box)
## 8. Reference Examples
These are **reference examples** for understanding Logger Box design. They are NOT intended to be run or tested in Phase 105. Execution and testing will be part of Phase 106+.
### Example 1: Simple Logger Box
```nyash
// Reference: Simple logging without levels
box SimpleLoggerBox {
console: ConsoleBox
birth() {
me.console = new ConsoleBox()
}
log(msg) {
me.console.println(msg)
}
}
// Usage example
static box SimpleLoggingApp {
main() {
local logger = new SimpleLoggerBox()
logger.log("Starting application...")
logger.log("✅ Success!")
}
}
```
### Example 2: Structured Logger Box
```nyash
// Reference: Level-based structured logging
box StructuredLoggerBox {
console: ConsoleBox
min_level: IntegerBox // 0=DEBUG, 1=INFO, 2=WARN, 3=ERROR
birth(min_level) {
me.console = new ConsoleBox()
me.min_level = min_level
}
debug(msg) {
if me.min_level <= 0 {
me.console.println("[DEBUG] " + msg)
}
}
info(msg) {
if me.min_level <= 1 {
me.console.println("[INFO] " + msg)
}
}
warn(msg) {
if me.min_level <= 2 {
me.console.println("[WARN] " + msg)
}
}
error(msg) {
if me.min_level <= 3 {
me.console.println("[ERROR] " + msg)
}
}
}
// Usage example
static box DataProcessor {
logger: StructuredLoggerBox
main() {
me.logger = new StructuredLoggerBox(1) // INFO level minimum
me.logger.debug("Debug info (won't show)")
me.logger.info("Processing started...")
me.logger.warn("Low memory warning")
me.logger.error("❌ Critical error!")
}
}
```
### Example 3: Contextual Logger Box
```nyash
// Reference: Context-aware logging
box ContextualLoggerBox {
console: ConsoleBox
context: StringBox
min_level: IntegerBox
birth(context, min_level) {
me.console = new ConsoleBox()
me.context = context
me.min_level = min_level
}
debug(msg) {
if me.min_level <= 0 {
me.console.println("[" + me.context + "][DEBUG] " + msg)
}
}
info(msg) {
if me.min_level <= 1 {
me.console.println("[" + me.context + "][INFO] " + msg)
}
}
warn(msg) {
if me.min_level <= 2 {
me.console.println("[" + me.context + "][WARN] " + msg)
}
}
error(msg) {
if me.min_level <= 3 {
me.console.println("[" + me.context + "][ERROR] " + msg)
}
}
}
// Usage example
box RequestHandler {
logger: ContextualLoggerBox
birth(request_id) {
me.logger = new ContextualLoggerBox(request_id, 1)
}
process(data) {
me.logger.info("Request received")
// ... processing ...
me.logger.info("Request completed")
}
}
static box RequestProcessingApp {
main() {
local handler1 = new RequestHandler("req-001")
local handler2 = new RequestHandler("req-002")
handler1.process(10)
handler2.process(20)
}
}
```
### Important Notes on Examples
These are **reference examples** for understanding Logger Box design. Users should:
1. Adapt these to their specific needs
2. Implement their own versions based on their application requirements
3. Consider Phase 106+ extensions for file/network output if needed
## 9. Anti-Patterns to Avoid
**DON'T: Multiple ConsoleBox instances**
```nyash
box BadLogger {
main() {
local c1 = new ConsoleBox()
local c2 = new ConsoleBox() // Wrong: duplicate
c1.println("msg1")
c2.println("msg2")
}
}
```
**DON'T: Mix logging into business logic**
```nyash
process(data) {
print("[DEBUG] processing...") // Wrong: mixed concerns
return data * 2
}
```
**DON'T: Ignore level filtering**
```nyash
debug(msg) {
me.console.println("[DEBUG] " + msg) // Wrong: always outputs
}
```
**DO: Centralize logging**
```nyash
box DataProcessor {
logger: StructuredLoggerBox
birth() {
me.logger = new StructuredLoggerBox(1) // INFO level
}
process(data) {
me.logger.info("Starting process...")
return data * 2
}
}
```
## 10. Future Extensions (Phase 106+)
These are planned for future phases:
### Phase 106: Output Redirection
- Logger Box could redirect to FileBox for file logging
- Or redirect to NetworkBox for remote logging
- Interface stays compatible
### Phase 107: Application Migration
- Migrate hako_check, selfhost-compiler to use Logger Box
- Standardize logging across all Nyash tools
### Phase 108+: Advanced Features
- Structured logging (JSON format)
- Log aggregation
- Performance metrics
## 11. Related Documentation
- [Phase 99: logging_policy.md](logging_policy.md) - Overall logging framework
- [Phase 104: hako_logging_design.md](hako_logging_design.md) - User application logging patterns
- [Phase 104: ring0-inventory.md](ring0-inventory.md) - Logging infrastructure inventory

View File

@ -298,6 +298,9 @@ Focus on high-impact migrations first, defer low-priority changes.
Nyash.hakoアプリケーションからのロギングは、ConsoleBoxを通じてユーザーに伝える方式に統一。 Nyash.hakoアプリケーションからのロギングは、ConsoleBoxを通じてユーザーに伝える方式に統一。
**Note**: Phase 105では Logger Box フレームワークが正式化され、より構造化された
ロギングが可能になりました。詳細は [Logger Box Design](logger_box_design.md) を参照。
### パターン分類 ### パターン分類
#### Pattern 1: ユーザー向けメッセージuser-facing #### Pattern 1: ユーザー向けメッセージuser-facing
@ -472,8 +475,10 @@ test my_test {
## 関連ドキュメント ## 関連ドキュメント
- [Logger Box Design](logger_box_design.md) - Phase 105 structured logging framework
- [.hako側ロギング設計](hako_logging_design.md) - Phase 104 ユーザーアプリ視点 - [.hako側ロギング設計](hako_logging_design.md) - Phase 104 ユーザーアプリ視点
- [Ring0 Inventory](ring0-inventory.md) - println! categorization and Ring0.log plans - [ring0-inventory.md](ring0-inventory.md) - Ring0.log利用状況の在庫管理
- [core_optional_design.md](core_optional_design.md) - CoreServices optional化
- [CoreBoxes Design - Section 15.6-A](core_boxes_design.md#section-156-a-logsoutput-unified-design) - Architectural context - [CoreBoxes Design - Section 15.6-A](core_boxes_design.md#section-156-a-logsoutput-unified-design) - Architectural context
- [Phase 85 CURRENT_TASK](../../../CURRENT_TASK.md) - Implementation timeline - [Phase 85 CURRENT_TASK](../../../CURRENT_TASK.md) - Implementation timeline

View File

@ -342,6 +342,22 @@ ring0.log.debug(&format!("Operation completed in {}ms", duration));
--- ---
### Phase 105: Logger Box Framework (COMPLETED)
**Scope**:
- Logger Box インターフェース設計(ログレベル: DEBUG/INFO/WARN/ERROR
- 3つの設計パターンLightweight/Structured/Contextualのリファレンス実装例
- Phase 99-104 ロギングポリシーとの整合確認
**Files Created/Updated**:
- docs/development/current/main/logger_box_design.md (new)
- docs/development/current/main/logging_policy.md (updated)
- docs/development/current/main/hako_logging_design.md (updated)
**Status**: Design + reference examples complete. Runtime implementation deferred to Phase 106+.
---
## Section 5: Migration Roadmap ## Section 5: Migration Roadmap
### Phase 99 (Current): Documentation & Planning ### Phase 99 (Current): Documentation & Planning