hackerbase/src/logging.scm

89 lines
2.3 KiB
Scheme

;;
;; logging.scm
;;
;; Universal logging module.
;;
;; ISC License
;;
;; Copyright 2023 Brmlab, z.s.
;; Dominik Pantůček <dominik.pantucek@trustica.cz>
;;
;; Permission to use, copy, modify, and/or distribute this software
;; for any purpose with or without fee is hereby granted, provided
;; that the above copyright notice and this permission notice appear
;; in all copies.
;;
;; THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
;; WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
;; WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
;; AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR
;; CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
;; OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
;; NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
;; CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
;;
(declare (unit logging))
(module
logging
(
*log-file*
log-debug
log-info
log-warning
log-error
)
(import scheme
(chicken base)
(chicken format)
(chicken time posix)
util-string)
;; No logging by default
(define *log-file* (make-parameter #f))
;; Opened log file
(define log-file (make-parameter #f))
;; Ensures leading zeroes
(define (format-number2 n)
(format "~A~A"
(if (< n 10) "0" "")
n))
;; Current time for logging
(define (format-current-time)
(let ((ltime (seconds->local-time)))
(format "~A-~A-~A ~A:~A:~A"
(+ 1900 (vector-ref ltime 5))
(format-number2 (add1 (vector-ref ltime 4)))
(format-number2 (vector-ref ltime 3))
(format-number2 (vector-ref ltime 2))
(format-number2 (vector-ref ltime 1))
(format-number2 (vector-ref ltime 0)))))
;; Handles the actual logging
(define ((log-line level) fmt . args)
(when (or (*log-file*)
(log-file))
(when (not (log-file))
(log-file (open-output-file (*log-file*) #:append))
(log-info "Logging started"))
(display (format "~A [~A] ~A"
(format-current-time)
(string-upcase (symbol->string level))
(apply format fmt args))
(log-file))
(newline (log-file))
(flush-output (log-file))))
;; Specific log procedures
(define log-debug (log-line 'debug))
(define log-info (log-line 'info))
(define log-warning (log-line 'warning))
(define log-error (log-line 'error))
)