]> git.lizzy.rs Git - rust.git/blob - src/libstd/rt/logging.rs
std: move StrUtil::as_c_str into StrSlice
[rust.git] / src / libstd / rt / logging.rs
1 // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use either::*;
12 use libc;
13
14 pub trait Logger {
15     fn log(&mut self, msg: Either<~str, &'static str>);
16 }
17
18 pub struct StdErrLogger;
19
20 impl Logger for StdErrLogger {
21     fn log(&mut self, msg: Either<~str, &'static str>) {
22         use io::{Writer, WriterUtil};
23
24         if !should_log_console() {
25             return;
26         }
27
28         let s: &str = match msg {
29             Left(ref s) => {
30                 let s: &str = *s;
31                 s
32             }
33             Right(ref s) => {
34                 let s: &str = *s;
35                 s
36             }
37         };
38         let dbg = ::libc::STDERR_FILENO as ::io::fd_t;
39         dbg.write_str(s);
40         dbg.write_str("\n");
41         dbg.flush();
42     }
43 }
44
45 /// Configure logging by traversing the crate map and setting the
46 /// per-module global logging flags based on the logging spec
47 pub fn init(crate_map: *u8) {
48     use os;
49     use str::StrSlice;
50     use ptr;
51     use option::{Some, None};
52
53     let log_spec = os::getenv("RUST_LOG");
54     match log_spec {
55         Some(spec) => {
56             do spec.as_c_str |buf| {
57                 unsafe { rust_update_log_settings(crate_map, buf) }
58             }
59         }
60         None => {
61             unsafe {
62                 rust_update_log_settings(crate_map, ptr::null());
63             }
64         }
65     }
66 }
67
68 pub fn console_on() { unsafe { rust_log_console_on() } }
69 pub fn console_off() { unsafe { rust_log_console_off() } }
70 fn should_log_console() -> bool { unsafe { rust_should_log_console() != 0 } }
71
72 extern {
73     fn rust_update_log_settings(crate_map: *u8, settings: *libc::c_char);
74     fn rust_log_console_on();
75     fn rust_log_console_off();
76     fn rust_should_log_console() -> libc::uintptr_t;
77 }
78