1

github.com/Shopify/sarama我正在尝试为 configure's的功能选项编写单元测试Logger。像这样使用 Kafka 运行 Docker 容器后,

docker run -p 2181:2181 -p 9092:9092 -e ADVERTISED_HOST=127.0.0.1  -e NUM_PARTITIONS=10 johnnypark/kafka-zookeeper

我正在尝试运行这个程序:

package main

import (
    "bufio"
    "bytes"
    "io/ioutil"
    "log"

    "github.com/Shopify/sarama"
)

func main() {
    var b bytes.Buffer
    out := bufio.NewWriter(&b)

    sarama.Logger = log.New(out, "[Sarama] ", log.LstdFlags)

    if _, err := sarama.NewClient([]string{"localhost:9092"}, sarama.NewConfig()); err != nil {
        log.Fatalln("NewClient:", err)
    }

    output, err := ioutil.ReadAll(&b)
    if err != nil {
        log.Fatalln("ReadAll:", err)
    }

    log.Printf("output: %s", output)
}

我希望看到一些输出。但是,打印输出为空:

> go run main.go
2020/09/25 16:44:58 output: 

相比之下,如果我将输出设置os.Stderr

package main

import (
    "log"
    "os"

    "github.com/Shopify/sarama"
)

func main() {
    sarama.Logger = log.New(os.Stderr, "[Sarama] ", log.LstdFlags)

    if _, err := sarama.NewClient([]string{"localhost:9092"}, sarama.NewConfig()); err != nil {
        log.Fatalln("NewClient:", err)
    }
}

我看到打印到终端的预期输出:

> go run main.go
[Sarama] 2020/09/25 16:46:04 Initializing new client
[Sarama] 2020/09/25 16:46:04 ClientID is the default of 'sarama', you should consider setting it to something application-specific.
[Sarama] 2020/09/25 16:46:04 ClientID is the default of 'sarama', you should consider setting it to something application-specific.
[Sarama] 2020/09/25 16:46:04 client/metadata fetching metadata for all topics from broker localhost:9092
[Sarama] 2020/09/25 16:46:04 Connected to broker at localhost:9092 (unregistered)
[Sarama] 2020/09/25 16:46:04 client/brokers registered new broker #0 at 127.0.0.1:9092
[Sarama] 2020/09/25 16:46:04 Successfully initialized new client

似乎*bytes.Buffer没有被“冲走” ioutil.ReadAll()?如何修复前面的示例,使其output不为空?

4

1 回答 1

1

原来我只需要打电话

out.Flush()

之前ioutil.ReadAll()。现在输出如预期:

> go run main.go
2020/09/25 16:58:26 output: [Sarama] 2020/09/25 16:58:26 Initializing new client
[Sarama] 2020/09/25 16:58:26 ClientID is the default of 'sarama', you should consider setting it to something application-specific.
[Sarama] 2020/09/25 16:58:26 ClientID is the default of 'sarama', you should consider setting it to something application-specific.
[Sarama] 2020/09/25 16:58:26 client/metadata fetching metadata for all topics from broker localhost:9092
[Sarama] 2020/09/25 16:58:26 Connected to broker at localhost:9092 (unregistered)
[Sarama] 2020/09/25 16:58:26 client/brokers registered new broker #0 at 127.0.0.1:9092
[Sarama] 2020/09/25 16:58:26 Successfully initialized new client
于 2020-09-25T23:59:42.830 回答