github.com/ericwq/aprilsh@v0.0.0-20240517091432-958bc568daa0/util/log.go (about)

     1  // Copyright 2022~2024 wangqi. All rights reserved.
     2  // Use of this source code is governed by a MIT-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package util
     6  
     7  import (
     8  	"context"
     9  	"io"
    10  	"os"
    11  
    12  	"log/slog"
    13  )
    14  
    15  const (
    16  	LevelTrace = slog.Level(-8)
    17  	LevelFatal = slog.Level(12)
    18  	DebugLevel = 1
    19  	TraceLevel = 2
    20  )
    21  
    22  var Logger *myLogger
    23  var levelNames = map[slog.Leveler]string{
    24  	LevelTrace: "TRACE",
    25  	LevelFatal: "FATAL",
    26  }
    27  
    28  type myLogger struct {
    29  	*slog.Logger
    30  	// addSource bool
    31  	// logLevel  *slog.LevelVar
    32  }
    33  
    34  func init() {
    35  	// default logger write to stderr
    36  	Logger = new(myLogger)
    37  	// Logger.logLevel = new(slog.LevelVar)
    38  	// Logger.SetLevel(slog.LevelInfo)
    39  	// // Logger.AddSource(false)
    40  	// Logger.SetOutput(os.Stderr)
    41  	Logger.CreateLogger(os.Stderr, false, slog.LevelInfo)
    42  }
    43  
    44  // func (l *myLogger) SetLevel(v slog.Level) {
    45  // 	l.logLevel.Set(v)
    46  // }
    47  
    48  // func (l *myLogger) AddSource(add bool) {
    49  // 	Logger.addSource = add
    50  // }
    51  
    52  // how to replace a line in file,sample
    53  // sed -i 's/.*defer util\.Log\.Restore.*//g' encrypt/encrypt_test.go
    54  //
    55  
    56  //	func (l *myLogger) SetOutput(w io.Writer) {
    57  //		ho := &slog.HandlerOptions{
    58  //			AddSource: Logger.addSource,
    59  //			Level:     Logger.logLevel,
    60  //			ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
    61  //				if a.Key == slog.LevelKey {
    62  //					level := a.Value.Any().(slog.Level)
    63  //					levelLabel, exists := levelNames[level]
    64  //					if !exists {
    65  //						levelLabel = level.String()
    66  //					}
    67  //
    68  //					a.Value = slog.StringValue(levelLabel)
    69  //				}
    70  //
    71  //				return a
    72  //			},
    73  //		}
    74  //		l.Logger = slog.New(slog.NewTextHandler(w, ho)).With("pid", os.Getpid())
    75  //		slog.SetDefault(l.Logger)
    76  //	}
    77  
    78  func (l *myLogger) CreateLogger(w io.Writer, source bool, level slog.Level) {
    79  	ho := &slog.HandlerOptions{
    80  		AddSource: source,
    81  		Level:     level,
    82  		ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
    83  			if a.Key == slog.LevelKey {
    84  				level := a.Value.Any().(slog.Level)
    85  				levelLabel, exists := levelNames[level]
    86  				if !exists {
    87  					levelLabel = level.String()
    88  				}
    89  
    90  				a.Value = slog.StringValue(levelLabel)
    91  			}
    92  
    93  			return a
    94  		},
    95  	}
    96  	l.Logger = slog.New(slog.NewTextHandler(w, ho)).With("pid", os.Getpid())
    97  	// slog.SetDefault(l.Logger)
    98  }
    99  
   100  func (l *myLogger) Trace(msg string, args ...any) {
   101  	l.Logger.Log(context.Background(), LevelTrace, msg, args...)
   102  }
   103  
   104  // network: udp, address: localhost:514. check net.Dial() for detail
   105  // func (l *logger) SetupSyslog(network string, address string) error {
   106  // 	writer, err := net.Dial(network, address)
   107  // 	// writer, err := syslog.New(syslog.LOG_DAEMON|syslog.LOG_LOCAL7, "aprilsh")
   108  // 	if err != nil {
   109  // 		return err
   110  // 	}
   111  //
   112  // 	ho := &slog.HandlerOptions{AddSource: l.isDebugLevel(), Level: Log.programLevel}
   113  // 	l.Logger = slog.New(slog.NewTextHandler(writer, ho))
   114  // 	slog.SetDefault(Log.Logger)
   115  // 	l.defaultLogger = slog.Default()
   116  // 	return nil
   117  // }
   118  
   119  // // create log file based on prefix under tmp directory. such as aprilsh-PID.log
   120  // func (l *logger) CreateLogFile(prefix string) (*os.File, error) {
   121  // 	name := joinPath(os.TempDir(), fmt.Sprintf("%s-%d.%s", prefix, os.Getpid(), "log"))
   122  // 	file, err := os.OpenFile(name, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0600)
   123  // 	if err != nil {
   124  // 		return nil, err
   125  // 	}
   126  //
   127  // 	return file, nil
   128  // }
   129  
   130  // func joinPath(dir, name string) string {
   131  // 	if len(dir) > 0 && os.IsPathSeparator(dir[len(dir)-1]) {
   132  // 		return dir + name
   133  // 	}
   134  // 	return dir + string(os.PathSeparator) + name
   135  // }