-
-
Notifications
You must be signed in to change notification settings - Fork 33
Add JSONL access logging #269
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
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,109 @@ | ||
| // Package accesslog writes proxy activity as JSON Lines. | ||
| package accesslog | ||
|
|
||
| import ( | ||
| "context" | ||
| "encoding/json" | ||
| "fmt" | ||
| "net/url" | ||
| "os" | ||
| "sync" | ||
| "time" | ||
| ) | ||
|
|
||
| const ( | ||
| accessLogFileMode os.FileMode = 0o600 | ||
|
|
||
| // EventRequest identifies the response sent by the proxy to a client. | ||
| EventRequest = "request" | ||
| // EventUpstream identifies one HTTP exchange with an upstream service. | ||
| EventUpstream = "upstream" | ||
| ) | ||
|
|
||
| type requestIDKey struct{} | ||
|
|
||
| // Entry is one proxy activity record. | ||
| type Entry struct { | ||
| Time time.Time `json:"time"` | ||
| Event string `json:"event"` | ||
| RequestID string `json:"request_id,omitempty"` | ||
| Method string `json:"method"` | ||
| Path string `json:"path,omitempty"` | ||
| URL string `json:"url,omitempty"` | ||
| StatusCode int `json:"status_code,omitempty"` | ||
| DurationMS int64 `json:"duration_ms"` | ||
| RemoteAddr string `json:"remote_addr,omitempty"` | ||
| Error string `json:"error,omitempty"` | ||
| } | ||
|
|
||
| // Logger appends complete JSON objects to a file, one per line. | ||
| type Logger struct { | ||
| mu sync.Mutex | ||
| file *os.File | ||
| encoder *json.Encoder | ||
| } | ||
|
|
||
| // Open opens path for append, creating it with owner-only permissions when needed. | ||
| func Open(path string) (*Logger, error) { | ||
| file, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, accessLogFileMode) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("opening access log: %w", err) | ||
| } | ||
|
|
||
| return &Logger{ | ||
| file: file, | ||
| encoder: json.NewEncoder(file), | ||
| }, nil | ||
| } | ||
|
|
||
| // Write appends an entry to the log. | ||
| func (l *Logger) Write(entry Entry) error { | ||
| if entry.Time.IsZero() { | ||
| entry.Time = time.Now().UTC() | ||
| } | ||
|
|
||
| l.mu.Lock() | ||
| defer l.mu.Unlock() | ||
|
|
||
| if err := l.encoder.Encode(entry); err != nil { | ||
| return fmt.Errorf("writing access log: %w", err) | ||
| } | ||
| return nil | ||
| } | ||
|
|
||
| // Close closes the log file after any active writer finishes. | ||
| func (l *Logger) Close() error { | ||
| l.mu.Lock() | ||
| defer l.mu.Unlock() | ||
|
|
||
| if err := l.file.Close(); err != nil { | ||
| return fmt.Errorf("closing access log: %w", err) | ||
| } | ||
| return nil | ||
| } | ||
|
|
||
| // WithRequestID stores a proxy request ID in ctx. | ||
| func WithRequestID(ctx context.Context, requestID string) context.Context { | ||
| return context.WithValue(ctx, requestIDKey{}, requestID) | ||
| } | ||
|
|
||
| // RequestID returns the proxy request ID stored in ctx. | ||
| func RequestID(ctx context.Context) string { | ||
| requestID, _ := ctx.Value(requestIDKey{}).(string) | ||
| return requestID | ||
| } | ||
|
|
||
| // URLWithoutSecrets returns a URL without user information, query values, or fragments. | ||
| func URLWithoutSecrets(value *url.URL) string { | ||
| if value == nil { | ||
| return "" | ||
| } | ||
|
|
||
| clean := *value | ||
| clean.User = nil | ||
| clean.RawQuery = "" | ||
| clean.ForceQuery = false | ||
| clean.Fragment = "" | ||
| clean.RawFragment = "" | ||
| return clean.String() | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,91 @@ | ||
| package accesslog | ||
|
|
||
| import ( | ||
| "bufio" | ||
| "context" | ||
| "encoding/json" | ||
| "net/url" | ||
| "os" | ||
| "path/filepath" | ||
| "sync" | ||
| "testing" | ||
| ) | ||
|
|
||
| func TestLoggerWritesJSONLines(t *testing.T) { | ||
| path := filepath.Join(t.TempDir(), "access.jsonl") | ||
| logger, err := Open(path) | ||
| if err != nil { | ||
| t.Fatal(err) | ||
| } | ||
|
|
||
| const entries = 20 | ||
| var wg sync.WaitGroup | ||
| for range entries { | ||
| wg.Add(1) | ||
| go func() { | ||
| defer wg.Done() | ||
| if err := logger.Write(Entry{ | ||
| Event: EventUpstream, | ||
| RequestID: "request-id", | ||
| Method: "GET", | ||
| URL: "https://registry.example/packages/example", | ||
| StatusCode: 429, | ||
| }); err != nil { | ||
| t.Errorf("Write: %v", err) | ||
| } | ||
| }() | ||
| } | ||
| wg.Wait() | ||
|
|
||
| if err := logger.Close(); err != nil { | ||
| t.Fatal(err) | ||
| } | ||
|
|
||
| file, err := os.Open(path) | ||
| if err != nil { | ||
| t.Fatal(err) | ||
| } | ||
| defer func() { _ = file.Close() }() | ||
|
|
||
| scanner := bufio.NewScanner(file) | ||
| count := 0 | ||
| for scanner.Scan() { | ||
| var entry Entry | ||
| if err := json.Unmarshal(scanner.Bytes(), &entry); err != nil { | ||
| t.Fatalf("line %d is not JSON: %v", count+1, err) | ||
| } | ||
| if entry.Time.IsZero() { | ||
| t.Errorf("line %d has no time", count+1) | ||
| } | ||
| if entry.StatusCode != 429 { | ||
| t.Errorf("line %d status_code = %d, want 429", count+1, entry.StatusCode) | ||
| } | ||
| count++ | ||
| } | ||
| if err := scanner.Err(); err != nil { | ||
| t.Fatal(err) | ||
| } | ||
| if count != entries { | ||
| t.Errorf("lines = %d, want %d", count, entries) | ||
| } | ||
| } | ||
|
|
||
| func TestRequestID(t *testing.T) { | ||
| ctx := WithRequestID(context.Background(), "abc-123") | ||
| if got := RequestID(ctx); got != "abc-123" { | ||
| t.Errorf("RequestID = %q, want %q", got, "abc-123") | ||
| } | ||
| } | ||
|
|
||
| func TestURLWithoutSecrets(t *testing.T) { | ||
| value, err := url.Parse("https://user:password@registry.example/package.tgz?token=secret#fragment") | ||
| if err != nil { | ||
| t.Fatal(err) | ||
| } | ||
|
|
||
| got := URLWithoutSecrets(value) | ||
| want := "https://registry.example/package.tgz" | ||
| if got != want { | ||
| t.Errorf("URLWithoutSecrets = %q, want %q", got, want) | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.