6
6
"fmt"
7
7
"io"
8
8
"net/http"
9
+ "strings"
9
10
10
11
"github.com/pkg/errors"
11
12
"github.com/rs/zerolog"
@@ -14,7 +15,21 @@ import (
14
15
const defaultNetworkLogLevel = zerolog .DebugLevel
15
16
const extendedNetworkLogLevel = zerolog .TraceLevel
16
17
const maxNumberOfRequestBodyCharacters = 60
17
- const maxNumberOfResponseBodyCharacters = - 1 // log complete response body
18
+ const maxNumberOfResponseBodyCharacters = 10 * 1024 // 10KiB, to ensure we don't log an entire CLI download response that is interrupted.
19
+
20
+ // Binary content types that should not have their response bodies logged to avoid memory issues
21
+ var binaryMIMETypes = []string {
22
+ "application/octet-stream" , // Standard binary MIME type
23
+ "binary/octet-stream" , // Non-standard but sometimes used
24
+ "application/zip" , // ZIP archives
25
+ "application/gzip" , // GZIP archives
26
+ "application/x-gzip" , // Alternative GZIP MIME type
27
+ "application/x-tar" , // TAR archives
28
+ "application/x-executable" , // Executable files
29
+ "application/x-msdownload" , // Windows executables
30
+ "application/x-mach-binary" , // macOS binaries
31
+ "application/x-elf" , // Linux ELF binaries
32
+ }
18
33
19
34
func shouldNotLog (currentLevel zerolog.Level , levelToLogAt zerolog.Level ) bool {
20
35
// Don't log if logger level is above the threshold
@@ -109,6 +124,17 @@ func shortenStringFromCenter(str string, maxCharacters int64) string {
109
124
return str
110
125
}
111
126
127
+ // isBinaryContent checks if the content type indicates binary data that shouldn't be logged
128
+ func isBinaryContent (contentType string ) bool {
129
+ mimeType := strings .ToLower (strings .TrimSpace (strings .Split (contentType , ";" )[0 ]))
130
+ for _ , binaryMIMEType := range binaryMIMETypes {
131
+ if mimeType == binaryMIMEType {
132
+ return true
133
+ }
134
+ }
135
+ return false
136
+ }
137
+
112
138
func LogRequest (r * http.Request , logger * zerolog.Logger ) {
113
139
if shouldNotLog (logger .GetLevel (), defaultNetworkLogLevel ) { // Don't log if logger level is above the threshold
114
140
return
@@ -141,6 +167,12 @@ func LogResponse(response *http.Response, logger *zerolog.Logger) {
141
167
return
142
168
}
143
169
170
+ // Skip response body logging for binary content to avoid memory issues with large binary downloads.
171
+ if isBinaryContent (response .Header .Get ("Content-Type" )) {
172
+ logger .WithLevel (defaultNetworkLogLevel ).Msgf ("%s body: [BINARY CONTENT - NOT LOGGED]" , logPrefixResponse )
173
+ return
174
+ }
175
+
144
176
logBody (logger , defaultNetworkLogLevel , logPrefixResponse , getResponseBody (response ), response .Header , maxNumberOfResponseBodyCharacters )
145
177
}
146
178
}
0 commit comments