這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
slog.go
package slogimport ("errors""fmt""os""strings""time")type Logger struct {console boolwarn boolinfo booltformat func() stringfile 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_chango 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 = truereturn log, nilcase "Info":log.warn = truelog.info = truereturn 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", self.tformat(), info)}}func (self *Logger) Warn(info interface{}) {if self.warn && self.console {fmt.Println("Warn", self.tformat(), info)}if self.file != nil {self.file <- fmt.Sprintf("Warn %s %s", self.tformat(), info)}}func (self *Logger) Info(info interface{}) {if self.info && self.console {fmt.Println("Info", self.tformat(), info)}if self.file != nil {self.file <- fmt.Sprintf("Info %s %s", self.tformat(), 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 mainimport ("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, _ := os.Create("log")log, err := slog.NewLog("Info", false, File, 10)if err != nil {fmt.Println(err)return}defer log.Close()for i := 0; i < b.N; i++ {log.Warn("Nima")}}
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。