Scenario:
Sign on service is a Unary Grpc server on in .Net core 3.0 which allows creation of users in our app. Server should start logging api context and artifacts data to ELK for logging and references.
Solution:
Use Grpc service interceptor to intercept the api calls and log the required data.
- VS 2019 -> Grpc server Project -> add ServicesInterceptor.cs
- Add below code in interceptor code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
| public class ServicesInterceptor: Interceptor
{
private readonly ILogger<ServicesInterceptor> _logger;
private readonly IElasticSearch _elasticSearch;
public ServicesInterceptor(ILogger<ServicesInterceptor> logger, IElasticSearch elasticSearch)
{
_logger = logger;
_elasticSearch = elasticSearch;
}
public override async Task<TResponse> UnaryServerHandler<TRequest, TResponse>(TRequest request, ServerCallContext context, UnaryServerMethod<TRequest, TResponse> continuation)
{
var sw = Stopwatch.StartNew();
var response = await base.UnaryServerHandler(request, context, continuation);
LogCall<TRequest, TResponse>(MethodType.Unary, context, JsonConvert.SerializeObject(request), JsonConvert.SerializeObject(response), sw.Elapsed.TotalMilliseconds);
sw.Stop();
return response;
}
private void LogCall<TRequest, TResponse>(MethodType methodType, ServerCallContext context, string request, string response, double duration) where TRequest: class where TResponse: class
{
var esApiLog = new GrpcElasticApiLogModel
{
RequestType = typeof(TRequest).Name,
MethodType = methodType.ToString(),
Request = request,
Response = response,
Duration = duration,
Server = context.Host
};
var json = JsonConvert.SerializeObject(esApiLog);
_elasticSearch.PostData(json, "ELK:indexes:webApiIndex");
}
}
|
- In startup.cs under in ConfigureServices method register the interceptor and elastic service
1
2
3
4
5
6
7
8
9
| public void ConfigureServices(IServiceCollection services)
{
services.AddGrpc(options =>
{
options.Interceptors.Add<ServicesInterceptor>();
});
services.AddSingleton<IElasticSearch, ElasticSearchService>();
}
|
Output:
Log entry in ELK
1
2
3
4
5
6
7
8
9
10
11
12
13
| {
"_index" : "log-webapi",
"_type" : "documents",
"_id" : "4BrQ2G8Bf2bSL1EXGEgL",
"_score" : 1.0,
"_source" : {
"MethodType" : "Unary",
"RequestType" : "SignOnRequest",
"Request" : """{"Email":"test@test.com","Name":"Test User","Password":"=dsdsdrt99"}""",
"Response" : """{"Sucess":true,"Name":"Test User"}""",
"Duration" : 3237.8186,
"Server" : "localhost:5001"
}
|
No comments:
Post a Comment