@@ -16,6 +16,7 @@ import (
1616
1717 "go.mongodb.org/mongo-driver/v2/bson"
1818 "go.mongodb.org/mongo-driver/v2/internal/bsoncoreutil"
19+ "go.mongodb.org/mongo-driver/v2/internal/mathutil"
1920 "go.mongodb.org/mongo-driver/v2/x/bsonx/bsoncore"
2021)
2122
@@ -28,8 +29,10 @@ const DefaultMaxDocumentLength = 1000
2829// toward the max document length.
2930const TruncationSuffix = "..."
3031
31- const logSinkPathEnvVar = "MONGODB_LOG_PATH"
32- const maxDocumentLengthEnvVar = "MONGODB_LOG_MAX_DOCUMENT_LENGTH"
32+ const (
33+ logSinkPathEnvVar = "MONGODB_LOG_PATH"
34+ maxDocumentLengthEnvVar = "MONGODB_LOG_MAX_DOCUMENT_LENGTH"
35+ )
3336
3437// LogSink represents a logging implementation, this interface should be 1-1
3538// with the exported "LogSink" interface in the mongo/options package.
@@ -185,7 +188,7 @@ func selectLogSink(sink LogSink) (LogSink, *os.File, error) {
185188 }
186189
187190 if path != "" {
188- logFile , err := os .OpenFile (path , os .O_APPEND | os .O_CREATE | os .O_RDWR , 0666 )
191+ logFile , err := os .OpenFile (path , os .O_APPEND | os .O_CREATE | os .O_RDWR , 0o666 )
189192 if err != nil {
190193 return nil , nil , fmt .Errorf ("unable to open log file: %w" , err )
191194 }
@@ -241,7 +244,13 @@ func FormatDocument(msg bson.Raw, width uint) string {
241244 return "{}"
242245 }
243246
244- str , truncated := bsoncore .Document (msg ).StringN (int (width ))
247+ widthi , err := mathutil.SafeConvertNumeric [int ](width )
248+ if err != nil {
249+ // Propagate warning about width being too large to format.
250+ return "[WARNING] width too large to format document for logging, exceeds max int"
251+ }
252+
253+ str , truncated := bsoncore .Document (msg ).StringN (widthi )
245254
246255 if truncated {
247256 str += TruncationSuffix
@@ -253,7 +262,14 @@ func FormatDocument(msg bson.Raw, width uint) string {
253262// FormatString formats a String for logging. The string is truncated
254263// to the given width.
255264func FormatString (str string , width uint ) string {
256- strTrunc := bsoncoreutil .Truncate (str , int (width ))
265+ var strTrunc string
266+ widthi , err := mathutil.SafeConvertNumeric [int ](width )
267+ if err != nil {
268+ // Propagate warning about width being too large to format.
269+ return "[WARNING] width too large to format string for logging, exceeds max int"
270+ }
271+
272+ strTrunc = bsoncoreutil .Truncate (str , widthi )
257273
258274 // Checks if the string was truncating by comparing the lengths of the two strings.
259275 if len (strTrunc ) < len (str ) {
0 commit comments