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

fix(server/v2): use only one logger for app and server #22241

Merged
merged 2 commits into from
Oct 14, 2024

Conversation

julienrbrt
Copy link
Member

@julienrbrt julienrbrt commented Oct 11, 2024

Description

Closes: #22237


Author Checklist

All items are required. Please add a note to the item if the item is not applicable and
please add links to any relevant follow up issues.

I have...

  • included the correct type prefix in the PR title, you can find examples of the prefixes below:
  • confirmed ! in the type prefix if API or client breaking change
  • targeted the correct branch (see PR Targeting)
  • provided a link to the relevant issue or specification
  • reviewed "Files changed" and left comments if necessary
  • included the necessary unit and integration tests
  • added a changelog entry to CHANGELOG.md
  • updated the relevant documentation or specification, including comments for documenting Go code
  • confirmed all CI checks have passed

Reviewers Checklist

All items are required. Please add a note if the item is not applicable and please add
your handle next to the items reviewed if you only reviewed selected items.

Please see Pull Request Reviewer section in the contributing guide for more information on how to review a pull request.

I have...

  • confirmed the correct type prefix in the PR title
  • confirmed all author checklist items have been addressed
  • reviewed state machine logic, API design and naming, documentation is accurate, tests and test coverage

Summary by CodeRabbit

  • New Features

    • Enhanced context handling for improved modularity.
    • Updated logging level configuration for the CometBFT server.
  • Bug Fixes

    • Improved error handling in command initialization.
  • Refactor

    • Simplified server initialization by removing unnecessary parameters.
    • Consistent naming conventions for logging variables.
    • Streamlined command execution flow.
  • Chores

    • Removed unused logging imports from various files.

Copy link
Contributor

coderabbitai bot commented Oct 11, 2024

📝 Walkthrough
📝 Walkthrough

Walkthrough

The changes in this pull request focus on simplifying the command execution and server initialization processes within the server/v2 package. Key modifications include the removal of the logger parameter from several functions, updates to the Server struct, and enhancements to context handling. Additionally, the simapp/v2/simdv2/cmd package has been adjusted to align with these changes, particularly in error handling and logging configuration.

Changes

File Path Change Summary
server/v2/commands.go Removed logger parameter from AddCommands function; renamed log to logger in configHandle.
server/v2/server.go Changed serverName to "serverv2"; removed logger field from Server struct; updated NewServer method signature.
server/v2/server_test.go Updated NewServer instantiation to remove logger parameter.
server/v2/util.go Added GetViperFromContext and GetLoggerFromContext functions; updated existing functions to use context.
simapp/v2/simdv2/cmd/commands.go Updated initRootCmd to remove logger from AddCommands function call.
simapp/v2/simdv2/cmd/config.go Adjusted logging level for CometBFT server to include serverv2:info.
simapp/v2/simdv2/cmd/testnet.go Removed import for log package; updated NewServer instantiation to remove logger.

Assessment against linked issues

