因為平時管理的web服務(wù)器都是VM服務(wù)器,為節(jié)省硬盤空間,一般給虛擬機分配的硬盤空間都比較小,只有8G,因為,保存不了多少日志,所以每天都需要把每臺WEB日志轉(zhuǎn)移到一個硬盤比較大的服務(wù)器上,然后再使用NBU集中備份,本程序主要使用go語言實現(xiàn)實現(xiàn)將web日志通過FTP自動上傳FTP服務(wù)器,使用了filepath.Walk遍歷日志目錄及第三方純go庫“github.com/jlaffaye/ftp”,而日志VM本地存儲路徑格式是 /var/log/weblog/www.domainName.com/month/20140616.access.log,
// uploadlog
/*
1.本程序主要是實現(xiàn)linux下上傳web日志使用,
2.使用方法是 uploadlog logfile_dir
程序只上傳當(dāng)前時間點的日志文件,
*/
package main
import (
"fmt"
ftp "github.com/jlaffaye/ftp"
"log"
"net"
"os"
"path/filepath"
"strconv"
"strings"
"time"
)
func main() {
fmt.Println("Hello World!")
if len(os.Args) != 2 {
log.Fatal("Usage:" + filepath.Base(os.Args[0]) + " log_dir ")
os.Exit(1)
}
//logFileName是將要分析的日志
logFileName, _, _ := getLogFileName()
serverIp := getLocalIpAddr()
//serverName, _ := os.Hostname()
time.Sleep(time.Duration(90) * time.Second)
dir := os.Args[1]
filepath.Walk(dir, func(path string, f os.FileInfo, err error) error {
if f == nil {
return err
}
if f.IsDir() {
return nil
}
if f.Name() == logFileName {
fmt.Println(path)
//pathFields的作用是將日志path解析成一個數(shù)據(jù),從而可以得到日志的域名,注意,如果是linux系統(tǒng),要用“/”
pathFields := strings.Split(path, "\")
var domainName string
if len(pathFields) > 3 {
domainName = pathFields[len(pathFields)-3]
}
fmt.Println(time.Now())
ftpUploadFile("ftp-server-ip:21", "logftpuser", "ftp-password", path, domainName, serverIp+"_"+logFileName)
fmt.Println(time.Now())
}
return nil
})
}
func getLogFileName() (string, string, string) {
MonthTOstr := map[string]string{"January": "01",
"February": "02",
"March": "03",
"April": "04",
"May": "05",
"June": "06",
"July": "07",
"August": "08",
"September": "09",
"October": "10",
"November": "11",
"December": "12"}
timenow := time.Now()
year, month, day := timenow.Date()
//monthStr := month.String()
hour, _, _ := timenow.Clock()
yearStr := strings.TrimLeft(strconv.Itoa(year), "20") //去掉前面的四位數(shù)年份如"2014"年的“20”
dayStr, hourStr := strconv.Itoa(day), strconv.Itoa(hour)
if day 10 {
dayStr = "0" + dayStr
}
if hour 10 {
hourStr = "0" + hourStr
}
fileName := "ex" + yearStr + MonthTOstr[month.String()] + dayStr + hourStr + ".log"
logDay := yearStr + MonthTOstr[month.String()] + dayStr
logMonth := yearStr + MonthTOstr[month.String()]
//monthSrt := strconv.Itoa(timenow.Month())
//fmt.Println(fileName, logDay)
return fileName, logDay, logMonth
//fmt.Println(fileName)
}
func getLocalIpAddr() string {
//這里使用一個合法的IP就行了,端口隨便,即使沒有打開也行,也許因為使用UDP,如果用TCP的話,對端不打開就會有問題
conn, err := net.Dial("udp", "192.168.8.51:80")
if err != nil {
//fmt.Println(err.Error())
return "127.0.0.1"
}
defer conn.Close()
//fmt.Println(conn.LocalAddr().String())
//conn.
//fmt.Println(strings.Split(conn.LocalAddr().String(), ":")[0])
return strings.Split(conn.LocalAddr().String(), ":")[0]
}
func ftpUploadFile(ftpserver, ftpuser, pw, localFile, remoteSavePath, saveName string) {
ftp, err := ftp.Connect(ftpserver)
if err != nil {
fmt.Println(err)
}
err = ftp.Login(ftpuser, pw)
if err != nil {
fmt.Println(err)
}
//注意是 pub/log,不能帶“/”開頭
ftp.ChangeDir("pub/log")
dir, err := ftp.CurrentDir()
fmt.Println(dir)
ftp.MakeDir(remoteSavePath)
ftp.ChangeDir(remoteSavePath)
dir, _ = ftp.CurrentDir()
fmt.Println(dir)
file, err := os.Open(localFile)
if err != nil {
fmt.Println(err)
}
defer file.Close()
err = ftp.Stor(saveName, file)
if err != nil {
fmt.Println(err)
}
ftp.Logout()
ftp.Quit()
fmt.Println("success upload file:", localFile)
}