您的位置:首页 > 编程语言 > Go语言

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

2016-01-27 20:11 696 查看
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, now(), 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", file, 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">
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Go语言 go golang1.5 golang