relese v1.0.34 to optimize the log

This commit is contained in:
musistudio
2025-08-10 21:37:48 +08:00
parent 6510d3aac9
commit b856e1e11b
7 changed files with 106 additions and 15 deletions

View File

@@ -1,8 +1,8 @@
import { existsSync } from "fs";
import { writeFile } from "fs/promises";
import { homedir } from "os";
import { join } from "path";
import { initConfig, initDir } from "./utils";
import path, { join } from "path";
import { initConfig, initDir, cleanupLogFiles } from "./utils";
import { createServer } from "./server";
import { router } from "./utils/router";
import { apiKeyAuth } from "./middleware/auth";
@@ -12,6 +12,8 @@ import {
savePid,
} from "./utils/processCheck";
import { CONFIG_FILE } from "./constants";
import createWriteStream from "pino-rotating-file-stream";
import { HOME_DIR } from "./constants";
async function initializeClaudeConfig() {
const homeDir = homedir();
@@ -46,14 +48,14 @@ async function run(options: RunOptions = {}) {
await initializeClaudeConfig();
await initDir();
// Clean up old log files, keeping only the 10 most recent ones
await cleanupLogFiles();
const config = await initConfig();
let HOST = config.HOST;
if (config.HOST && !config.APIKEY) {
HOST = "127.0.0.1";
console.warn(
"⚠️ API key is not set. HOST is forced to 127.0.0.1."
);
console.warn("⚠️ API key is not set. HOST is forced to 127.0.0.1.");
}
const port = config.PORT || 3456;
@@ -73,12 +75,15 @@ async function run(options: RunOptions = {}) {
cleanupPidFile();
process.exit(0);
});
console.log(HOST)
console.log(HOST);
// Use port from environment variable if set (for background process)
const servicePort = process.env.SERVICE_PORT
? parseInt(process.env.SERVICE_PORT)
: port;
const startTime = new Date().toISOString();
const server = createServer({
jsonPath: CONFIG_FILE,
initialConfig: {
@@ -92,6 +97,15 @@ async function run(options: RunOptions = {}) {
"claude-code-router.log"
),
},
logger: {
level: "debug",
stream: createWriteStream({
path: HOME_DIR,
filename: `./logs/ccr-${startTime}.log`,
maxFiles: 3,
interval: "1d",
}),
},
});
// Add async preHandler hook for authentication
server.addHook("preHandler", async (req, reply) => {
@@ -105,8 +119,8 @@ async function run(options: RunOptions = {}) {
});
});
server.addHook("preHandler", async (req, reply) => {
if(req.url.startsWith("/v1/messages")) {
router(req, reply, config)
if (req.url.startsWith("/v1/messages")) {
router(req, reply, config);
}
});
server.start();

View File

@@ -9,6 +9,7 @@ import {
PLUGINS_DIR,
} from "../constants";
import { getSystemUUID, generateTempAPIKey, getTempAPIKey } from "./systemUUID";
import { cleanupLogFiles } from "./logCleanup";
const ensureDir = async (dir_path: string) => {
try {
@@ -139,3 +140,6 @@ export const initConfig = async () => {
// 导出系统UUID相关函数
export { getSystemUUID, generateTempAPIKey, getTempAPIKey };
// 导出日志清理函数
export { cleanupLogFiles };

44
src/utils/logCleanup.ts Normal file
View File

@@ -0,0 +1,44 @@
import fs from "node:fs/promises";
import path from "node:path";
import { HOME_DIR } from "../constants";
/**
* Cleans up old log files, keeping only the most recent ones
* @param maxFiles - Maximum number of log files to keep (default: 9)
*/
export async function cleanupLogFiles(maxFiles: number = 9): Promise<void> {
try {
const logsDir = path.join(HOME_DIR, "logs");
// Check if logs directory exists
try {
await fs.access(logsDir);
} catch {
// Logs directory doesn't exist, nothing to clean up
return;
}
// Read all files in the logs directory
const files = await fs.readdir(logsDir);
// Filter for log files (files starting with 'ccr-' and ending with '.log')
const logFiles = files
.filter(file => file.startsWith('ccr-') && file.endsWith('.log'))
.sort()
.reverse(); // Sort in descending order (newest first)
// Delete files exceeding the maxFiles limit
if (logFiles.length > maxFiles) {
for (let i = maxFiles; i < logFiles.length; i++) {
const filePath = path.join(logsDir, logFiles[i]);
try {
await fs.unlink(filePath);
} catch (error) {
console.warn(`Failed to delete log file ${filePath}:`, error);
}
}
}
} catch (error) {
console.warn("Failed to clean up log files:", error);
}
}