-
Notifications
You must be signed in to change notification settings - Fork 456
Expand file tree
/
Copy pathtest_logger.rs
More file actions
75 lines (69 loc) · 1.94 KB
/
test_logger.rs
File metadata and controls
75 lines (69 loc) · 1.94 KB
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
71
72
73
74
75
// This file is Copyright its original authors, visible in version control
// history.
//
// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
// You may not use this file except in accordance with one or both of these
// licenses.
use lightning::util::logger::{Logger, Record};
use std::any::TypeId;
use std::io::Write;
use std::sync::{Arc, Mutex};
pub trait Output: Clone + 'static {
fn locked_write(&self, data: &[u8]);
}
#[derive(Clone)]
pub struct DevNull {}
impl Output for DevNull {
fn locked_write(&self, _data: &[u8]) {}
}
#[derive(Clone)]
pub struct Stdout {}
impl Output for Stdout {
fn locked_write(&self, data: &[u8]) {
std::io::stdout().write_all(data).unwrap();
}
}
#[derive(Clone)]
pub struct StringBuffer(Arc<Mutex<String>>);
impl Output for StringBuffer {
fn locked_write(&self, data: &[u8]) {
self.0.lock().unwrap().push_str(&String::from_utf8(data.to_vec()).unwrap());
}
}
impl StringBuffer {
pub fn new() -> Self {
Self(Arc::new(Mutex::new(String::new())))
}
pub fn into_string(self) -> String {
Arc::try_unwrap(self.0).unwrap().into_inner().unwrap()
}
}
pub struct TestLogger<Out: Output> {
id: String,
out: Out,
}
impl<Out: Output> TestLogger<Out> {
pub fn new(id: String, out: Out) -> TestLogger<Out> {
TestLogger { id, out }
}
}
struct LockedWriteAdapter<'a, Out: Output>(&'a Out);
impl<'a, Out: Output> Write for LockedWriteAdapter<'a, Out> {
fn write(&mut self, data: &[u8]) -> Result<usize, std::io::Error> {
self.0.locked_write(data);
Ok(data.len())
}
fn flush(&mut self) -> Result<(), std::io::Error> {
Ok(())
}
}
impl<Out: Output> Logger for TestLogger<Out> {
fn log(&self, record: Record) {
if TypeId::of::<Out>() == TypeId::of::<DevNull>() {
return;
}
writeln!(LockedWriteAdapter(&self.out), "{:<6} {}", self.id, record).unwrap();
}
}