Objective Addressed Explanation
Ensure server components are configured by command line flags (#22237) The changes do not address the command line flag configuration issue.

Possibly related PRs

Suggested labels

Type: CI, C:server/v2 api, C:server/v2 cometbft

Suggested reviewers

  • facundomedica
  • sontrinh16
  • hieuvubk
  • kocubinski
  • testinginprod

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>, please review it.
    • 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 gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @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.

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 the C:server/v2 Issues related to server/v2 label Oct 11, 2024
Copy link
Contributor

@julienrbrt your pull request is missing a changelog!

@julienrbrt julienrbrt added the backport/v0.52.x PR scheduled for inclusion in the v0.52's next stable release label Oct 11, 2024
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: 0

🧹 Outside diff range and nitpick comments (6)
server/v2/util.go (2)

33-41: LGTM with a minor suggestion.

The new GetViperFromContext function is well-implemented and follows good practices. It correctly retrieves the viper instance from the context and includes appropriate error handling.

Consider using a more idiomatic Go approach for the type assertion:

v, ok := ctx.Value(corectx.ViperContextKey).(*viper.Viper)
if !ok {
    panic(fmt.Sprintf("incorrect viper type %T: expected *viper.Viper. Have you forgot to set the viper in the context?", ctx.Value(corectx.ViperContextKey)))
}
return v

This change reduces the number of variables and makes the code slightly more concise.


48-57: LGTM with a minor suggestion.

The new GetLoggerFromContext function is well-implemented and consistent with the GetViperFromContext function. It correctly retrieves the logger instance from the context and includes appropriate error handling.

Similar to the suggestion for GetViperFromContext, consider using a more idiomatic Go approach for the type assertion:

logger, ok := ctx.Value(corectx.LoggerContextKey).(log.Logger)
if !ok {
    panic(fmt.Sprintf("incorrect logger type %T: expected log.Logger. Have you forgot to set the logger in the context?", ctx.Value(corectx.LoggerContextKey)))
}
return logger

This change reduces the number of variables and makes the code slightly more concise.

simapp/v2/simdv2/cmd/config.go (1)

82-82: Approved: Log level configuration updated appropriately.

The addition of "serverv2:info" to the log level configuration aligns with the PR objectives to address logging issues for server components. This change will enable informational logging for the serverv2 component while maintaining the existing log levels for other components, which should aid in debugging and monitoring.

For improved readability, consider using a multi-line string literal for the log level configuration. For example:

cfg.LogLevel = `
    *:warn
    serverv2:info
    p2p:info
    state:info
`

This format makes it easier to read and modify individual log level settings in the future.

simapp/v2/simdv2/cmd/commands.go (1)

Line range hint 68-77: Approve changes with a minor suggestion for error handling

The changes align with the PR objective of using a single logger for both app and server. The removal of the logger parameter from the serverv2.AddCommands function call is appropriate.

The error handling has been simplified, which improves code readability. However, we can further improve it by using a more idiomatic Go error handling pattern.

Consider updating the error handling to use the following pattern:

if err := serverv2.AddCommands(
    rootCmd,
    newApp,
    initServerConfig(),
    cometbft.New(
        &genericTxDecoder[T]{txConfig},
        initCometOptions[T](),
        initCometConfig(),
    ),
    grpc.New[T](),
    serverstore.New[T](),
    telemetry.New[T](),
); err != nil {
    return err // or log.Fatal(err) depending on the function signature
}

This approach avoids the use of panic and allows for more graceful error handling or propagation.

server/v2/commands.go (2)

46-46: LGTM! Consider enhancing error handling.

The removal of the logger parameter from NewServer call aligns well with the PR objective of using a single logger. This simplification improves code clarity and maintainability.

Consider adding error handling for the NewServer call:

server, err := NewServer(globalServerCfg, components...)
if err != nil {
    return fmt.Errorf("failed to create new server: %w", err)
}

171-176: LGTM! Consider enhancing error logging.

The renaming of log to logger and the use of NewLogger function improve code clarity and align with the PR objectives.

Consider logging the error before returning it:

logger, err := NewLogger(v, cmd.OutOrStdout())
if err != nil {
    fmt.Fprintf(cmd.ErrOrStderr(), "Failed to create logger: %v\n", err)
    return err
}
📜 Review details

Configuration used: .coderabbit.yml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 4733fc1 and 3c7720a.

📒 Files selected for processing (7)
  • server/v2/commands.go (2 hunks)
  • server/v2/server.go (3 hunks)
  • server/v2/server_test.go (0 hunks)
  • server/v2/util.go (1 hunks)
  • simapp/v2/simdv2/cmd/commands.go (1 hunks)
  • simapp/v2/simdv2/cmd/config.go (1 hunks)
  • simapp/v2/simdv2/cmd/testnet.go (1 hunks)
💤 Files with no reviewable changes (1)
  • server/v2/server_test.go
🧰 Additional context used
📓 Path-based instructions (6)
server/v2/commands.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

server/v2/server.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

server/v2/util.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

simapp/v2/simdv2/cmd/commands.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

simapp/v2/simdv2/cmd/config.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

simapp/v2/simdv2/cmd/testnet.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

🔇 Additional comments (8)
server/v2/util.go (3)

43-46: LGTM! Good refactoring.

The modification to GetViperFromCmd is a good improvement. It now leverages the GetViperFromContext function, promoting code reuse and maintaining a single source of truth for retrieving the viper instance from the context.


59-62: LGTM! Consistent refactoring.

The modification to GetLoggerFromCmd is a good improvement, consistent with the changes made to GetViperFromCmd. It now leverages the GetLoggerFromContext function, promoting code reuse and maintaining a single source of truth for retrieving the logger instance from the context.


33-62: Overall, excellent refactoring that improves code structure and consistency.

The changes in this file successfully address the PR objectives by consolidating the logging mechanism and improving consistency in handling context values. The new functions GetViperFromContext and GetLoggerFromContext provide a centralized way to retrieve these instances, which should help in properly respecting command line flags for logging format.

The refactoring of GetViperFromCmd and GetLoggerFromCmd to use these new functions promotes code reuse and maintainability. These changes are likely to resolve the issue described in #22237 by ensuring that server components are properly configured to respect command line flags.

Great job on improving the overall structure and consistency of the code!

server/v2/commands.go (1)

Line range hint 1-211: Update documentation and verify test coverage.

The changes successfully address the issue of using a single logger for the app and server, aligning well with the PR objectives. The code structure is good and follows the Uber Golang style guide.

Please ensure that:

  1. The package documentation is updated to reflect the changes in logger handling.
  2. Any existing tests are updated to accommodate the new logger initialization process.

To verify test coverage, run the following script:

server/v2/server.go (3)

107-108: LGTM: Consistent logging approach in Stop method.

The changes to the Stop method mirror those in the Start method, maintaining a consistent approach to logging across the Server struct's methods. This consistency improves code readability and maintainability.


86-87: LGTM: Logging now uses context-based logger.

The change to use GetLoggerFromContext(ctx) instead of a struct-level logger improves flexibility and context-awareness in logging. The addition of the module key enhances log clarity.

To ensure the GetLoggerFromContext function is properly implemented, please run:

rg -A 10 'func GetLoggerFromContext'

This will help verify that the function correctly retrieves the logger from the context.


59-59: LGTM: Server name updated to reflect version.

The change from "server" to "serverv2" is consistent with the package name. This update might affect areas where the server name is used, such as logging or configuration.

To ensure this change doesn't introduce any inconsistencies, please run the following command to check for any remaining occurrences of the old server name:

✅ Verification successful

Verified: Server name updated correctly.

The change from "server" to "serverv2" in server/v2/server.go has been consistently applied to all relevant instances of serverName. No residual references to the old server name "server" were found, ensuring uniformity across the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

rg '"server"' --type go

Length of output: 598


Script:

#!/bin/bash
# Search for any occurrences of 'server' in Go files
rg 'server' --type go

Length of output: 169194


Script:

#!/bin/bash
# Search for all occurrences of 'serverName' in Go files
rg 'serverName' --type go

Length of output: 172

simapp/v2/simdv2/cmd/testnet.go (1)

346-346: LGTM! Simplified server initialization.

The removal of the logger parameter from serverv2.NewServer aligns with the PR objective of using a single logger for both app and server. This change simplifies the server initialization process.

To ensure that logging functionality is still properly configured and accessible, please run the following verification script:

✅ Verification successful

Verified: Logging Configuration Intact

The removal of the logger parameter from serverv2.NewServer has been successfully verified. There are no remaining references to the old logging method, and the new logging implementation is consistently used throughout the server/v2/ directory.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that logging is still properly configured after the change.

# Test 1: Check if there are any remaining references to the old logging method
echo "Checking for old logging references:"
rg --type go 'NewServer.*logger'

# Test 2: Verify that the new logging method is properly implemented
echo "Verifying new logging implementation:"
rg --type go 'log\.' server/v2/

# Test 3: Check for any TODO or FIXME comments related to logging
echo "Checking for TODO or FIXME comments related to logging:"
rg --type go -e 'TODO.*log' -e 'FIXME.*log'

Length of output: 6761

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: 0

🧹 Outside diff range and nitpick comments (7)
server/v2/server_test.go (2)

68-70: LGTM with a minor suggestion for error handling

The changes align well with the PR objective of consolidating logging. The use of SetServerContext is appropriate here.

A minor suggestion to improve error handling:

- ctx, err := serverv2.SetServerContext(context.Background(), v, logger)
- require.NoError(t, err)
+ ctx, err := serverv2.SetServerContext(context.Background(), v, logger)
+ require.NoError(t, err, "Failed to set server context")

Adding an error message to require.NoError can help with debugging if the test fails.


Line range hint 41-117: Suggestion: Add test case for new logging behavior

The changes to the TestServer function are consistent with the PR objective of using a single logger for both the app and server. However, to ensure comprehensive test coverage, consider adding a specific test case that verifies the new logging behavior.

For example, you could add a test that:

  1. Captures the log output.
  2. Performs an operation that triggers logging.
  3. Verifies that the log output contains the expected content and format.

This would help ensure that the logging changes are working as intended and provide better test coverage for the modifications made in this PR.

server/v2/util.go (3)

16-26: LGTM with a minor suggestion for improvement

The new SetServerContext function is well-implemented and follows good practices. It properly handles nil contexts and clearly sets both logger and viper in the context.

Consider adding error checking for nil viper and logger parameters to make the function more robust:

 func SetServerContext(ctx context.Context, viper *viper.Viper, logger log.Logger) (context.Context, error) {
 	if ctx == nil {
 		ctx = context.Background()
 	}
+	if viper == nil {
+		return nil, errors.New("viper cannot be nil")
+	}
+	if logger == nil {
+		return nil, errors.New("logger cannot be nil")
+	}
 
 	ctx = context.WithValue(ctx, corectx.LoggerContextKey, logger)
 	ctx = context.WithValue(ctx, corectx.ViperContextKey, viper)
 	return ctx, nil
 }

40-48: LGTM with a suggestion for improved error handling

The new GetViperFromContext function is well-implemented. It correctly retrieves the viper instance from the context and includes an informative panic message if the viper is not set or of incorrect type.

Consider using a multi-value type assertion to avoid a potential panic if the context value is nil:

 func GetViperFromContext(ctx context.Context) *viper.Viper {
 	value := ctx.Value(corectx.ViperContextKey)
-	v, ok := value.(*viper.Viper)
+	v, ok := value.(*viper.Viper)
 	if !ok {
-		panic(fmt.Sprintf("incorrect viper type %T: expected *viper.Viper. Have you forgot to set the viper in the context?", value))
+		panic(fmt.Sprintf("incorrect or missing viper: expected *viper.Viper, got %T. Have you forgot to set the viper in the context?", value))
 	}
 	return v
 }

55-69: LGTM with a suggestion for improved error handling

The new GetLoggerFromContext function and the changes to GetLoggerFromCmd are well-implemented. They follow a consistent pattern with their viper counterparts, which improves code readability and maintainability.

For GetLoggerFromContext, consider using a multi-value type assertion to avoid a potential panic if the context value is nil:

 func GetLoggerFromContext(ctx context.Context) log.Logger {
 	v := ctx.Value(corectx.LoggerContextKey)
-	logger, ok := v.(log.Logger)
+	logger, ok := v.(log.Logger)
 	if !ok {
-		panic(fmt.Sprintf("incorrect logger type %T: expected log.Logger. Have you forgot to set the logger in the context?", v))
+		panic(fmt.Sprintf("incorrect or missing logger: expected log.Logger, got %T. Have you forgot to set the logger in the context?", v))
 	}
 
 	return logger
 }

The changes to GetLoggerFromCmd look good and align well with the PR objectives of consolidating logging mechanisms.

server/v2/server.go (2)

86-87: LGTM: Updated logger usage in Start method

The changes to retrieve the logger from the context and include the module key in the log message are good improvements. They align with the PR objective and enhance log clarity.

Consider adding an error log message before returning the error in the Start method. This would provide more context in the logs when a start failure occurs:

 if err := g.Wait(); err != nil {
+    logger.With(log.ModuleKey, s.Name()).Error("failed to start servers", "err", err)
     return fmt.Errorf("failed to start servers: %w", err)
 }

107-108: LGTM: Updated logger usage in Stop method

The changes to retrieve the logger from the context and include the module key in the log message are good improvements. They align with the PR objective and enhance log clarity.

Consider adding an error log message before returning the error in the Stop method. This would provide more context in the logs when a stop failure occurs:

- return g.Wait()
+ if err := g.Wait(); err != nil {
+    logger.With(log.ModuleKey, s.Name()).Error("failed to stop servers", "err", err)
+    return err
+ }
+ return nil
📜 Review details

Configuration used: .coderabbit.yml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 3c7720a and f21df91.

📒 Files selected for processing (4)
  • server/v2/server.go (2 hunks)
  • server/v2/server_test.go (2 hunks)
  • server/v2/util.go (1 hunks)
  • simapp/v2/simdv2/cmd/config.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • simapp/v2/simdv2/cmd/config.go
🧰 Additional context used
📓 Path-based instructions (3)
server/v2/server.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

server/v2/server_test.go (2)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.


Pattern **/*_test.go: "Assess the unit test code assessing sufficient code coverage for the changes associated in the pull request"

server/v2/util.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

🔇 Additional comments (6)
server/v2/server_test.go (1)

103-103: LGTM: Proper context usage

The update to use the existing ctx instead of context.TODO() is correct. This change ensures that the cancellation will properly propagate through the entire test, which is important for proper resource management and test behavior.

server/v2/util.go (2)

28-38: LGTM! Good refactoring

The changes to SetCmdServerContext are well-implemented. The function now leverages the new SetServerContext function, which simplifies the code and improves consistency. Error handling is properly implemented, and the function's purpose remains clear.


50-53: LGTM! Good refactoring

The changes to GetViperFromCmd are well-implemented. The function now leverages the new GetViperFromContext function, which simplifies the code and improves consistency. This refactoring aligns well with the PR objectives of consolidating viper retrieval mechanisms.

server/v2/server.go (3)

86-87: LGTM: Updated server name constant

The change from "server" to "serverv2" in the serverName constant accurately reflects the version update. This improves clarity without affecting functionality.


Line range hint 1-268: Summary: Improved logging consistency and simplified server structure

The changes in this file successfully implement the PR objective of using a single logger for the app and server. Key improvements include:

  1. Updating the serverName constant for clarity.
  2. Removing the logger field from the Server struct and the logger parameter from the NewServer function.
  3. Modifying the Start and Stop methods to use a logger from the context.
  4. Adding module keys to log messages for better context.

These changes enhance logging consistency and simplify the server structure. However, it's important to ensure that these modifications don't introduce issues in other parts of the codebase that may have depended on the previous logging structure.

To ensure the changes don't introduce unintended side effects, please run the following verification:

#!/bin/bash
# Description: Check for any remaining references to the removed logger field

# Test: Search for any remaining references to s.logger
echo "Checking for references to s.logger in the codebase:"
rg --type go 's\.logger' .

# Test: Search for any remaining NewServer calls with a logger parameter
echo "Checking for NewServer calls with a logger parameter:"
rg --type go 'NewServer\([^)]*logger[^)]*\)' .

86-87: LGTM: Removed logger field and parameter

The removal of the logger field from the Server struct and the logger parameter from the NewServer function aligns with the PR objective of using a single logger. This simplification is a good step towards consistent logging.

To ensure this change doesn't introduce any issues, please verify logger usage throughout the codebase:

Copy link
Contributor

@hieuvubk hieuvubk left a comment

Choose a reason for hiding this comment

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

lgtm

@julienrbrt julienrbrt added this pull request to the merge queue Oct 14, 2024
Merged via the queue into main with commit 1f941bb Oct 14, 2024
74 of 76 checks passed
@julienrbrt julienrbrt deleted the julien/onelogger branch October 14, 2024 06:09
mergify bot pushed a commit that referenced this pull request Oct 14, 2024
(cherry picked from commit 1f941bb)

# Conflicts:
#	server/v2/commands.go
#	server/v2/server.go
#	server/v2/server_test.go
#	server/v2/util.go
julienrbrt added a commit that referenced this pull request Oct 14, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
backport/v0.52.x PR scheduled for inclusion in the v0.52's next stable release C:server/v2 Issues related to server/v2
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[Bug]: server/v2 server components are not configured by command line flags
4 participants