為 putty 添加保存log時寫入時間的功能


putty 幾乎是我用過的遠程工具里面的最好的了。目前感覺還有的缺憾有

缺少標簽頁切換
沒有命令窗口
log文件保存時沒有保存時間線的選項
今天來動手為putty增加在保存的log的前面打上時間標簽。

下載putty的源代碼,假設你把它解壓到putty這個文件夾內。我們主要更改以下幾個文件

  1. [putty\windows\winhelp.h](## winhelp.h)
  2. putty\putty.h
  3. putty\config.c
  4. putty\logging.c

UI上添加選項

winhelp.h

在 WINHELP_CTX_xxxxx 字段新增一條。這里我新增了一條

#define WINHELP_CTX_logging_timeheader "config-logtimeheader"

CTX 后面的 logging_timeheader 等下會用到。

putty.h

#define CONFIG_OPTIONS(X) \字段新增一條,這里我新增的是

X(BOOL, NONE, logtimeheader) \

位置大概是1389行。

config.c

位置大概 1667 行,仿造原有的代碼,添加一個checkbox。這里我寫成

ctrl_checkbox(s, "Include time header of line", 'j',HELPCTX(logging_timeheader),conf_checkbox_handler, I(CONF_logtimeheader));

上面的代碼中,HELPCTX(logging_timeheader) 里面的 logging_timeheader 是在 putty\windows\winhelp.h 新增的條目。
I(CONF_logtimeheader)中的 logtimeheader是在 putty\putty.h 中新增的條目。

功能實現

這一步的主邏輯是在 putty\logging.c 這個文件內添加的。修改位置為大概 54 行。static void logwrite(LogContext *ctx, ptrlen data) 這個函數體內。修改后如下所示

static void logwrite(LogContext *ctx, ptrlen data)
{
    /*
     * In state L_CLOSED, we call logfopen, which will set the state
     * to one of L_OPENING, L_OPEN or L_ERROR. Hence we process all of
     * those three _after_ processing L_CLOSED.
     */
    if (ctx->state == L_CLOSED)
        logfopen(ctx);

    if (ctx->state == L_OPENING) {
        bufchain_add(&ctx->queue, data.ptr, data.len);
    } else if (ctx->state == L_OPEN) {
        assert(ctx->lgfp);
        if (fwrite(data.ptr, 1, data.len, ctx->lgfp) < data.len) {
            logfclose(ctx);
            ctx->state = L_ERROR;
            lp_eventlog(ctx->lp, "Disabled writing session log "
                "due to error while writing");
        }
        /************** 新增開始 **************/
        if ((strcmp(data.ptr, "\n") == 0) && (conf_get_bool(ctx->conf, CONF_logtimeheader))) {
            char buf[256];
            struct tm tm;
            tm = ltime();
            strftime(buf, 24, "%Y.%m.%d %H:%M:%S   ", &tm);
            fwrite(buf, 1, strlen(buf), ctx->lgfp);
        }
        /*************** 新增結束 *************/
    }   /* else L_ERROR, so ignore the write */
}

logwrite 這個函數是用來將putty窗口內顯示的字符輸出到log文件內的。
如果調用這個函數的地方是一行一行傳進來的的話,修改的地方應該是在調用這個函數的地方。但是根據調用的情況來看,多數情況下是一個字符一個字符寫的。
所以我的做法是檢查到輸出的字符是 \n 時,就輸出一個時間,這樣下一行再輸出的內容就是跟在這個時間后面的。
最后實現的效果大概是下面這個樣子

轉載請注明來源 https://bdznh.github.io/2020/06/21/add-new-config-into-putty/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM