newlisp提供了很多的文件处理函数,由于网络等原因。传递失败的消息可以暂时缓存在本地,为较少原程序的负担,可以利用newlisp脚本做容错处理,将这些失败的消息再次传递到接收端。
日志文件格式是一条消息一行。
newlisp代码如下:
#!/usr/bin/newlisp
(set 'rest-url "http://localhost/collect")
(set 'dir "/home/file/log_file/")
(set 'cmd (string "ls " dir))
(println "cmd: " cmd)
(set 'file (exec cmd))
(define (post-msg msg)
(set 'res (post-url rest-url msg "application/x-www-form-urlencoded" 100000))
(println "res: " res )
(unless (find "ERR: HTTP document empty" res)
;;write a new file when error occur
(append-file (string file-path ".bk") (append msg "\n"))
)
)
(define (parse-file file-name)
(set 'file-path (string dir file-name))
(println file-path)
(set 'f (open file-path "read"))
(while (read-line f)
(set 'msg (current-line))
(println "msg: " msg)
(post-msg msg)
)
)
(dolist (file-name file)
(parse-file file-name)
;;delete file after all lines processed
(delete-file file-path)
)
(exit)
程序主要用到的文件函数包括read-line和current-line。从dolist开始,其中file是遍历文件目录下得到的所有消息文件,parse-file函数是对其中一个消息文件逐行读取,并通过post-msg函数传递给接收端的api. post-msg中的unless表名如果没有传递成功,会把失败的消息再次写到一个新的文件,等到下此运行脚本会再次传递。