1. 程式人生 > 其它 >go語言實現通過FTP庫自動上傳web日誌

go語言實現通過FTP庫自動上傳web日誌

因為平時管理的web伺服器都是VM伺服器,為節省硬碟空間,一般給虛擬機器分配的硬碟空間都比較小,只有8G,因為,儲存不了多少日誌,所以每天都需要把每臺WEB日誌轉移到一個硬碟比較大的伺服器上,然後再使用NBU集中備份,本程式主要使用go語言實現實現將web日誌通過FTP自動上傳FTP伺服器,使用了filepath.Walk遍歷日誌目錄及第三方純go庫“github.com/jlaffaye/ftp”,而日誌VM本地儲存路徑格式是 /var/log/weblog/www.domainName.com/month/20140616.access.log,

?

// uploadlog
/*
1.本程式主要是實現linux下上傳web日誌使用,
2.使用方法是 uploadlog logfile_dir
程式只上傳當前時間點的日誌檔案,
*/
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解析成一個數據,從而可以得到日誌的域名,注意,如果是linux系統,要用“/”
      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") //去掉前面的四位數年份如"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)
}

以上所述就是本文的全部內容了,希望大家能夠喜歡。