newlisp按行處理日誌文件

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表名如果沒有傳遞成功,會把失敗的消息再次寫到一個新的文件,等到下此運行腳本會再次傳遞。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章