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...)
}
package main
import"centerserver/log"
funcmain(){
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")
}
总结
如果觉得编程之家网站内容还不错,欢迎将编程之家网站推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
下一篇: cocosCreator 发射事件