index.ts•2.78 kB
import { ToolDefinition, ToolResponse } from '../types.js';
import { Config } from '../../config/config.js';
import fs from 'fs';
import path from 'path';
// 日志工具类
class LoggerManager {
private logDir: string;
constructor(
private readonly config: Config
) {
// 使用当前目录下的 log 目录
this.logDir = path.join(process.cwd(), 'log');
// 确保日志目录存在
if (!fs.existsSync(this.logDir)) {
fs.mkdirSync(this.logDir, { recursive: true });
}
}
private getLogFileName(): string {
const now = new Date();
return path.join(
this.logDir,
`${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}.log`
);
}
private formatLogMessage(level: string, message: string): string {
const now = new Date();
const workDir = process.cwd();
return `[${level.toUpperCase()}] ${now.toISOString()} [${workDir}] - ${message}\n`;
}
private async writeLog(level: string, message: string): Promise<void> {
// 确保日志目录存在
if (!fs.existsSync(this.logDir)) {
await fs.promises.mkdir(this.logDir, { recursive: true });
}
const logFile = this.getLogFileName();
const logMessage = this.formatLogMessage(level, message);
await fs.promises.appendFile(logFile, logMessage, 'utf8');
}
// 日志工具处理器
async loggerHandler(args: { level: string; message: string }): Promise<ToolResponse> {
try {
await this.writeLog(args.level, args.message);
const timestamp = new Date().toISOString();
const workDir = process.cwd();
return {
content: [{
type: 'text',
text: `日志已写入: [${args.level.toUpperCase()}] ${timestamp} [${workDir}] - ${args.message}`
}]
};
} catch (error) {
return {
content: [{
type: 'text',
text: error instanceof Error ? error.message : String(error)
}],
isError: true
};
}
}
// 清理资源
dispose(): void {
// 不需要清理资源
}
}
// 创建日志工具
export function createLoggerTools(
config: Config
): ToolDefinition[] {
const manager = new LoggerManager(config);
return [{
name: 'logger',
description: '写入日志到当前工作目录的log目录下,按日期分文件存储',
inputSchema: {
type: 'object',
properties: {
level: {
type: 'string',
enum: ['info', 'warn', 'error'],
description: '日志级别'
},
message: {
type: 'string',
description: '日志消息'
}
},
required: ['level', 'message']
},
handler: args => manager.loggerHandler(args)
}];
}