Go语言自己实现的异步小log程序.

前端之家收集整理的这篇文章主要介绍了Go语言自己实现的异步小log程序.前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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.f2er.com/go/190183.html

猜你在找的Go相关文章