我们在写代码调试的时候,有时候需要打印es的query log 看下请求json到底长什么样。在new的时候我们需要传一个 实现了 elasticsearch 这个包 Logger 接口的结构体进来。
package DbBase
import (
"fmt"
"log"
"net"
"net/http"
"time"
"github.com/spf13/viper"
"gopkg.in/olivere/elastic.v5"
)
var esClient *elastic.Client
var err error
//tracelog 实现 elastic.Logger 接口
type tracelog struct{}
//实现输出
func (tracelog) Printf(format string, v ...interface{}) {
fmt.Printf(format, v...)
}
func InitEs() {
httpClient := &http.Client{}
httpClient.Transport = &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: 5 * time.Second,
KeepAlive: 30 * time.Second,
}).DialContext,
MaxIdleConns: 200,
MaxIdleConnsPerHost: 200,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
}
esClient, err = elastic.NewClient(
elastic.SetHttpClient(httpClient),
elastic.SetSniff(false),
elastic.SetURL(viper.GetString("es.weili.host")),
elastic.SetHealthcheck(false),
elastic.SetTraceLog(new(tracelog)), // 这一 必须的
)
if err != nil {
log.Fatalln(err)
}
}
func GetEs() *elastic.Client {
return esClient
}