package logger import ( "fmt" "io/ioutil" "log" "os" "path" "runtime/debug" "strconv" "strings" "time" ) type Log struct { lastDate string loglist []string } //默认日志等级。error(<3)|info(4)|debug(5) var LogLevel = "5" //日志文件保留最近的份数 var KeepCount = 7 var Logger = new(Log) func (c *Log) Init() { log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile) logfilename := time.Now().Format("20060102") + ".log" logFile, err := os.OpenFile("./"+logfilename, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644) if err != nil { log.Panic("创建日志文件异常") os.Exit(1) } log.SetOutput(logFile) c.lastDate = time.Now().Format("2006-01-02") c.loglist = append(c.loglist, logfilename) //清除过期日志文件 go c.clearLogfile() } func (c *Log) Println(obj interface{}) { fmt.Println(fmt.Sprintf("%s:%+v", time.Now().Format("2006-01-02 15:04:05"), obj)) log.Println(fmt.Sprintf("%s:%+v", time.Now().Format("2006-01-02 15:04:05"), obj)) } func (c *Log) Error(obj interface{}, info ...string) { c.makeLogFile() log.Println(fmt.Sprintf(" %s:%+v\n---Strace:%s", "ERROR", obj, string(debug.Stack()))) if len(info) > 0 { log.Println(info) } } func (c *Log) DebugStack(obj interface{}) { if LogLevel >= "5" { c.makeLogFile() log.Println(fmt.Sprintf(" %s:%+v\n---Strace:%s", "Debug", obj, string(debug.Stack()))) } } func (c *Log) InfoStack(obj interface{}) { if LogLevel >= "4" { c.makeLogFile() log.Println(fmt.Sprintf(" %s:%+v\n---Strace:%s", "Info", obj, string(debug.Stack()))) } } func (c *Log) Debug(obj interface{}) { if LogLevel >= "5" { c.makeLogFile() sorce := strings.Split(string(debug.Stack()), "\n")[6:7][0] log.Println(fmt.Sprintf(" %s:%+v \n\t\t\t\t\t\t\t\tsource:%s", "Debug", obj, sorce)) } } func (c *Log) Info(obj interface{}) { if LogLevel >= "4" { c.makeLogFile() sorce := strings.Split(string(debug.Stack()), "\n")[6:7][0] log.Println(fmt.Sprintf(" %s:%+v \n\t\t\t\t\t\t\t\tsource:%s", "Info", obj, sorce)) } } func (c *Log) makeLogFile() { nowdate := time.Now().Format("2006-01-02") if c.lastDate != nowdate { c.Init() } } func (c *Log) clearLogfile() { dir, _ := os.Getwd() files, _ := ioutil.ReadDir(dir) nowday := time.Now().AddDate(0, 0, -1*KeepCount).Format("20060102") nowdayInt, _ := strconv.Atoi(nowday) for _, file := range files { if path.Ext(strings.ToLower(file.Name())) == ".log" { fileFlag := file.ModTime().Format("20060102") fileFlagInt, _ := strconv.Atoi(fileFlag) if fileFlagInt > 0 && fileFlagInt < nowdayInt { os.Remove("./" + file.Name()) } } } }