github.com/mdaxf/iac@v0.0.0-20240519030858-58a061660378/vendor_skip/go.mongodb.org/mongo-driver/internal/logger/io_sink.go (about)

     1  // Copyright (C) MongoDB, Inc. 2023-present.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License"); you may
     4  // not use this file except in compliance with the License. You may obtain
     5  // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
     6  
     7  package logger
     8  
     9  import (
    10  	"encoding/json"
    11  	"io"
    12  	"sync"
    13  	"time"
    14  )
    15  
    16  // IOSink writes a JSON-encoded message to the io.Writer.
    17  type IOSink struct {
    18  	enc *json.Encoder
    19  
    20  	// encMu protects the encoder from concurrent writes. While the logger
    21  	// itself does not concurrently write to the sink, the sink may be used
    22  	// concurrently within the driver.
    23  	encMu sync.Mutex
    24  }
    25  
    26  // Compile-time check to ensure IOSink implements the LogSink interface.
    27  var _ LogSink = &IOSink{}
    28  
    29  // NewIOSink will create an IOSink object that writes JSON messages to the
    30  // provided io.Writer.
    31  func NewIOSink(out io.Writer) *IOSink {
    32  	return &IOSink{
    33  		enc: json.NewEncoder(out),
    34  	}
    35  }
    36  
    37  // Info will write a JSON-encoded message to the io.Writer.
    38  func (sink *IOSink) Info(_ int, msg string, keysAndValues ...interface{}) {
    39  	kvMap := make(map[string]interface{}, len(keysAndValues)/2+2)
    40  
    41  	kvMap[KeyTimestamp] = time.Now().UnixNano()
    42  	kvMap[KeyMessage] = msg
    43  
    44  	for i := 0; i < len(keysAndValues); i += 2 {
    45  		kvMap[keysAndValues[i].(string)] = keysAndValues[i+1]
    46  	}
    47  
    48  	sink.encMu.Lock()
    49  	defer sink.encMu.Unlock()
    50  
    51  	_ = sink.enc.Encode(kvMap)
    52  }
    53  
    54  // Error will write a JSON-encoded error message to the io.Writer.
    55  func (sink *IOSink) Error(err error, msg string, kv ...interface{}) {
    56  	kv = append(kv, KeyError, err.Error())
    57  	sink.Info(0, msg, kv...)
    58  }