網站搜尋

typescript - 為 VSCode 擴充功能建立日誌檔


在 VSCode 擴展中,將日誌語句寫入 檔案 的標準方法是什麼?

我覺得有某種範式在起作用,而我卻沒有注意到……我可以找到很多方法來讓控制台日誌對調試我的擴展更有用(Channels,像 typescript-logging 這樣的庫),但我沒有看到任何為我的擴展創建日誌文件的方法。

這不是一個常見的做法嗎?如果我的擴充功能的使用者遇到問題,對他們來說,最簡單的方式將診斷資訊傳給我,是不是透過打開開發者工具看到的控制台日誌來保存?

感謝任何建議

答案#1

對於那些試圖解決相同問題並尋找建議的人,我最終選擇了 winston.js,它為 TypeScript 提供了類型。

我定義了一個日誌記錄器如下:

const logger: winston.Logger = winston.createLogger({
level: 'debug',
format: winston.format.combine(
    winston.format.simple(),
    winston.format.timestamp({
        format: 'YYYY-MM-DD HH:mm:ss'
    }),
    winston.format.printf(info => `${info.timestamp} ${info.level}: ${info.message}`)
),
transports: [
    new winston.transports.File({
        level: 'info',
        dirname: logFileDir,
        filename: logFileName
    }),
    new winston.transports.File({
        level: 'debug',
        dirname: logFileDir,
        filename: debugLogFileName
    }),
]
});
export logger;

然後就能在我的程式碼其他地方呼叫 logger.info("whatever"),並將其寫入指定的日誌檔案。

你也可以讓日誌寫入控制台,方法是添加一個 Console 傳輸,但要注意這個錯誤會導致日誌無法顯示在 VSCode 的「Debug Console」中。這個解決方法對我解決了這個問題。

答案#2

你不一定需要第三方庫。你可以直接透過 window.createOutputChannel() 創建一個 LogOutputChannel。

import { window } from 'vscode';
const logger = window.createOutputChannel('My extension', {log: true});

然後按以下方式使用它:

// from low to high log-level, "Info" is default
logger.trace("Trace");
logger.debug("Debug");
logger.info("Info");
logger.warn("Warn");
logger.error("Error");

請注意,logger.logLevel 是唯讀屬性。使用者可以透過命令 Developer: Set Log Level... 來設定它,預設為 Info。請參考可用的 LogLevel。


你也可能想要註冊一個命令,讓使用者可以直接一鍵打開你的日誌檔案:

const openLogFileCommand = vscode.commands.registerCommand('my-extension.openLogFile', async () => {
    // loggerName is the name you've passed in to `createOutputChannel()`
    const logFilePath = vscode.Uri.joinPath(context.logUri, `${loggerName}.log`);
    vscode.window.withProgress({
        location: vscode.ProgressLocation.Notification,
        title: "Opening log file...",
        cancellable: false
    }, async (progressIndicator, token) => {
        await new Promise<void>(async (resolve) => {
            try {
                const doc = await vscode.workspace.openTextDocument(logFilePath);
                await vscode.window.showTextDocument(doc);
            } catch {
                vscode.window.showErrorMessage("Could not open Manim Notebook log file");
            } finally {
                resolve();
            }
        });
    });
});

此外,如果您需要更多自訂,還有 logUri:

擴充功能可以建立日誌檔案的目錄的 URI。該目錄在磁碟上可能不存在,建立由擴充功能決定。然而,父目錄保證是存在的。

所以在這裡你可以做任何你想做的事情,例如使用其他程式庫來創建自訂的日誌文件。但我猜在大多數情況下,createOutputChannel() 應該已經足夠強大了。