I'm trying to develop an HTTP service in Ballerina. I need to add a correlation Id to each log entry printed in the service like mentioned in [1] for java. Is there any recommended approach to achieve this in ballerina?
[1] https://dzone.com/articles/correlation-id-for-logging-in-microservices
I was trying the following simple HTTP service.
import ballerina/http;
type Album readonly & record {|
string title;
string artist;
|};
table<Album> key(title) albums = table [
{title: "Blue Train", artist: "John Coltrane"},
{title: "Jeru", artist: "Gerry Mulligan"}
];
service / on new http:Listener(9090) {
resource function get albums() returns Album[] {
return albums.toArray();
}
}
You can implement a request interceptor to generate correlation Id from UUID generation for each request and put it into the http:RequestContext as a key-value pair. The
http:RequestContext
is available throughout the request life cycle. Hence whenever the logging is required, retrieve the correlation Id from thehttp:RequestContext
. You can addhttp:RequestContext
as resource function argument to any service type.