Skip to content

feat: Log API requests made by CLI #1615

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

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
feat: Add simple request logging to CLI
  • Loading branch information
dwahler committed May 20, 2022
commit 7b0389016c05c40a20639a4d0609bbd728250b68
38 changes: 38 additions & 0 deletions cli/requestlogging.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package cli

import (
"fmt"
"io"
"net/http"
"strconv"
)

type loggingRoundTripper struct {
http.RoundTripper
io.Writer
}

func newLoggingRoundTripper(writer io.Writer) http.RoundTripper {
return &loggingRoundTripper{
Writer: writer,
}
}

func (lrt loggingRoundTripper) RoundTrip(request *http.Request) (*http.Response, error) {
Copy link
Member

Choose a reason for hiding this comment

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

Do you want add optionally showing body payloads?

inner := lrt.RoundTripper
if inner == nil {
inner = http.DefaultTransport
}

response, err := inner.RoundTrip(request)

var displayedStatusCode string
if err != nil {
displayedStatusCode = "(err)"
} else {
displayedStatusCode = strconv.Itoa(response.StatusCode)
}

_, _ = fmt.Fprintf(lrt.Writer, "%s %s %s\n", request.Method, request.URL.String(), displayedStatusCode)
Copy link
Contributor

Choose a reason for hiding this comment

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

I think it could be nice to add something here that clarifies this isn't a webserver access log, and instead an outbound client log.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Good point. I added a sending request: prefix to make this a bit clearer.

return response, err
}
40 changes: 40 additions & 0 deletions cli/requestlogging_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package cli_test

import (
"testing"

"github.com/stretchr/testify/require"

"github.com/coder/coder/cli/clitest"
"github.com/coder/coder/coderd/coderdtest"
"github.com/coder/coder/pty/ptytest"
)

func TestRequestLogging(t *testing.T) {
t.Parallel()
t.Run("List", func(t *testing.T) {
t.Parallel()
client := coderdtest.New(t, &coderdtest.Options{IncludeProvisionerD: true})
user := coderdtest.CreateFirstUser(t, client)
version := coderdtest.CreateTemplateVersion(t, client, user.OrganizationID, nil)
coderdtest.AwaitTemplateVersionJob(t, client, version.ID)
template := coderdtest.CreateTemplate(t, client, user.OrganizationID, version.ID)
workspace := coderdtest.CreateWorkspace(t, client, user.OrganizationID, template.ID)
coderdtest.AwaitWorkspaceBuildJob(t, client, workspace.LatestBuild.ID)
cmd, root := clitest.New(t, "ls", "--log-requests")
clitest.SetupConfig(t, client, root)
doneChan := make(chan struct{})
pty := ptytest.New(t)
cmd.SetIn(pty.Input())
cmd.SetOut(pty.Output())
go func() {
defer close(doneChan)
err := cmd.Execute()
require.NoError(t, err)
}()
pty.ExpectMatch("GET " + client.URL.String() + "/api/v2/workspaces 200")
pty.ExpectMatch(workspace.Name)
pty.ExpectMatch("Running")
<-doneChan
})
}
18 changes: 16 additions & 2 deletions cli/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ const (
varGlobalConfig = "global-config"
varNoOpen = "no-open"
varForceTty = "force-tty"
varLogRequests = "log-requests"
)

func init() {
Expand Down Expand Up @@ -91,11 +92,14 @@ func Root() *cobra.Command {

cmd.PersistentFlags().String(varURL, "", "Specify the URL to your deployment.")
cmd.PersistentFlags().String(varToken, "", "Specify an authentication token.")
cliflag.String(cmd.PersistentFlags(), varGlobalConfig, "", "CODER_CONFIG_DIR", configdir.LocalConfig("coderv2"), "Specify the path to the global `coder` config directory.")
cmd.PersistentFlags().Bool(varLogRequests, false, "Log requests made to remote API endpoints.")

// Hidden flags for internal use.
cliflag.String(cmd.PersistentFlags(), varAgentToken, "", "CODER_AGENT_TOKEN", "", "Specify an agent authentication token.")
_ = cmd.PersistentFlags().MarkHidden(varAgentToken)
cliflag.String(cmd.PersistentFlags(), varAgentURL, "", "CODER_AGENT_URL", "", "Specify the URL for an agent to access your deployment.")
_ = cmd.PersistentFlags().MarkHidden(varAgentURL)
cliflag.String(cmd.PersistentFlags(), varGlobalConfig, "", "CODER_CONFIG_DIR", configdir.LocalConfig("coderv2"), "Specify the path to the global `coder` config directory.")
cmd.PersistentFlags().Bool(varForceTty, false, "Force the `coder` command to run as if connected to a TTY.")
_ = cmd.PersistentFlags().MarkHidden(varForceTty)
cmd.PersistentFlags().Bool(varNoOpen, false, "Block automatically opening URLs in the browser.")
Expand Down Expand Up @@ -126,7 +130,17 @@ func createClient(cmd *cobra.Command) (*codersdk.Client, error) {
return nil, err
}
}
client := codersdk.New(serverURL)
logRequests, err := cmd.Flags().GetBool(varLogRequests)
if err != nil {
return nil, err
}

var client *codersdk.Client
if logRequests {
client = codersdk.NewWithRoundTripper(serverURL, newLoggingRoundTripper(cmd.OutOrStderr()))
} else {
client = codersdk.New(serverURL)
}
client.SessionToken = token
return client, nil
}
Expand Down
10 changes: 10 additions & 0 deletions codersdk/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,16 @@ func New(serverURL *url.URL) *Client {
}
}

// NewWithRoundTripper behaves like New, but allows specifying a custom implementation of http.RoundTripper.
func NewWithRoundTripper(serverURL *url.URL, roundTripper http.RoundTripper) *Client {
return &Client{
URL: serverURL,
HTTPClient: &http.Client{
Transport: roundTripper,
},
}
}

// Client is an HTTP caller for methods to the Coder API.
// @typescript-ignore Client
type Client struct {
Expand Down