2016-08-26 51 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