All files / my-screeps-repo/src/utils logger.js

48.68% Statements 37/76
38.88% Branches 14/36
52.94% Functions 9/17
51.42% Lines 36/70

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275                    3x           3x 3x           3x 3x           3x                                     14x                   14x                 14x 14x                                                             1x                             3x 3x 3x     3x 3x                 3x 3x 3x     3x 3x                 8x 8x 8x 8x 6x 6x 6x   2x     8x 8x                                         6x 6x 6x                                               1x                                                                                                         3x                                  
/**
 * src/utils/logger.js
 * Screeps ログ出力ユーティリティ
 *
 * ログレベル別の出力制御・統計収集・スタック安全化を提供する。
 * グローバルキャッシュは global.cache.logs に格納する。
 */
 
'use strict';
 
const { LOG_LEVEL, DEFAULT_LOG_LEVEL } = require('../constants');
 
// ============================================================
// 内部状態
// ============================================================
 
let _level = DEFAULT_LOG_LEVEL;
const _stats = {
    debug: 0,
    info: 0,
    warn: 0,
    error: 0,
};
const _history = [];
const MAX_HISTORY = 50;
 
// ============================================================
// カラーコード(Screeps コンソール用 HTML)
// ============================================================
 
const COLORS = {
    debug: '#888888',
    info: '#00bfff',
    warn: '#ffaa00',
    error: '#ff4444',
    success: '#00ff88',
    highlight: '#ffffff',
};
 
// ============================================================
// 内部ヘルパー
// ============================================================
 
/**
 * 現在のティックと現在時刻を含むプレフィックスを生成する
 * @param {string} level - ログレベル文字列
 * @returns {string}
 */
function _prefix(level) {
    return `[T:${Game.time}][${level.toUpperCase()}]`;
}
 
/**
 * HTML カラータグで文字列をラップする
 * @param {string} text
 * @param {string} color - 16進数カラーコード (#rrggbb)
 * @returns {string}
 */
function _colorize(text, color) {
    return `<font color="${color}">${text}</font>`;
}
 
/**
 * ログエントリを履歴に追加する
 * @param {string} level
 * @param {string} message
 */
function _record(level, message) {
    _history.push({ tick: Game.time, level, message });
    Iif (_history.length > MAX_HISTORY) {
        _history.shift();
    }
}
 
// ============================================================
// 公開API
// ============================================================
 
/**
 * ログレベルを設定する
 * @param {number} level - LOG_LEVEL 定数のいずれか
 */
function setLevel(level) {
    _level = level;
}
 
/**
 * 現在のログレベルを取得する
 * @returns {number}
 */
function getLevel() {
    return _level;
}
 
/**
 * DEBUGレベルのログを出力する
 * @param {string} message
 * @param {*} [data] - 付加情報(JSON文字列化される)
 */
function debug(message, data) {
    Eif (_level > LOG_LEVEL.DEBUG) return;
    _stats.debug++;
    const full = data !== undefined
        ? `${message} ${JSON.stringify(data)}`
        : message;
    _record('debug', full);
    console.log(_colorize(`${_prefix('debug')} ${full}`, COLORS.debug));
}
 
/**
 * INFOレベルのログを出力する
 * @param {string} message
 * @param {*} [data]
 */
function info(message, data) {
    Iif (_level > LOG_LEVEL.INFO) return;
    _stats.info++;
    const full = data !== undefined
        ? `${message} ${JSON.stringify(data)}`
        : message;
    _record('info', full);
    console.log(_colorize(`${_prefix('info')} ${full}`, COLORS.info));
}
 
/**
 * WARNレベルのログを出力する
 * @param {string} message
 * @param {*} [data]
 */
function warn(message, data) {
    Iif (_level > LOG_LEVEL.WARN) return;
    _stats.warn++;
    const full = data !== undefined
        ? `${message} ${JSON.stringify(data)}`
        : message;
    _record('warn', full);
    console.log(_colorize(`${_prefix('warn')} ${full}`, COLORS.warn));
}
 
/**
 * ERRORレベルのログを出力する
 * @param {string} message
 * @param {Error|*} [error] - エラーオブジェクトまたは付加情報
 */
function error(message, error) {
    Iif (_level > LOG_LEVEL.ERROR) return;
    _stats.error++;
    let full = message;
    if (error instanceof Error) {
        full += ` | ${error.message}`;
        Eif (error.stack) {
            full += `\n${getSafeStack(error.stack)}`;
        }
    } else Iif (error !== undefined) {
        full += ` ${JSON.stringify(error)}`;
    }
    _record('error', full);
    console.log(_colorize(`${_prefix('error')} ${full}`, COLORS.error));
}
 
/**
 * 成功ログ(INFOレベル)を緑色で出力する
 * @param {string} message
 */
function success(message) {
    if (_level > LOG_LEVEL.INFO) return;
    _stats.info++;
    _record('info', message);
    console.log(_colorize(`${_prefix('info')} ✓ ${message}`, COLORS.success));
}
 
/**
 * スタックトレースから安全な部分を抽出する(長すぎる場合に切り詰め)
 * @param {string} stack
 * @param {number} [maxLines=5] - 返す最大行数
 * @returns {string}
 */
function getSafeStack(stack, maxLines) {
    Iif (!stack) return '';
    const lines = stack.split('\n');
    return lines.slice(0, maxLines || 5).join('\n');
}
 
/**
 * 関数をtry-catchでラップして実行し、エラー時にログを出力する
 * @param {Function} fn - 実行する関数
 * @param {string} context - エラーメッセージに含めるコンテキスト名
 * @param {...*} args - 関数に渡す引数
 * @returns {*} 関数の戻り値、エラー時は undefined
 */
function tryCatch(fn, context, ...args) {
    try {
        return fn(...args);
    } catch (e) {
        error(`[${context}] ${e.message}`, e);
        return undefined;
    }
}
 
/**
 * ログ統計を返す
 * @returns {{ debug: number, info: number, warn: number, error: number, total: number }}
 */
function getStats() {
    return {
        ..._stats,
        total: _stats.debug + _stats.info + _stats.warn + _stats.error,
    };
}
 
/**
 * ログ履歴を返す
 * @param {number} [count=10] - 取得する件数
 * @returns {Array<{ tick: number, level: string, message: string }>}
 */
function getHistory(count) {
    const n = count || 10;
    return _history.slice(-n);
}
 
/**
 * 統計をリセットする
 */
function resetStats() {
    _stats.debug = 0;
    _stats.info = 0;
    _stats.warn = 0;
    _stats.error = 0;
    _history.length = 0;
}
 
/**
 * ロガーを初期化する(各ティックの先頭で呼び出す)
 * Memory.logLevel が設定されていればそれを使用する
 */
function init() {
    if (Memory.logLevel !== undefined && Memory.logLevel !== _level) {
        _level = Memory.logLevel;
    }
}
 
/**
 * ログ設定ダッシュボードをコンソールに表示する
 */
function showDashboard() {
    const stats = getStats();
    console.log(_colorize('=== Logger Dashboard ===', COLORS.highlight));
    console.log(`Level: ${_level} (0=DEBUG, 1=INFO, 2=WARN, 3=ERROR, 4=NONE)`);
    console.log(`Stats: DEBUG=${stats.debug} INFO=${stats.info} WARN=${stats.warn} ERROR=${stats.error}`);
    console.log('Recent logs:');
    const recent = getHistory(5);
    for (const entry of recent) {
        const color = COLORS[entry.level] || COLORS.info;
        console.log(_colorize(`  [T:${entry.tick}][${entry.level}] ${entry.message}`, color));
    }
}
 
module.exports = {
    LOG_LEVEL,
    setLevel,
    getLevel,
    debug,
    info,
    warn,
    error,
    success,
    getSafeStack,
    tryCatch,
    getStats,
    getHistory,
    resetStats,
    init,
    showDashboard,
};