Skip to content
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

Conversation

nmbryant
Copy link
Contributor

@nmbryant nmbryant commented Sep 5, 2024

Is this something that is wanted upstream? We added this option to log slow GraphQL queries so that we could find which queries need to be optimized or pages that could potentially cause issues.

Checklist

  • The PR conforms to DataHub's Contributing Guideline (particularly Commit Message Format)
  • Links to related issues (if applicable)
  • Tests for the changes have been added/updated (if applicable)
  • Docs related to the changes have been added/updated (if applicable). If a new feature has been added a Usage Guide has been added for the same.
  • For any breaking change/potential downtime/deprecation/big changes an entry has been made in Updating DataHub

Summary by CodeRabbit

  • New Features

    • Introduced enhanced logging for GraphQL requests, including the ability to log slow queries.
    • Added configuration options for verbose logging and slow query thresholds, improving monitoring capabilities.
  • Bug Fixes

    • Improved performance measurement for GraphQL requests, helping to identify potential bottlenecks.
  • Documentation

    • Updated configuration settings for better clarity on logging behavior and performance monitoring.

Copy link
Contributor

coderabbitai bot commented Sep 5, 2024

Walkthrough

The changes introduce enhancements to the Application.java file for improved logging and performance measurement of GraphQL requests. A new method for logging slow queries is added, and the request handling logic is updated to measure execution time. Additionally, the configuration file application.conf is updated with new settings for verbose logging and slow query thresholds, enhancing the application's logging capabilities.

Changes

Files Change Summary
datahub-frontend/app/controllers/Application.java Added a new method logSlowQuery for logging slow GraphQL requests and modified the proxy method to measure request duration.
datahub-frontend/conf/application.conf Introduced new settings for GraphQL logging, including graphql.verbose.logging and graphql.verbose.slowQueryMillis, while clarifying existing settings.

Poem

In the meadow where I hop and play,
New logs and metrics brighten my day.
With queries slow, we’ll catch the trail,
And hop along, we shall not fail!
🐇✨


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@github-actions github-actions bot added product PR or Issue related to the DataHub UI/UX community-contribution PR or Issue raised by member(s) of DataHub Community labels Sep 5, 2024
@nmbryant
Copy link
Contributor Author

nmbryant commented Sep 5, 2024

@coderabbitai review

Copy link
Contributor

coderabbitai bot commented Sep 5, 2024

Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 59f9a4b and e7f3e77.

Files selected for processing (2)
  • datahub-frontend/app/controllers/Application.java (5 hunks)
  • datahub-frontend/conf/application.conf (1 hunks)
Additional comments not posted (5)
datahub-frontend/conf/application.conf (2)

303-307: Review of New GraphQL Logging Configuration

The new settings introduced for logging slow GraphQL queries (graphql.verbose.logging and graphql.verbose.slowQueryMillis) are well-defined and follow the existing configuration pattern. These settings allow for toggling verbose logging and defining a threshold for what constitutes a slow query, which aligns with the PR's objectives to enhance performance monitoring.

  • Correctness: The syntax for setting and overriding with environment variables is correct.
  • Maintainability: Using environment variables (${?GRAPHQL_VERBOSE_LOGGING} and ${?GRAPHQL_VERBOSE_LONG_QUERY_MILLIS}) for these settings enhances configurability and maintainability, allowing different environments to easily override these values without code changes.

301-301: Review of Unchanged Entity Client Setting

The explicit definition of entityClient.restli.get.batchConcurrency with a fallback to an environment variable (${?ENTITY_CLIENT_RESTLI_GET_BATCH_CONCURRENCY}) is a good practice. This ensures that the application can adapt to different environments without requiring code changes, which is crucial for maintaining consistent behavior across deployments.

datahub-frontend/app/controllers/Application.java (3)

12-13: Approved: Import statements.

The new imports for JsonNode and ObjectMapper are necessary for handling JSON operations in the logSlowQuery method.


20-20: Approved: Import statement.

The import of Instant is necessary for measuring the duration of requests, which is a part of the new feature.


139-141: Approved: Time measurement initiation.

The use of Instant.now() to capture the start time of the request is appropriate for measuring the request duration.

Comment on lines +170 to +178
// 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);
}

Copy link
Contributor

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:

try {
    boolean verboseGraphQLLogging = _config.getBoolean("graphql.verbose.logging");
    int verboseGraphQLLongQueryMillis = _config.getInt("graphql.verbose.slowQueryMillis");
} catch (ConfigException e) {
    _logger.error("Error accessing configuration for GraphQL logging.", e);
}

Comment on lines +381 to +407
* 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);
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review: logSlowQuery method implementation.

The method implementation for logging slow GraphQL queries is mostly correct. However, there are a few areas of improvement:

  1. The removal of the "query" field from the JSON body is a good practice to avoid logging sensitive data, but ensure that the JSON body is not null before casting and modifying it.
  2. The exception handling could be more specific by catching more specific exceptions than the general Exception.
  3. The logging statement at the end could benefit from more structured logging instead of concatenating strings.

Consider the following improvements:

  1. Check for null before casting the JSON body:
if (jsonNode != null && jsonNode.isObject()) {
    ((ObjectNode) jsonNode).remove("query");
}
  1. Catch more specific exceptions:
catch (IOException e) {
    _logger.info("GraphQL Request Received: {}, Unable to parse JSON body due to IO issues", resolvedUri, e);
}
  1. Use structured logging:
_logger.info("Slow GraphQL Request Received: URI={}, QueryString={}, Actor={}, JSON={}, Duration={} ms",
             resolvedUri, request.queryString(), actorValue, jsonBodyStr, duration);

Copy link
Collaborator

@david-leifker david-leifker left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM! Thank you!

@david-leifker david-leifker merged commit c63d75e into datahub-project:master Sep 10, 2024
34 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
community-contribution PR or Issue raised by member(s) of DataHub Community product PR or Issue related to the DataHub UI/UX
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants