ログ・設定の分散
説明(どんな問題か)
どんな状態か?
- ログ出力処理や設定値へのアクセスが、各所でバラバラに記述されている
- それぞれが異なる形式・手段でログ出力や設定読み込みをしており、統一性がない
- ログや設定の扱いが開発者ごとに異なる実装になりがち
なぜ問題か?
- 保守性・再利用性が低くなる
- ログ形式や出力先を変えたいとき、影響範囲が大きくなる
- 設定値の参照ミスや重複読み込みがパフォーマンス低下やバグの温床になる
アンチパターンのコード例
- TypeScript
- PHP
- Python
// あちこちで Logger や設定を直接扱っている
class OrderService {
createOrder(orderId: string) {
console.log(`[OrderService] 注文作成: ${orderId}`); // 直書きログ
const debugMode = process.env.DEBUG_MODE === "true"; // 設定の直接参照
if (debugMode) {
console.log(`[DEBUG] 注文詳細: ${orderId}`);
}
}
}
class UserService {
createUser(name: string) {
console.log(`[UserService] ユーザー作成: ${name}`);
}
}
<?php
class OrderService {
public function createOrder(string $orderId): void {
echo "[OrderService] 注文作成: {$orderId}\n"; // 直書きログ
$debugMode = getenv("DEBUG_MODE") === "true"; // 設定の直接参照
if ($debugMode) {
echo "[DEBUG] 注文詳細: {$orderId}\n";
}
}
}
class UserService {
public function createUser(string $name): void {
echo "[UserService] ユーザー作成: {$name}\n"; // 直書きログ
}
}
// 環境変数設定(実行前に CLI などで設定)
// putenv("DEBUG_MODE=true");
$orderService = new OrderService();
$orderService->createOrder("order-123");
$userService = new UserService();
$userService->createUser("hiroshi");
import os
class OrderService:
def create_order(self, order_id: str):
print(f"[OrderService] 注文作成: {order_id}") # 直書きログ
debug_mode = os.environ.get("DEBUG_MODE") == "true" # 設定の直接参照
if debug_mode:
print(f"[DEBUG] 注文詳細: {order_id}")
class UserService:
def create_user(self, name: str):
print(f"[UserService] ユーザー作成: {name}") # 直書きログ
# 実行例
# os.environ["DEBUG_MODE"] = "true"
order_service = OrderService()
order_service.create_order("order-123")
user_service = UserService()
user_service.create_user("hiroshi")
問題点:
console.log()
を直接使用 → ログ仕様変更時に全て直す必要があるprocess.env
に直接アクセス → 設定の集中管理ができない- 責務が分散していて再利用も難しい
パターン別のリファクタリング
対応可能なデザインパターン例
パターン | 概要 | 主な解決アプローチ |
---|---|---|
Singleton | アプリケーション全体でインスタンスを 1 つに限定 | ログや設定を共有状態で管理 |
Facade | 複雑な設定・ログ処理をシンプルな API で提供 | 窓口を統一して利用しやすくする |