-
Notifications
You must be signed in to change notification settings - Fork 3k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat(logging): add option to log slow GraphQL queries #11308
Merged
david-leifker
merged 2 commits into
datahub-project:master
from
nmbryant:graphql-verbose-logging
Sep 10, 2024
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -9,12 +9,15 @@ | |
import akka.util.ByteString; | ||
import auth.Authenticator; | ||
import com.datahub.authentication.AuthenticationConstants; | ||
import com.fasterxml.jackson.databind.JsonNode; | ||
import com.fasterxml.jackson.databind.ObjectMapper; | ||
import com.fasterxml.jackson.databind.node.ObjectNode; | ||
import com.linkedin.util.Pair; | ||
import com.typesafe.config.Config; | ||
import java.io.InputStream; | ||
import java.net.URI; | ||
import java.time.Duration; | ||
import java.time.Instant; | ||
import java.util.List; | ||
import java.util.Map; | ||
import java.util.Optional; | ||
|
@@ -33,6 +36,7 @@ | |
import play.libs.ws.StandaloneWSClient; | ||
import play.libs.ws.ahc.StandaloneAhcWSClient; | ||
import play.mvc.Controller; | ||
import play.mvc.Http.Cookie; | ||
import play.mvc.Http; | ||
import play.mvc.ResponseHeader; | ||
import play.mvc.Result; | ||
|
@@ -132,6 +136,9 @@ public CompletableFuture<Result> proxy(String path, Http.Request request) | |
headers.put(Http.HeaderNames.X_FORWARDED_PROTO, List.of(schema)); | ||
} | ||
|
||
// Get the current time to measure the duration of the request | ||
Instant start = Instant.now(); | ||
|
||
return _ws.url( | ||
String.format( | ||
"%s://%s:%s%s", protocol, metadataServiceHost, metadataServicePort, resolvedUri)) | ||
|
@@ -160,6 +167,15 @@ AuthenticationConstants.LEGACY_X_DATAHUB_ACTOR_HEADER, getDataHubActorHeader(req | |
.execute() | ||
.thenApply( | ||
apiResponse -> { | ||
// Log the query if it takes longer than the configured threshold and verbose logging is enabled | ||
boolean verboseGraphQLLogging = _config.getBoolean("graphql.verbose.logging"); | ||
int verboseGraphQLLongQueryMillis = _config.getInt("graphql.verbose.slowQueryMillis"); | ||
Instant finish = Instant.now(); | ||
long timeElapsed = Duration.between(start, finish).toMillis(); | ||
if (verboseGraphQLLogging && timeElapsed >= verboseGraphQLLongQueryMillis) { | ||
logSlowQuery(request, resolvedUri, timeElapsed); | ||
} | ||
|
||
final ResponseHeader header = | ||
new ResponseHeader( | ||
apiResponse.getStatus(), | ||
|
@@ -359,4 +375,34 @@ private String mapPath(@Nonnull final String path) { | |
// Otherwise, return original path | ||
return path; | ||
} | ||
|
||
|
||
/** | ||
* Called if verbose logging is enabled and request takes longer that the slow query milliseconds defined in the config | ||
* @param request GraphQL request that was made | ||
* @param resolvedUri URI that was requested | ||
* @param duration How long the query took to complete | ||
*/ | ||
private void logSlowQuery(Http.Request request, String resolvedUri, float duration) { | ||
StringBuilder jsonBody = new StringBuilder(); | ||
Optional<Cookie> actorCookie = request.getCookie("actor"); | ||
String actorValue = actorCookie.isPresent() ? actorCookie.get().value() : "N/A"; | ||
|
||
try { | ||
ObjectMapper mapper = new ObjectMapper(); | ||
JsonNode jsonNode = request.body().asJson(); | ||
((ObjectNode) jsonNode).remove("query"); | ||
jsonBody.append(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonNode)); | ||
} | ||
catch (Exception e) { | ||
_logger.info("GraphQL Request Received: {}, Unable to parse JSON body", resolvedUri); | ||
} | ||
String jsonBodyStr = jsonBody.toString(); | ||
_logger.info("Slow GraphQL Request Received: {}, Request query string: {}, Request actor: {}, Request JSON: {}, Request completed in {} ms", | ||
resolvedUri, | ||
request.queryString(), | ||
actorValue, | ||
jsonBodyStr, | ||
duration); | ||
} | ||
Comment on lines
+381
to
+407
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Review: The method implementation for logging slow GraphQL queries is mostly correct. However, there are a few areas of improvement:
Consider the following improvements:
if (jsonNode != null && jsonNode.isObject()) {
((ObjectNode) jsonNode).remove("query");
}
catch (IOException e) {
_logger.info("GraphQL Request Received: {}, Unable to parse JSON body due to IO issues", resolvedUri, e);
}
_logger.info("Slow GraphQL Request Received: URI={}, QueryString={}, Actor={}, JSON={}, Duration={} ms",
resolvedUri, request.queryString(), actorValue, jsonBodyStr, duration); |
||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Review: Logging slow GraphQL queries.
The implementation correctly checks if verbose logging is enabled and if the query duration exceeds the threshold before logging. However, consider adding error handling for potential exceptions when accessing configuration values.
Consider adding a try-catch block around the configuration access to handle possible
ConfigException
: