ELK Integration with Back End application
WEB API -
- Install package Elastic.Apm.NetCoreAll [Ref: https://www.nuget.org/packages/Elastic.Apm.NetCoreAll]
- Update the appsettings.json file adding the following configuration to accommodate Elastic APM integration:
"SecretToken": "apm-server-secret-token",
"ServerUrls": "http://ec2-32-75-437-265.ap-southeast-2.compute.amazonaws.com:8200",
"ServiceName": "Your_API" //allowed characters: a-z, A-Z, 0-9, -, _, and space. Default is the entry assembly of the application
}
SecretToken - APM server secret token.
ServerUrls - This is the server URL where the ELK is setup and the metrics data will be pushed.
ServiceName - This is the name of the service which is sending the metric data. It will be used in the ELK server APM module as shown in the screenshot below:
Windows Service (.NET Core)
- Install package Elastic.Apm [Ref: https://www.nuget.org/packages/Elastic.Apm]
- Install package Elastic.Apm.EntityFrameworkCore [Ref: https://www.nuget.org/packages/Elastic.Apm.EntityFrameworkCore]
- Public API mechanism is used for capturing the APM metrics in case of Windows service.
- Copy the following code and paste it at the starting of the method from where you want to start capturing the metrics. Provide the values of the data marked in BOLD as per your service.
Environment.SetEnvironmentVariable("ELASTIC_APM_SECRET_TOKEN", "your secret token");
Environment.SetEnvironmentVariable("ELASTIC_APM_SERVER_URLS", "elastic server url");
Environment.SetEnvironmentVariable("ELASTIC_APM_SERVICE_NAME", "YourServiceName");
Agent.Subscribe(new EfCoreDiagnosticsSubscriber());
var outgoingDistributedTracingData = (Agent.Tracer.CurrentSpan?.OutgoingDistributedTracingData ?? Agent.Tracer.CurrentTransaction?.OutgoingDistributedTracingData)?.SerializeToString();
var transaction = Agent.Tracer.StartTransaction("YourServiceTransactionName", ApiConstants.ActionExec, DistributedTracingData.TryDeserializeFromString(outgoingDistributedTracingData));
try
{
Process();
}
catch(Exception ex)
{
transaction.CaptureException(ex);
}
finally
{
transaction.End();
}
- Agent.Subscribe(new EfCoreDiagnosticsSubscriber()); - It allows you to capture the EF core metrics and you have to provision it separately in case of Windows Service.
- Process() - It is the method you want to send metric data for.
- transaction.CaptureException(ex) - This allows to capture the errors and send it to the APM server.
- transaction.End() - It is required to end the transaction.
Once it will be done then on running the service it will start sending data to APM server