加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-16 18:38:54 所属栏目:大数据 来源:网络整理
导读: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 := Logge

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")
	}
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读