github.com/machinefi/w3bstream@v1.6.5-rc9.0.20240426031326-b8c7c4876e72/pkg/depends/conf/logger/config.go (about)

     1  package logger
     2  
     3  import (
     4  	"log/slog"
     5  	"os"
     6  
     7  	"github.com/machinefi/w3bstream/pkg/depends/base/consts"
     8  	"github.com/machinefi/w3bstream/pkg/depends/kit/logr"
     9  )
    10  
    11  type Config struct {
    12  	Service string
    13  	Version string
    14  	Level   logr.Level `env:""`
    15  	Output  OutputType `env:""`
    16  	Format  FormatType `env:""`
    17  
    18  	init bool
    19  }
    20  
    21  func (c *Config) SetDefault() {
    22  	if c.Output == 0 {
    23  		c.Output = OUTPUT_TYPE__ALWAYS
    24  	}
    25  	if c.Format == 0 {
    26  		c.Format = FORMAT_TYPE__JSON
    27  	}
    28  }
    29  
    30  func (c *Config) Init() error {
    31  	if !c.init {
    32  		if c.Service == "" {
    33  			c.Service = os.Getenv(consts.EnvProjectName)
    34  		}
    35  		if c.Version == "" {
    36  			c.Version = os.Getenv(consts.EnvProjectVersion)
    37  		}
    38  
    39  		switch c.Level {
    40  		case logr.ErrorLevel:
    41  			gLevel = slog.LevelError
    42  		case logr.WarnLevel:
    43  			gLevel = slog.LevelWarn
    44  		case logr.InfoLevel:
    45  			gLevel = slog.LevelInfo
    46  		case logr.DebugLevel:
    47  			gLevel = slog.LevelDebug
    48  		}
    49  
    50  		gOutput = c.Output
    51  
    52  		var handler slog.Handler
    53  		/*
    54  			skip :[
    55  				1. runtime.Callers,
    56  				2. pkg/depends/conf/logger.(*customJsonHandler).Handle
    57  				3. log/slog.(*Logger).logAttrs
    58  				4. log/slog.(*Logger).LogAttrs
    59  				5. pkg/depends/conf/logger.(*stdoutSpanExporter).ExportSpans
    60  				6. pkg/depends/conf/logger.(*spanMapExporter).ExportSpans
    61  				7. go.opentelemetry.io/otel/sdk/trace.(*simpleSpanProcessor).OnEnd
    62  				8. go.opentelemetry.io/otel/sdk/trace.(*recordingSpan).End
    63  				9. pkg/depends/conf/logger.(*spanLogger).End
    64  			]
    65  		*/
    66  
    67  		switch c.Format {
    68  		case FORMAT_TYPE__TEXT:
    69  			handler = NewTextHandler(0)
    70  		default:
    71  			handler = NewJsonHandler(0)
    72  		}
    73  		gStdLogger = slog.New(handler)
    74  
    75  		c.init = true
    76  	}
    77  	return nil
    78  }
    79  
    80  var (
    81  	// gOutput global output to trace provider option, depends on span's status
    82  	gOutput OutputType
    83  	// gLevel global log level
    84  	gLevel slog.Level
    85  	// gStdLogger just used for stdoutSpanExporter
    86  	gStdLogger *slog.Logger
    87  )