douzhi19900102 2017-05-24 16:39
浏览 44
已采纳

os.Pipe无法与日志包一起正常工作

I have a piece of code which sets up an os.Pipe to capture Stdout/Stderr:

https://github.com/sevagh/stdcap/blob/master/stdcap.go

// Capture executes f() and returns the captured data
func (s *stdcap) Capture(f func()) string {
    s.mu.Lock()
    defer s.mu.Unlock()

    var old, r, w *os.File

    if s.out {
        old = os.Stdout
        r, w, _ = os.Pipe()
        os.Stdout = w
    } else {
        old = os.Stderr
        r, w, _ = os.Pipe()
        os.Stderr = w
    }

    f()

    outC := make(chan string)
    defer close(outC)

    go func() {
        var buf bytes.Buffer
        io.Copy(&buf, r)
        outC <- buf.String()
    }()

    w.Close()

    if s.out {
        os.Stdout = old
    } else {
        os.Stderr = old
    }

    return <-outC
}

Today I tried using this code with the log package and it doesn't work.

This works:

func TestOutCapture(t *testing.T) {
    sc := StdoutCapture()
    out := sc.Capture(func() {
        fmt.Printf("Hello world!")
    })

    if out != "Hello world!" {
        t.Errorf("Expected \"Hello world!\", got: %s
", out)
    }
}

func TestErrCapture(t *testing.T) {
    sc := StderrCapture()
    err := sc.Capture(func() {
        fmt.Fprintf(os.Stderr, "Hello world!")
    })

    if err != "Hello world!" {
        t.Errorf("Expected \"Hello world!\", got: %s
", err)
    }
}

These don't work:

func TestLogOutCapture(t *testing.T) {
    sc := StdoutCapture()

    log.SetOutput(os.Stdout)
    out := sc.Capture(func() {
        log.Printf("Hello world!")
    })

    if out != "Hello world!" {
        t.Errorf("Expected \"Hello world!\", got: %s
", out)
    }
}

func TestLogErrCapture(t *testing.T) {
    sc := StderrCapture()
    log.SetOutput(os.Stderr)

    err := sc.Capture(func() {
        log.Printf("Hello world!")
    })

    if err != "Hello world!" {
        t.Errorf("Expected \"Hello world!\", got: %s
", err)
    }
}

Any ideas on where I can debug this? Does the Golang log package not use os.Stdout/os.Stderr?

  • 写回答

1条回答 默认 最新

  • duan6301 2017-05-24 16:44
    关注

    The logging package initializes the standard logger with the value os.Stderr at initialization time. Modifications to the variable os.Stderr do not change the value in the logger field.

    Call log.SetOutput to change the output location for the standard logger from your capture function. Unfortunately, there's not a way to get standard logger's output so you can save and restore it in your capture function.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用