mirror of
https://github.com/SikongJueluo/cc-utils.git
synced 2025-11-29 12:57:50 +08:00
refactor(logging): migrate from CCLog to structured Logger
This commit is contained in:
@@ -1,4 +1,3 @@
|
||||
import { CCLog, DAY, LogLevel } from "@/lib/ccLog";
|
||||
import { ToastConfig, UserGroupConfig, loadConfig } from "./config";
|
||||
import { createAccessControlCli } from "./cli";
|
||||
import { launchAccessControlTUI } from "./tui";
|
||||
@@ -7,14 +6,31 @@ import { ReadWriteLock } from "@/lib/mutex/ReadWriteLock";
|
||||
import { ChatManager } from "@/lib/ChatManager";
|
||||
import { gTimerManager } from "@/lib/TimerManager";
|
||||
import { KeyEvent, pullEventAs } from "@/lib/event";
|
||||
import {
|
||||
ConditionalStream,
|
||||
ConsoleStream,
|
||||
DAY,
|
||||
FileStream,
|
||||
Logger,
|
||||
LogLevel,
|
||||
processor,
|
||||
textRenderer,
|
||||
} from "@/lib/ccStructLog";
|
||||
|
||||
const args = [...$vararg];
|
||||
|
||||
// Init Log
|
||||
const logger = new CCLog("accesscontrol.log", {
|
||||
printTerminal: true,
|
||||
logInterval: DAY,
|
||||
outputMinLevel: LogLevel.Info,
|
||||
let isOnConsoleStream = true;
|
||||
const logger = new Logger({
|
||||
processors: [
|
||||
processor.filterByLevel(LogLevel.Info),
|
||||
processor.addTimestamp(),
|
||||
],
|
||||
renderer: textRenderer,
|
||||
streams: [
|
||||
new ConditionalStream(new ConsoleStream(), () => isOnConsoleStream),
|
||||
new FileStream("accesscontrol.log", DAY),
|
||||
],
|
||||
});
|
||||
|
||||
// Load Config
|
||||
@@ -203,7 +219,9 @@ function watchLoop() {
|
||||
continue;
|
||||
}
|
||||
|
||||
const watchPlayerNames = gWatchPlayersInfo.flatMap((value) => value.name);
|
||||
const watchPlayerNames = gWatchPlayersInfo.flatMap(
|
||||
(value) => value.name,
|
||||
);
|
||||
logger.debug(`Watch Players [ ${watchPlayerNames.join(", ")} ]`);
|
||||
for (const player of gWatchPlayersInfo) {
|
||||
const playerInfo = playerDetector.getPlayerPos(player.name);
|
||||
@@ -329,13 +347,15 @@ function keyboardLoop() {
|
||||
if (event.key === keys.c) {
|
||||
logger.info("Launching Access Control TUI...");
|
||||
try {
|
||||
logger.setInTerminal(false);
|
||||
isOnConsoleStream = false;
|
||||
launchAccessControlTUI();
|
||||
logger.info("TUI closed, resuming normal operation");
|
||||
} catch (error) {
|
||||
logger.error(`TUI error: ${textutils.serialise(error as object)}`);
|
||||
logger.error(
|
||||
`TUI error: ${textutils.serialise(error as object)}`,
|
||||
);
|
||||
} finally {
|
||||
logger.setInTerminal(true);
|
||||
isOnConsoleStream = true;
|
||||
reloadConfig();
|
||||
}
|
||||
} else if (event.key === keys.r) {
|
||||
@@ -379,7 +399,9 @@ function cliLoop() {
|
||||
releaser = configLock.tryAcquireRead();
|
||||
}
|
||||
|
||||
const isAdmin = config.adminGroupConfig.groupUsers.includes(ev.username);
|
||||
const isAdmin = config.adminGroupConfig.groupUsers.includes(
|
||||
ev.username,
|
||||
);
|
||||
|
||||
releaser.release();
|
||||
if (!isAdmin) continue;
|
||||
@@ -422,11 +444,14 @@ function main(args: string[]) {
|
||||
return;
|
||||
} else if (args[0] == "config") {
|
||||
logger.info("Launching Access Control TUI...");
|
||||
logger.setInTerminal(false);
|
||||
isOnConsoleStream = false;
|
||||
|
||||
try {
|
||||
launchAccessControlTUI();
|
||||
} catch (error) {
|
||||
logger.error(`TUI error: ${textutils.serialise(error as object)}`);
|
||||
logger.error(
|
||||
`TUI error: ${textutils.serialise(error as object)}`,
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -3,10 +3,23 @@ import {
|
||||
CraftRecipe,
|
||||
CreatePackageTag,
|
||||
} from "@/lib/CraftManager";
|
||||
import { CCLog, LogLevel } from "@/lib/ccLog";
|
||||
import { Queue } from "@/lib/datatype/Queue";
|
||||
import {
|
||||
ConsoleStream,
|
||||
Logger,
|
||||
LogLevel,
|
||||
processor,
|
||||
textRenderer,
|
||||
} from "@/lib/ccStructLog";
|
||||
|
||||
const logger = new CCLog("autocraft.log", { outputMinLevel: LogLevel.Info });
|
||||
const logger = new Logger({
|
||||
processors: [
|
||||
processor.filterByLevel(LogLevel.Info),
|
||||
processor.addFullTimestamp(),
|
||||
],
|
||||
renderer: textRenderer,
|
||||
streams: [new ConsoleStream()],
|
||||
});
|
||||
|
||||
const peripheralsNames = {
|
||||
// packsInventory: "minecraft:chest_14",
|
||||
@@ -103,17 +116,20 @@ function main() {
|
||||
logger.debug(
|
||||
`Turtle:\n${textutils.serialise(blockReader.getBlockData()!, { allow_repetitions: true })}`,
|
||||
);
|
||||
const packageDetailInfo = blockReader.getBlockData()?.Items[1];
|
||||
const packageDetailInfo =
|
||||
blockReader.getBlockData()?.Items[1];
|
||||
if (packageDetailInfo === undefined) {
|
||||
logger.error(`Package detail info not found`);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Get OrderId and isFinal
|
||||
const packageOrderId = (packageDetailInfo.tag as CreatePackageTag)
|
||||
.Fragment.OrderId;
|
||||
const packageOrderId = (
|
||||
packageDetailInfo.tag as CreatePackageTag
|
||||
).Fragment.OrderId;
|
||||
const packageIsFinal =
|
||||
(packageDetailInfo.tag as CreatePackageTag).Fragment.IsFinal > 0
|
||||
(packageDetailInfo.tag as CreatePackageTag).Fragment
|
||||
.IsFinal > 0
|
||||
? true
|
||||
: false;
|
||||
|
||||
@@ -121,11 +137,21 @@ function main() {
|
||||
const packageRecipes =
|
||||
CraftManager.getPackageRecipe(packageDetailInfo);
|
||||
if (packageRecipes.isSome()) {
|
||||
if (packageIsFinal) recipesQueue.enqueue(packageRecipes.value);
|
||||
else recipesWaitingMap.set(packageOrderId, packageRecipes.value);
|
||||
if (packageIsFinal)
|
||||
recipesQueue.enqueue(packageRecipes.value);
|
||||
else
|
||||
recipesWaitingMap.set(
|
||||
packageOrderId,
|
||||
packageRecipes.value,
|
||||
);
|
||||
} else {
|
||||
if (packageIsFinal && recipesWaitingMap.has(packageOrderId)) {
|
||||
recipesQueue.enqueue(recipesWaitingMap.get(packageOrderId)!);
|
||||
if (
|
||||
packageIsFinal &&
|
||||
recipesWaitingMap.has(packageOrderId)
|
||||
) {
|
||||
recipesQueue.enqueue(
|
||||
recipesWaitingMap.get(packageOrderId)!,
|
||||
);
|
||||
recipesWaitingMap.delete(packageOrderId);
|
||||
} else {
|
||||
logger.debug(`No recipe, just pass`);
|
||||
@@ -166,7 +192,8 @@ function main() {
|
||||
});
|
||||
|
||||
if (craftCnt == 0) break;
|
||||
if (craftCnt < maxSignleCraftCnt) maxSignleCraftCnt = craftCnt;
|
||||
if (craftCnt < maxSignleCraftCnt)
|
||||
maxSignleCraftCnt = craftCnt;
|
||||
const craftRet = craftManager.craft(maxSignleCraftCnt);
|
||||
craftItemDetail ??= craftRet;
|
||||
logger.info(`Craft ${craftCnt} times`);
|
||||
|
||||
@@ -7,56 +7,16 @@
|
||||
|
||||
import {
|
||||
Logger,
|
||||
createDevLogger,
|
||||
createProdLogger,
|
||||
|
||||
// Processors
|
||||
addTimestamp,
|
||||
addFormattedTimestamp,
|
||||
addFullTimestamp,
|
||||
addSource,
|
||||
addComputerId,
|
||||
addStaticFields,
|
||||
transformField,
|
||||
|
||||
// Renderers
|
||||
textRenderer,
|
||||
jsonRenderer,
|
||||
|
||||
// Streams
|
||||
processor,
|
||||
ConsoleStream,
|
||||
FileStream,
|
||||
BufferStream,
|
||||
DAY,
|
||||
ConditionalStream,
|
||||
HOUR,
|
||||
jsonRenderer,
|
||||
LogLevel,
|
||||
textRenderer,
|
||||
} from "../lib/ccStructLog";
|
||||
import { ConditionalStream } from "@/lib/ccStructLog/streams";
|
||||
|
||||
// =============================================================================
|
||||
// Basic Usage Examples
|
||||
// =============================================================================
|
||||
|
||||
print("=== Basic Usage Examples ===");
|
||||
|
||||
// 1. Quick start with pre-configured loggers
|
||||
const devLog = createDevLogger();
|
||||
devLog.info("Application started", { version: "1.0.0", port: 8080 });
|
||||
devLog.debug("Debug information", { userId: 123, action: "login" });
|
||||
devLog.error("Something went wrong", {
|
||||
error: "Connection failed",
|
||||
retries: 3,
|
||||
});
|
||||
|
||||
// 2. Production logging to file
|
||||
const prodLog = createProdLogger("app.log", {
|
||||
source: "MyApplication",
|
||||
rotationInterval: DAY,
|
||||
includeConsole: true,
|
||||
});
|
||||
|
||||
prodLog.info("User action", { userId: 456, action: "purchase", amount: 29.99 });
|
||||
prodLog.warn("Low disk space", { available: 1024, threshold: 2048 });
|
||||
|
||||
// =============================================================================
|
||||
// Custom Logger Configurations
|
||||
@@ -67,10 +27,10 @@ print("\n=== Custom Logger Configurations ===");
|
||||
// 4. Custom logger with specific processors and renderer
|
||||
const customLogger = new Logger({
|
||||
processors: [
|
||||
addFullTimestamp(),
|
||||
addComputerId(),
|
||||
addSource("CustomApp"),
|
||||
addStaticFields({
|
||||
processor.addTimestamp(),
|
||||
processor.addComputerId(),
|
||||
processor.addSource("CustomApp"),
|
||||
processor.addStaticFields({
|
||||
environment: "development",
|
||||
version: "2.1.0",
|
||||
}),
|
||||
@@ -109,10 +69,10 @@ const sanitizePasswords = (event: Map<string, unknown>) => {
|
||||
|
||||
const secureLogger = new Logger({
|
||||
processors: [
|
||||
addTimestamp(),
|
||||
processor.addTimestamp(),
|
||||
addRequestId,
|
||||
sanitizePasswords,
|
||||
transformField("message", (msg) => `[SECURE] ${msg}`),
|
||||
processor.transformField("message", (msg) => `[SECURE] ${msg}`),
|
||||
],
|
||||
renderer: jsonRenderer,
|
||||
streams: [new ConsoleStream()],
|
||||
@@ -133,7 +93,7 @@ print("\n=== Stream Examples ===");
|
||||
// 11. Buffer stream for batch processing
|
||||
const bufferStream = new BufferStream(100); // Keep last 100 messages
|
||||
const bufferLogger = new Logger({
|
||||
processors: [addFormattedTimestamp()],
|
||||
processors: [processor.addTimestamp()],
|
||||
renderer: textRenderer,
|
||||
streams: [
|
||||
new ConditionalStream(new ConsoleStream(), (msg, event) => {
|
||||
@@ -162,7 +122,7 @@ for (const msg of bufferedMessages) {
|
||||
|
||||
// 12. Multi-stream with different formats
|
||||
const multiFormatLogger = new Logger({
|
||||
processors: [addFullTimestamp(), addComputerId()],
|
||||
processors: [processor.addTimestamp(), processor.addComputerId()],
|
||||
renderer: (event) => "default", // This won't be used
|
||||
streams: [
|
||||
// Console with human-readable format
|
||||
@@ -196,7 +156,7 @@ print("\n=== Error Handling Examples ===");
|
||||
// 13. Robust error handling
|
||||
const robustLogger = new Logger({
|
||||
processors: [
|
||||
addTimestamp(),
|
||||
processor.addTimestamp(),
|
||||
// Processor that might fail
|
||||
(event) => {
|
||||
try {
|
||||
@@ -231,7 +191,7 @@ print("\n=== Cleanup Examples ===");
|
||||
|
||||
// 14. Proper cleanup
|
||||
const fileLogger = new Logger({
|
||||
processors: [addTimestamp()],
|
||||
processors: [processor.addTimestamp()],
|
||||
renderer: jsonRenderer,
|
||||
streams: [new FileStream("temp.log")],
|
||||
});
|
||||
@@ -249,37 +209,3 @@ print("- all.log (complete log)");
|
||||
print("- debug.log (detailed debug info)");
|
||||
print("- structured.log (JSON format)");
|
||||
print("- temp.log (temporary file, now closed)");
|
||||
|
||||
// =============================================================================
|
||||
// Performance Comparison (commented out to avoid noise)
|
||||
// =============================================================================
|
||||
|
||||
/*
|
||||
print("\n=== Performance Comparison ===");
|
||||
|
||||
const iterations = 1000;
|
||||
|
||||
// Test simple console logging
|
||||
const startTime1 = os.clock();
|
||||
const simpleLogger = createMinimalLogger();
|
||||
for (let i = 0; i < iterations; i++) {
|
||||
simpleLogger.info(`Simple message ${i}`);
|
||||
}
|
||||
const endTime1 = os.clock();
|
||||
print(`Simple Console Logger: ${endTime1 - startTime1} seconds`);
|
||||
|
||||
// Test complex processor chain
|
||||
const startTime2 = os.clock();
|
||||
const complexLogger = createDetailedLogger("perf_test.log", {
|
||||
source: "PerfTest"
|
||||
});
|
||||
for (let i = 0; i < iterations; i++) {
|
||||
complexLogger.info(`Complex message ${i}`, {
|
||||
iteration: i,
|
||||
data: { nested: { value: i * 2 } }
|
||||
});
|
||||
}
|
||||
complexLogger.close();
|
||||
const endTime2 = os.clock();
|
||||
print(`Complex Processor Chain: ${endTime2 - startTime2} seconds`);
|
||||
*/
|
||||
|
||||
Reference in New Issue
Block a user