This is a creation in Article, where the information may have evolved or changed.
Simple to learn the basic grammar of the Golang/go language, do a timed cut nginx log of the small script exercise, feel very good ~
Script code as follows, install after the script to join the crontab timed run, of course, Golang can also be executed on its own schedule, here to Crontab run, because the Golang process may be killed ....
Package Mainimport ("FMT" "OS" "Path/filepath" "Syscall" "Time" "Strings" "Os/exec" "Io/ioutil") func main () {// Log directory Srcdirpath: = "/usr/local/nginx/logs"//Store cutting log directory Targetdirpath: = "/usr/local/nginx/logs/history"// NGIXN Process ID file Nginxpidpath: = "/usr/local/nginx/logs/nginx.pid"//check for the presence of the cut log directory, create Finfo if not present, errfile: = OS. Stat (Targetdirpath) if Errfile!=nil {errfile: = os. Mkdirall (Targetdirpath, 0777) if errfile! = nil {fmt. Println ("Failed to create log directory:" +errfile.error ()) return}} else if!finfo. Isdir () {fmt. Println (targetdirpath+ "already exists and not a directory") return}//gets the current date as the root of this cut log t: = time. Now () Nowdatetime: = T.format ("2006-01-02") LogPath: = targetdirpath+ "/" +nowdatetime OS. Mkdirall (LogPath, 0777)//get Nginx process id pfile,err: = os. Open (Nginxpidpath) defer pfile. Close () if err! = Nil {fmt. Println ("Not found Nginx pid file") return} piddata,_: = Ioutil. ReadAll (pfile) PID: = string (piddata) PID = strings. Replace (PID, "\ n", "",-1)//Traverse log directory filepath. Walk (Srcdirpath,func (path string, info os. FileInfo, err Error) error {if info. Isdir () {return nil} else {//Get cut log path Targetfilepath: = Strings. Replace (path,srcdirpath,logpath,1) if strings. Index (Targetfilepath, "nginx.pid")! =-1 {return nil}//move file syscall. Rename (Path,targetfilepath)//Create the original file, here is not required, because after restarting Nginx will automatically generate drops//nfile,errcreate: = OS. Create (path)//if errcreate! = nil {//FMT. Println ("Create file Faild:" +errcreate.error ())//}//defer nfile.close ()}return nil})//smooth restart Nginxcmd: = Exec. Command ("Kill", "-USR1", pid) _, Errcmd: = cmd. Output () if errcmd! = nil {fmt. PRINTLN ("Restart Nginx failed:" +errcmd.error ()) return;} Fmt. PRINTLN ("Success")}