-
Notifications
You must be signed in to change notification settings - Fork 0
/
log.ml
70 lines (60 loc) · 1.6 KB
/
log.ml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
(*
* Author: Kaustuv Chaudhuri <kaustuv.chaudhuri@inria.fr>
* Copyright (C) 2013 Inria (Institut National de Recherche
* en Informatique et en Automatique)
* See LICENSE for licensing details.
*)
open Batteries
type loglevel =
| FATAL | ERROR | WARN | INFO | DEBUG | TRACE
let lev_string = function
| FATAL -> "FATAL"
| ERROR -> "ERROR"
| WARN -> "WARN"
| INFO -> "INFO"
| DEBUG -> "DEBUG"
| TRACE -> "TRACE"
let loglevel = ref WARN
let logging = ref false
let logdest = ref stdout
let log ?force lev fmt =
let ouch =
begin match force with
| Some ch -> Some ch
| None ->
if !logging && lev <= !loglevel
then Some !logdest
else None
end in
let fmt = fmt ^^ "\n" in
begin match ouch with
| Some ch ->
if lev >= ERROR then Printf.fprintf ch "[%s] " (lev_string lev) ;
Printf.fprintf ch (fmt ^^ "\n%!")
| None ->
Printf.ifprintf () fmt
end
let file_channels : (string, unit BatIO.output) Map.t ref = ref Map.empty
let reset () =
loglevel := WARN ;
logging := false ;
logdest := stdout ;
Map.iter (fun nm ch ->
log ~force:stdout TRACE "Closing %S" nm ;
close_out ch
) !file_channels ;
file_channels := Map.empty
let to_stdout () =
logging := true ;
logdest := stdout
let to_file f =
logging := true ;
log ~force:stdout TRACE "Logging to %S" f ;
if Map.mem f !file_channels then
logdest := Map.find f !file_channels
else begin
let ch = open_out_bin f in
file_channels := Map.add f ch !file_channels ;
logdest := ch
end
let eprintf fmt = log ~force:stderr FATAL fmt