因为平时管理的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以上所述就是本文的全部内容了,希望大家能够喜欢。
查看更多关于go语言实现通过FTP库自动上传web日志的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://www.haodehen.cn/did18580