go.charczuk.com@v0.0.0-20240327042549-bc490516bd1a/sdk/logutil/new.go (about)

     1  /*
     2  
     3  Copyright (c) 2023 - Present. Will Charczuk. All rights reserved.
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file at the root of the repository.
     5  
     6  */
     7  
     8  package logutil
     9  
    10  import (
    11  	"io"
    12  	"log"
    13  	"os"
    14  )
    15  
    16  // DefaultFlags are the default logger flags.
    17  const DefaultFlags = log.Lshortfile | log.Ldate | log.Ltime | log.Lmicroseconds | Linfo | Lwarn | Lerror | Ldebug
    18  
    19  // Logger flags to enable specific message types.
    20  const (
    21  	Ldebug = log.Lmsgprefix << (1 + iota)
    22  	Linfo
    23  	Lwarn
    24  	Lerror
    25  )
    26  
    27  // New returns a new logger
    28  func New(opts ...Option) *log.Logger {
    29  	l := log.New(os.Stdout, "", DefaultFlags)
    30  	for _, opt := range opts {
    31  		opt(l)
    32  	}
    33  	return l
    34  }
    35  
    36  // Option mutates a logger.
    37  type Option func(*log.Logger)
    38  
    39  // OptConfig sets the output of the logger.
    40  func OptConfig(cfg Config) Option {
    41  	return func(l *log.Logger) {
    42  		if cfg.Disabled {
    43  			l.SetOutput(io.Discard)
    44  			return
    45  		}
    46  		l.SetFlags(cfg.ParsedFlags())
    47  	}
    48  }
    49  
    50  // OptOutput sets the output of the logger.
    51  func OptOutput(wr io.Writer) Option {
    52  	return func(l *log.Logger) {
    53  		l.SetOutput(wr)
    54  	}
    55  }
    56  
    57  // OptFlags sets the flags on the logger.
    58  func OptFlags(flags int) Option {
    59  	return func(l *log.Logger) {
    60  		l.SetFlags(flags)
    61  	}
    62  }
    63  
    64  // OptFlagEnable enables flags on the logger.
    65  func OptFlagEnable(flags ...int) Option {
    66  	return func(l *log.Logger) {
    67  		var composite int
    68  		for _, f := range flags {
    69  			composite = composite | f
    70  		}
    71  		l.SetFlags(l.Flags() | composite)
    72  	}
    73  }
    74  
    75  // OptPrefix sets the prefix on the logger.
    76  func OptPrefix(prefix string) Option {
    77  	return func(l *log.Logger) {
    78  		l.SetPrefix(prefix)
    79  	}
    80  }