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

Output debug logs for API access #115

Merged
merged 5 commits into from
Oct 28, 2023
Merged
Changes from 3 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
67 changes: 65 additions & 2 deletions atom/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,13 @@ import (
"encoding/xml"
"fmt"
"io"
"log"
"log/slog"
Songmu marked this conversation as resolved.
Show resolved Hide resolved
"net/http"
"os"
"path/filepath"
"strings"
"sync"
)

// Client wrapped *http.Client and some methods for accessing atom feed are added
Expand Down Expand Up @@ -88,13 +94,70 @@ func entryBody(e *Entry) (*bytes.Buffer, error) {
return body, nil
}

func (c *Client) http(method, url string, body io.Reader) (*http.Response, error) {
var blogsyncDebug = os.Getenv("BLOGSYNC_DEBUG") != ""

var debugLogger = sync.OnceValue(func() *slog.Logger {
var w io.Writer = os.Stderr
cached, err := os.UserCacheDir()
if err == nil {
logf := filepath.Join(cached, "blogsync", "tracedump.log")
if err := os.MkdirAll(filepath.Dir(logf), 0755); err == nil {
if f, err := os.OpenFile(logf, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644); err == nil {
log.Printf("trace dumps are output to %s\n", logf)
w = f
}
}
}
return slog.New(slog.NewJSONHandler(w, &slog.HandlerOptions{
Level: slog.LevelDebug,
}))
})

type traceDump struct {
Request string `json:"request,omitempty"`
Response string `json:"response,omitempty"`
Method string `json:"method"`
URL string `json:"url"`
Status int `json:"status"`
}

func (c *Client) http(method, url string, body io.Reader) (resp *http.Response, err error) {
if blogsyncDebug {
td := traceDump{
Method: method,
URL: url,
}
if body != nil {
bb, err := io.ReadAll(body)
if err != nil {
return nil, err
}
td.Request = string(bb)
body = strings.NewReader(td.Request)
}
defer func() {
if err != nil {
return
}
bb, rerr := io.ReadAll(resp.Body)
if rerr != nil {
err = rerr
resp.Body.Close()
return
}
td.Response = string(bb)
td.Status = resp.StatusCode
debugLogger().Debug("traceDump", "data", td)
resp.Body = io.NopCloser(strings.NewReader(td.Response))
}()
}

req, err := http.NewRequest(method, url, body)
if err != nil {
return nil, err
}

resp, err := c.Client.Do(req)
resp, err = c.Client.Do(req)
if err != nil {
return nil, err
}
Expand Down
Loading