...

Source file src/cdr.dev/slog/s.go

Documentation: cdr.dev/slog

     1  package slog
     2  
     3  import (
     4  	"context"
     5  	"log"
     6  	"strings"
     7  )
     8  
     9  // Stdlib creates a standard library logger from the given logger.
    10  //
    11  // All logs will be logged at the level set by the logger and the
    12  // given ctx will be passed to the logger's Log method, thereby
    13  // logging all fields and tracing info in the context.
    14  //
    15  // You can redirect the stdlib default logger with log.SetOutput
    16  // to the Writer on the logger returned by this function.
    17  // See the example.
    18  func Stdlib(ctx context.Context, l Logger, level Level) *log.Logger {
    19  	l.skip += 2
    20  
    21  	l = l.Named("stdlib")
    22  
    23  	w := &stdlogWriter{
    24  		ctx:   ctx,
    25  		l:     l,
    26  		level: level,
    27  	}
    28  
    29  	return log.New(w, "", 0)
    30  }
    31  
    32  type stdlogWriter struct {
    33  	ctx   context.Context
    34  	l     Logger
    35  	level Level
    36  }
    37  
    38  func (w stdlogWriter) Write(p []byte) (n int, err error) {
    39  	msg := string(p)
    40  	// stdlib includes a trailing newline on the msg that
    41  	// we do not want.
    42  	msg = strings.TrimSuffix(msg, "\n")
    43  
    44  	w.l.log(w.ctx, w.level, msg, Map{})
    45  
    46  	return len(p), nil
    47  }
    48  

View as plain text