在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
以追加的方式将程序输出到不同的日志文件,当日志文件超过10M大小时,自动清空文件。 package tools import ( "fmt" "log" "os" ) const logDir string = "/usr/local/dbmng/log/" func PathExists(path string) bool { _, err := os.Stat(path) if err == nil { return true } if os.IsNotExist(err) { return false } return false } func CreateDir(dir string) { if !PathExists(dir) { err := os.Mkdir(dir, os.ModePerm) if err != nil { fmt.Printf("mkdir failed![%v]\n", err) } } } //日志分类,不同用途的日志记录于不同的文件 func LogInfo(msg string) { fileName := "/usr/local/dbmng/log/info.log" //logFile,err := os.Create(fileName) LogClearFile(fileName) logFile, err := os.OpenFile(fileName, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666) defer logFile.Close() if err != nil { log.Fatalln("open file error") } debugLog := log.New(logFile, "[Info]", log.LstdFlags) debugLog.Println(msg) } func LogInfoDbVip(msg string) { fileName := "/usr/local/dbmng/log/info_dbvip.log" LogClearFile(fileName) logFile, err := os.OpenFile(fileName, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666) defer logFile.Close() if err != nil { log.Fatalln("open file error") } debugLog := log.New(logFile, "[Info]", log.LstdFlags) debugLog.Println(msg) } // 日志大于10M 时清空一次,目录不存在时会自动创建,没有测试父级目录不存在会不会创建 func LogClearFile(fileName string) { CreateDir(logDir) if PathExists(fileName) { fileInfo, _ := os.Stat(fileName) //文件大小 filesize := fileInfo.Size() if filesize > 12328960 { // 大于10M时清空一次 os.Create(fileName) } } } func LogWarning(msg string) { fileName := "/usr/local/dbmng/log/warning.log" LogClearFile(fileName) logFile, err := os.OpenFile(fileName, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666) defer logFile.Close() if err != nil { log.Fatalln("open file error") } debugLog := log.New(logFile, "[Warning]", log.LstdFlags) debugLog.Println(msg) } func showUsing() { fileName := "Info_First.log" logFile, err := os.Create(fileName) defer logFile.Close() if err != nil { log.Fatalln("open file error") } debugLog := log.New(logFile, "[Info]", log.Llongfile) debugLog.Println("A Info message here") debugLog.SetPrefix("[Debug]") debugLog.Println("A Debug Message here ") } /* func main(){ LogInfo("普通测试") LogInfoDbVip("第一次测试 ") LogWarning("第二次测试 ") } */
|
请发表评论