Go语言代码自动更新服务器代码分享

前端之家收集整理的这篇文章主要介绍了Go语言代码自动更新服务器代码分享前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
package log

import (
	"io"
	"log"
	"os"
	"runtime"
	"time"
)

type l struct {
	logs  *log.Logger
	level int
	io.Closer
}

func NewLog(HttpLogPath string,level int) *l {
	file,err := os.OpenFile(HttpLogPath,os.O_CREATE|os.O_RDWR,0644)
	if err != nil {
		log.Println("Error",err)
		log.Println("Error","日志输出到标准输出.")
		return nil
	}
	var Log *log.Logger = log.New(os.Stdout,now(),0)
	if file != nil {
		Log = log.New(file,0)
		go flushLogFile(file)
	}
	file.Seek(0,2)
	return &l{Log,level,file}
}

func now() string {
	return time.Now().Format("2006-01-02 15:04:05 ")
}

func flushLogFile(File *os.File) {
	for _ = range time.NewTicker(50 * time.Second).C {
		if File == nil {
			return
		}
		File.Sync()
	}
}

func (self *l) SetLogLevel(level int) {
	if level > 4 {
		return
	}
	self.level = level
}

func (self *l) Print(v ...interface{}) {
	self.logs.Print(v)
}

func (self *l) Printf(formate string,v ...interface{}) {
	self.logs.Printf(formate,v)
}

func (self *l) Println(v ...interface{}) {
	self.logs.Println(v)
}

func (self *l) PrintfI(formate string,v ...interface{}) {
	if self.level > 1 {
		return
	}
	self.logs.Printf("Info->"+formate,v...)
}

func (self *l) PrintfW(formate string,v ...interface{}) {
	if self.level > 2 {
		return
	}
	self.logs.Printf("Warn->"+formate,v...)
}

func (self *l) PrintfE(formate string,v ...interface{}) {
	if self.level > 3 {
		return
	}
	self.logs.Printf("Error->"+formate,v...)
}

func (self *l) PrintfF(formate string,v ...interface{}) {
	if self.level > 4 {
		return
	}
	self.logs.Fatalf("Fatal->"+formate,v...)
}

func (self *l) InfoPrintf(callers int,formate string,v ...interface{}) {
	_,file,line,ok := runtime.Caller(callers + 1)
	if !ok {
		return
	}
	self.logs.Printf("File->%s Line->%d\n",line)
	self.logs.Printf(formate,v...)
}<pre name="code" class="html">
<pre style="margin-top: 0px; margin-bottom: 0px;"><span style=" color:#0000ff;">package</span><span style=" color:#f57900;"> </span>main
 
import "centerserver/log"
 
func main() {
l := log.NewLog("http.log", 0)
l.InfoPrintf(0, "%s\n", "错误在这里↑")
l.PrintfI("%s\n", "Info")
l.PrintfW("%s\n", "Warn")
l.PrintfE("%s\n", "Error")
l.PrintfF("%s\n", "Fatal")
}
 
 

 
</pre><pre name="code" class="html">
原文链接:https://www.f2er.com/go/189976.html

猜你在找的Go相关文章