项目文件夹

文件
Nikolay Vitkov bf0574da8c refactor: change type of logger (#2165)
This change aligns most of our logger allowing them to be omitted when
needed meaning code inside the args will not be executed unconditionally
- example `logger?.(JSON.stringy(X))`.

Currently only changes the type, while in a follow up I will remove the
`debug` package and update the file logs.
2026-06-02 09:29:48 +00:00

49 行
1.2 KiB
TypeScript

/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import fs from 'node:fs';
import {debug} from './third_party/index.js';
import type {Logger} from './types.js';
const mcpDebugNamespace = 'mcp:log';
const namespacesToEnable = [
mcpDebugNamespace,
...(process.env['DEBUG'] ? [process.env['DEBUG']] : []),
];
export function saveLogsToFile(fileName: string): fs.WriteStream {
// Enable overrides everything so we need to add them
debug.enable(namespacesToEnable.join(','));
const logFile = fs.createWriteStream(fileName, {flags: 'a+'});
debug.log = function (...chunks: any[]) {
logFile.write(`${chunks.join(' ')}\n`);
};
logFile.on('error', function (error) {
console.error(`Error when opening/writing to log file: ${error.message}`);
logFile.end();
process.exit(1);
});
return logFile;
}
export function flushLogs(
logFile: fs.WriteStream,
timeoutMs = 2000,
): Promise<void> {
return new Promise((resolve, reject) => {
const timeout = setTimeout(reject, timeoutMs);
logFile.end(() => {
clearTimeout(timeout);
resolve();
});
});
}
export const logger: Logger = debug(mcpDebugNamespace) as Logger;