Download The demexp Book - Linux
Transcript
However, redirect logs to file can be called when command line options are parsed to redirect normal and debug logs to a file named filename. In case filename is “-”, the logs are redirected to standard output. 176a hsrvflags.ml 175ai+≡ / 175c 176b . let redirect_logs_to_file () = if !flag_log_filename = "" then failwith "internal error: Srvflags.redirect_logs_to_file"; if !flag_log_filename = "-" then ( log_formatter := Format.std_formatter; debug_formatter := Format.std_formatter ) else ( try let oc = open_out !flag_log_filename in let fmt = Format.formatter_of_out_channel oc in log_formatter := fmt; debug_formatter := fmt with Sys_error str -> Format.eprintf "ERROR: cannot open log file ’%s’: %s\n" !flag_log_filename str ) Helper function current time as string returns current time in international ISO-8601 string format. 176b hsrvflags.ml 175ai+≡ let current_time_as_iso_string () = Time.time_as_localtime_iso_string (Unix.time ()) / 176a 176c . We define the helper function dbg which prints on output its arguments only if flag debug is true. dbg can be used in the same way as printf. The trick here is to call kprintf as last expression in the function: http://caml.inria.fr/archives/ 200405/msg00355.html. 176c hsrvflags.ml 175ai+≡ let dbg fmt = let print_if_necessary str = if !flag_debug then ( let id = Thread.id (Thread.self ()) in Format.fprintf !debug_formatter "<%d>%s@[ %s@]@." id (current_time_as_iso_string ()) str; ) in Format.kprintf print_if_necessary fmt / 176b 176d . Helper function log is similar to dbg, but print its output to standard output. 176d hsrvflags.ml 175ai+≡ let log fmt = let print str = let id = Thread.id (Thread.self ()) in Format.fprintf !log_formatter "<%d>%s@[ %s@]@." id (current_time_as_iso_string ()) str in Format.kprintf print fmt 176 / 176c