2016-08-26 53 views
4

我正在寫一個需要登錄信息但我想將日誌存儲在文件中的球拍程序。我的第一個嘗試是使用「with-logging-to-port」並使用「open-output-file」創建一個輸出端口。球拍:登錄到文件

#lang racket 
(require racket/logging) 
(define (identity/log x) 
    (log-info "returning ~a" x) x) 

(with-logging-to-port (open-output-file "testing.txt") 
    (λ() (identity/log 4)) 'info) 

但是,當我打開文件後,它是空白的!另外,由於「open-output-file」給我一個文件已經存在的錯誤,我不能再運行一次以上。

回答

1

打開與您的文件的標誌'追加。例如:

(open-output-file "testing.txt" #:exists 'append) 
3

我很確定原因是您沒有正確關閉文件。這應該工作:

(let ((out (open-output-file "testing.txt" 
          ; just to not get an error on consecutive runs 
          #:exists 'append))) 
    (with-logging-to-port out 
    (λ() (identity/log 4)) 'info) 
    (close-output-port out)) 

而不是做家政的,你可以使用call-with-output-file

(call-with-output-file "testing.txt" 
    (λ (out) 
    (with-logging-to-port out 
     (λ() (identity/log 4)) 'info)) 
    #:exists 'append) 
2

我給你我的日誌FUNC的源:

(define my_logger (make-logger 'my-log)) 

(define logger_thread #f) 

(define (log fmt . content) 
    (log-message my_logger 'info "" (string-append (format-time (now)) " " (apply format (cons fmt content))))) 

(define (start-logger log_path) 
    (let ([r (make-log-receiver my_logger 'info)] 
     [riqi (format-riqi (now))]) 
    (set! logger_thread 
      (thread 
      (lambda() 
      (let ([log_dir (build-path log_path (substring riqi 0 4))]) 
       (when (not (directory-exists? log_dir)) 
       (make-directory log_dir)) 
       (with-output-to-file 
        (build-path log_path (substring riqi 0 4) riqi) #:exists 'append 
        (lambda() 
        (let loop() 
         (match (sync r) 
         [(vector l m v v1) 
          (printf "~a\n" v) 
          (flush-output)]) 
         (loop)))))))))) 

(define (restart-logger) 
    (kill-thread logger_thread) 
    (start-logger)) 

(define (launch-log-daemon log_path) 
    (start-logger log_path) 
    (thread 
    (lambda() 
    (let loop() 
     (sync 
     (alarm-evt (+ (current-inexact-milliseconds) (* 1000 60 60)))) 
     (when (= 0 (date-hour (seconds->date (current-seconds)))) 
     (restart-logger)) 
     (loop))))) 

在應用程序開始時,你應該運行:

(launch-log-daemon log_path) 

那麼你可以使用它像這樣:

(log "~a:~a" "some1" "some2") 

我使用日期作爲日誌文件的目錄和名稱,

當日期改變時它會自動啓動一個新的日誌文件。

foramt-riqi和格式,時間是在這裏:

(define (format-riqi the_date) 
    (format "~a~a~a" 
      (date-year the_date) 
      (~a (date-month the_date) #:min-width 2 #:pad-string "0" #:align 'right) 
      (~a (number->string (date-day the_date)) #:min-width 2 #:pad-string "0" #:align 'right))) 

(define (format-time the_date) 
    (format "~a:~a:~a" 
      (~a (date-hour the_date) #:min-width 2 #:pad-string "0" #:align 'right) 
      (~a (date-minute the_date) #:min-width 2 #:pad-string "0" #:align 'right) 
      (~a (date-second the_date) #:min-width 2 #:pad-string "0" #:align 'right))) 
+0

什麼是'格式time'和'格式riqi'? –

+1

對不起,請原諒我,很長一段時間不檢查郵件,format-riqi和format-time是我的chinglish功能,意思是格式日期和時間。 – simmone