日誌的轉儲和壓縮是很是關鍵的,它不只能夠減小硬盤空間佔用,主要還能夠在發生故障時根據日誌定位出故障緣由。下面來看看golang和java的文件轉儲實現。java
go語言:golang
用到了filepath包下的Walk方法,具體說明能夠參看歷史文章:日誌
go語言path/filepath包之Walk源碼解析code
package main import ( "fmt" "os" "io" "archive/zip" "path/filepath" "time" "log" ) func main() { logFile := "D:/tmp/successLog/logs/root.log" backFile := "D:/tmp/successLog/logs/root_" + time.Now().Format("20060102150405") + ".zip" err := zipFile(logFile, backFile) if err != nil { log.Println(fmt.Sprintf("zip file %s to %s error : %v", logFile, backFile, err)) return } else { os.Remove(logFile) } //轉儲後建立新文件 //createFile() //修改文件權限 //os.Chmod(backfile, 0400) //刪除備份文件 //deleteOldBackfiles(dir) } func zipFile(source, target string) error { zipFile, err := os.OpenFile(target, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0440) if err != nil { log.Println(err) return err } defer zipFile.Close() archive := zip.NewWriter(zipFile) defer archive.Close() return filepath.Walk(source, func(path string, info os.FileInfo, err error) error { if err != nil { return err } header, err := zip.FileInfoHeader(info) if err != nil { return err } if !info.IsDir() { header.Method = zip.Deflate } header.SetModTime(time.Now().UTC()) header.Name = path writer, err := archive.CreateHeader(header) if err != nil { return err } if info.IsDir() { return nil } file, err := os.Open(path) if err != nil { return err } defer file.Close() _, err = io.Copy(writer, file) return err }) }