summaryrefslogtreecommitdiff
path: root/src/logging.rs
blob: e4ebf13f3deea2abb3d5c0ca370687c40a37a146 (plain)
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
// Copyright 2016 Joe Wilm, The Alacritty Project Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//! Logging for alacritty.
//!
//! The main executable is supposed to call `initialize()` exactly once during
//! startup. All logging messages are written to stdout, given that their
//! log-level is sufficient for the level configured in `cli::Options`.
use log;
use std::sync;
use std::io;
use cli;

pub struct Logger<T:Send+io::Write> {
    level: log::LogLevelFilter,
    output: sync::Mutex<T>
}

impl<T> Logger<T> where T:Send+io::Write {
    pub fn new(output: T, level: log::LogLevelFilter) -> Logger<io::LineWriter<T>> {
        Logger { level: level,
                 output: sync::Mutex::new(io::LineWriter::new(output)) }
    }
}


impl<T> log::Log for Logger<T> where T:Send+io::Write {
    fn enabled(&self, metadata: &log::LogMetadata) -> bool {
        metadata.level() <= self.level
    }

    fn log(&self, record: &log::LogRecord) {
        if !self.enabled(record.metadata()) {
            return
        }
        let writer = &mut self.output.lock().unwrap();
        if self.level < log::LogLevelFilter::Debug {
            writer.write(format!("{}\n", record.args()).as_ref()).unwrap();
        } else {
            writer.write(format!("{}: {}\n",
                                 record.target(),
                                 record.args())
                         .as_ref()).unwrap();
        }
    }
}

pub fn initialize(options: &cli::Options) {
    log::set_logger(|max_log_level| {
        max_log_level.set(options.log_level);
        Box::new(Logger::new(io::stdout(), options.log_level))
    }).unwrap_or_else(|e| die!("{}", e));
}