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

Add debug mode with slog for logging #149

Merged
merged 1 commit into from
Apr 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
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
15 changes: 13 additions & 2 deletions internal/cli/cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"flag"
"fmt"
"io"
"log/slog"
"os"
"os/signal"
"runtime"
Expand Down Expand Up @@ -60,6 +61,7 @@ func (c *CLI) Run(args []string) int {
uploadFilename string
filetype string
snippetMode bool
debugMode bool
)

c.conf = config.NewConfig()
Expand All @@ -79,6 +81,8 @@ func (c *CLI) Run(args []string) int {

flags.BoolVar(&snippetMode, "snippet", false, "switch to snippet uploading mode")

flags.BoolVar(&debugMode, "debug", false, "debug mode (for developers)")

flags.BoolVar(&version, "version", false, "Print version information and quit")

err := flags.Parse(args[1:])
Expand Down Expand Up @@ -128,8 +132,15 @@ func (c *CLI) Run(args []string) int {
return ExitCodeFail
}

var logger *slog.Logger
if debugMode {
logger = slog.New(slog.NewTextHandler(c.errStream, &slog.HandlerOptions{AddSource: true, Level: slog.LevelDebug}))
} else {
logger = slog.New(slog.NewTextHandler(c.errStream, nil))
}

if filename != "" || snippetMode {
c.sClient, err = slack.NewClientForPostFile(nil)
c.sClient, err = slack.NewClientForPostFile(logger)
if err != nil {
fmt.Fprintln(c.errStream, err)
return ExitCodeFail
Expand All @@ -154,7 +165,7 @@ func (c *CLI) Run(args []string) int {
return ExitCodeFail
}

c.sClient, err = slack.NewClient(c.conf.SlackURL, nil)
c.sClient, err = slack.NewClient(c.conf.SlackURL, logger)
if err != nil {
fmt.Fprintln(c.errStream, err)
return ExitCodeFail
Expand Down
35 changes: 16 additions & 19 deletions internal/slack/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import (
"encoding/json"
"fmt"
"io"
"log"
"log/slog"
"net/http"
"net/url"
"strings"
Expand All @@ -22,7 +22,7 @@ type Client struct {
URL *url.URL
HTTPClient *http.Client

Logger *log.Logger
Logger *slog.Logger
}

type PostTextParam struct {
Expand All @@ -44,7 +44,7 @@ type Slack interface {
PostFile(ctx context.Context, token string, param *PostFileParam) error
}

func NewClient(urlStr string, logger *log.Logger) (*Client, error) {
func NewClient(urlStr string, logger *slog.Logger) (*Client, error) {
if len(urlStr) == 0 {
return nil, fmt.Errorf("client: missing url")
}
Expand All @@ -54,11 +54,6 @@ func NewClient(urlStr string, logger *log.Logger) (*Client, error) {
return nil, fmt.Errorf("failed to parse url: %s: %w", urlStr, err)
}

var discardLogger = log.New(io.Discard, "", log.LstdFlags)
if logger == nil {
logger = discardLogger
}

client := &Client{
URL: parsedURL,
HTTPClient: http.DefaultClient,
Expand All @@ -68,12 +63,7 @@ func NewClient(urlStr string, logger *log.Logger) (*Client, error) {
return client, nil
}

func NewClientForPostFile(logger *log.Logger) (*Client, error) {
var discardLogger = log.New(io.Discard, "", log.LstdFlags)
if logger == nil {
logger = discardLogger
}

func NewClientForPostFile(logger *slog.Logger) (*Client, error) {
client := &Client{
HTTPClient: http.DefaultClient,
Logger: logger,
Expand Down Expand Up @@ -109,18 +99,23 @@ func (c *Client) PostText(ctx context.Context, param *PostTextParam) error {

req.Header.Set("Content-Type", "application/json")

c.Logger.Debug("request", "url", req.URL.String(), "method", req.Method, "header", req.Header)

res, err := c.HTTPClient.Do(req)
if err != nil {
return err
}
defer res.Body.Close()

body, err := io.ReadAll(res.Body)
if err != nil {
return fmt.Errorf("failed to read res.Body: %w", err)
}

c.Logger.Debug("request", "url", req.URL.String(), "method", req.Method, "header", req.Header, "status", res.StatusCode, "body", body)

if res.StatusCode != http.StatusOK {
b, err := io.ReadAll(res.Body)
if err != nil {
return fmt.Errorf("failed to read res.Body and the status code of the response from slack was not 200: %w", err)
}
return fmt.Errorf("status code: %d; body: %s", res.StatusCode, b)
return fmt.Errorf("status code: %d; body: %s", res.StatusCode, body)
}

return nil
Expand Down Expand Up @@ -169,6 +164,8 @@ func (c *Client) PostFile(ctx context.Context, token string, param *PostFilePara
return err
}

c.Logger.Debug("request", "url", req.URL.String(), "method", req.Method, "header", req.Header, "status", res.StatusCode, "body", b)

if res.StatusCode != http.StatusOK {
return fmt.Errorf("failed to read res.Body and the status code of the response from slack was not 200; body: %s", b)
}
Expand Down
19 changes: 10 additions & 9 deletions internal/slack/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"net/url"
Expand All @@ -15,7 +16,7 @@ import (
)

func TestNewClient_badURL(t *testing.T) {
_, err := NewClient("", nil)
_, err := NewClient("", slog.New(slog.NewTextHandler(io.Discard, nil)))
if err == nil {
t.Fatal("expected error, but nothing was returned")
}
Expand All @@ -27,7 +28,7 @@ func TestNewClient_badURL(t *testing.T) {
}

func TestNewClient_parsesURL(t *testing.T) {
client, err := NewClient("https://example.com/foo/bar", nil)
client, err := NewClient("https://example.com/foo/bar", slog.New(slog.NewTextHandler(io.Discard, nil)))
if err != nil {
t.Fatal(err)
}
Expand Down Expand Up @@ -80,7 +81,7 @@ func TestPostText_Success(t *testing.T) {
http.ServeFile(w, r, "testdata/post_text_ok.html")
})

c, err := NewClient(testAPIServer.URL, nil)
c, err := NewClient(testAPIServer.URL, slog.New(slog.NewTextHandler(io.Discard, nil)))
if err != nil {
t.Fatal(err)
}
Expand Down Expand Up @@ -109,7 +110,7 @@ func TestPostText_Fail(t *testing.T) {
http.ServeFile(w, r, "testdata/post_text_fail.html")
})

c, err := NewClient(testAPIServer.URL, nil)
c, err := NewClient(testAPIServer.URL, slog.New(slog.NewTextHandler(io.Discard, nil)))
if err != nil {
t.Fatal(err)
}
Expand Down Expand Up @@ -172,7 +173,7 @@ func TestPostFile_Success(t *testing.T) {

defer SetSlackFilesUploadURL(testAPIServer.URL)()

c, err := NewClientForPostFile(nil)
c, err := NewClientForPostFile(slog.New(slog.NewTextHandler(io.Discard, nil)))
if err != nil {
t.Fatal(err)
}
Expand Down Expand Up @@ -232,7 +233,7 @@ func TestPostFile_Success_provideFiletype(t *testing.T) {

defer SetSlackFilesUploadURL(testAPIServer.URL)()

c, err := NewClientForPostFile(nil)
c, err := NewClientForPostFile(slog.New(slog.NewTextHandler(io.Discard, nil)))
if err != nil {
t.Fatal(err)
}
Expand Down Expand Up @@ -263,7 +264,7 @@ func TestPostFile_FailNotOk(t *testing.T) {

defer SetSlackFilesUploadURL(testAPIServer.URL)()

c, err := NewClientForPostFile(nil)
c, err := NewClientForPostFile(slog.New(slog.NewTextHandler(io.Discard, nil)))
if err != nil {
t.Fatal(err)
}
Expand Down Expand Up @@ -300,7 +301,7 @@ func TestPostFile_FailNotResponseStatusCodeNotOK(t *testing.T) {

defer SetSlackFilesUploadURL(testAPIServer.URL)()

c, err := NewClientForPostFile(nil)
c, err := NewClientForPostFile(slog.New(slog.NewTextHandler(io.Discard, nil)))
if err != nil {
t.Fatal(err)
}
Expand Down Expand Up @@ -336,7 +337,7 @@ func TestPostFile_FailNotJSON(t *testing.T) {

defer SetSlackFilesUploadURL(testAPIServer.URL)()

c, err := NewClientForPostFile(nil)
c, err := NewClientForPostFile(slog.New(slog.NewTextHandler(io.Discard, nil)))
if err != nil {
t.Fatal(err)
}
Expand Down
Loading