Skip to content

Elasticsearch.Net(NEST) 设置保留请求和回复Body,并在请求结束后回调

L edited this page Nov 17, 2021 · 1 revision
IElasticClient ElasticClient = new ElasticClient(new ConnectionSettings(new Uri($"ElasticsearchEndPoint"))
    //打印请求、回复,可能影响性能
    .DisableDirectStreaming()
    .OnRequestCompleted(apiCallDetails => 
{
    if (apiCallDetails.Success)
    {
#if DEBUG
        string infos = GetInfosFromApiCallDetails(apiCallDetails);
        Console.WriteLine(infos);
#endif
    }
    else
    {
        string infos = GetInfosFromApiCallDetails(apiCallDetails);
        Console.WriteLine(infos);
    }
}));

private static string GetInfosFromApiCallDetails(IApiCallDetails r)
{
    string infos = "";
    infos += $"Uri:\n{r.Uri}\n";
    infos += $"Success:\n{r.Success}\n";
    infos += $"SuccessOrKnownError:\n{r.SuccessOrKnownError}\n";
    infos += $"HttpMethod:\n{r.HttpMethod}\n";
    infos += $"HttpStatusCode:\n{r.HttpStatusCode}\n";
    infos += $"DebugInformation:\n{r.DebugInformation}\n";
    foreach (var deprecationWarning in r.DeprecationWarnings)
        infos += $"DeprecationWarnings:\n{deprecationWarning}\n";
    if (r.OriginalException != null)
    {
        infos += $"OriginalException.GetMessage:\n{ExceptionHelper.GetMessage(r.OriginalException)}\n";
        infos += $"OriginalException.GetStackTrace:\n{ExceptionHelper.GetStackTrace(r.OriginalException)}\n";
    }
    if (r.RequestBodyInBytes != null)
        infos += $"RequestBody:\n{Encoding.UTF8.GetString(r.RequestBodyInBytes)}\n";
    if (r.ResponseBodyInBytes != null)
        infos += $"ResponseBody:\n{Encoding.UTF8.GetString(r.ResponseBodyInBytes)}\n";
    infos += $"ResponseMimeType:\n{r.ResponseMimeType}\n";
    return infos;
}

输出结果如下:

Uri:
http://xxxxxxxxx:9200/indexname/_search?typed_keys=true
Success:
True
SuccessOrKnownError:
True
HttpMethod:
POST
HttpStatusCode:
200
DebugInformation:
Successful (200) low level call on POST: /indexname/_search?typed_keys=true
# Audit trail of this API call:
 - [1] HealthyResponse: Node: http://xxxxxxxxx:9200/ Took: 00:00:00.2758133
# Request:
{"from":0,"size":100,"sort":[{".....":{"order":"asc"}}]}
# Response:
.......

RequestBody:
{"from":0,"size":100,"sort":[{".....":{"order":"asc"}}]}
ResponseBody:
.......
ResponseMimeType:
application/json

参考资料

Get raw query from NEST client

Clone this wiki locally