slog.go
package slog import ( "errors" "fmt" "os" "strings" "time" ) type Logger struct { console bool warn bool info bool tformat func() string file chan string } func NewLog(level string,console bool,File *os.File,buf int) (*Logger,error) { log := &Logger{console: console,tformat: format} if File != nil { FileInfo,err := File.Stat() if err != nil { return nil,err } mode := strings.Split(FileInfo.Mode().String(),"-") if strings.Contains(mode[1],"w") { str_chan := make(chan string,buf) log.file = str_chan go func() { for { fmt.Fprintln(File,<-str_chan) } }() defer func() { for len(str_chan) > 0 { time.Sleep(1e9) } }() } else { return nil,errors.New("can't write.") } } switch level { case "Warn": log.warn = true return log,nil case "Info": log.warn = true log.info = true return log,nil } return nil,errors.New("level must be Warn or Info.") } func (self *Logger) Error(info interface{}) { if self.console { fmt.Println("Error",self.tformat(),info) } if self.file != nil { self.file <- fmt.Sprintf("Error %s %s",info) } } func (self *Logger) Warn(info interface{}) { if self.warn && self.console { fmt.Println("Warn",info) } if self.file != nil { self.file <- fmt.Sprintf("Warn %s %s",info) } } func (self *Logger) Info(info interface{}) { if self.info && self.console { fmt.Println("Info",info) } if self.file != nil { self.file <- fmt.Sprintf("Info %s %s",info) } } func (self *Logger) Close() { for len(self.file) > 0 { time.Sleep(1e8) } } func format() string { return time.Now().Format("2006-01-02 15:04:05") }
slog_test.go
package main import ( "fmt" "os" "slog" "testing" ) func Test_log(T *testing.T) { File,_ := os.Create("log") log,err := slog.NewLog("Info",true,File,10) if err != nil { fmt.Println(err) return } defer log.Close() for i := 0; i < 1000; i++ { log.Warn("Nima") log.Info("Fuck") } } func Benchmark_log(b *testing.B) { File,false,10) if err != nil { fmt.Println(err) return } defer log.Close() for i := 0; i < b.N; i++ { log.Warn("Nima") } }
原文地址:https://www.jb51.cc/go/190183.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。