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

2022-09-24 21:15:11 字數 2755 閱讀 4079

因為平時管理的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

程式只上傳當前時間點的日誌檔案,

//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.isdir()

if f.name() == logfilename

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)

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

if hour < 10

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())

logday)

return filename, logday, logmonth

}func getlocalipaddr() string

defer conn.close()

//conn.

":")[0])

return strings.split(conn.localaddr().string(), ":")[0]

}func ftpuploadfile(ftpserver, ftpuser, pw, localfile, remotes**epath, s**ename string)

err = ftp.login(ftpuser, pw)

if err != nil

//注意是 pub/log,不能帶「/」開頭

ftp.changedir("pub/log")

dir, err := ftp.currentdir()

fmt.println(dir)

ftp.maked程式設計客棧ir(remotes**epath)

ftp.changedir(remotesa程式設計客棧vepath)

dir, _ = ftp.currentdir()

fmt.println(dir)

file, err := os.open(localfile)

if err != nil

defer file.close()

err = ftp.stor(s**ename, file)

if err != nil

ftp.logout()

ftp.quit()

fmt.println("success upload file:", localfile)

}本文標題: go語言實現通過ftp庫自動上傳web日誌

本文位址:

Go語言實現Valid Parentheses

write a function called that takes a string of parentheses,and determines if the order of the parentheses is valid.the function should return true if ...

go語言實現鍊錶

宣告結構體 宣告全域性變數,儲存頭結點 var head node var curr node 宣告節點型別 type node struct 建立頭結點 func createheadnode data string node 新增新節點 func addnode data string node...

Go語言實現走迷宮

package main import fmt os exec os time 定義全域性變數 var 定義變數儲存r當前位置 currentrow 1 currentcol 1 定義變數儲存迷宮出口位置 索引 endrow 1 endcol 5 func main 2.定義乙個函式列印地圖 pri...