1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 use lightning::util::logger::{Logger, Record};
11 use std::sync::{Arc, Mutex};
14 pub trait Output : Clone + 'static {
15 fn locked_write(&self, data: &[u8]);
20 impl Output for DevNull {
21 fn locked_write(&self, _data: &[u8]) {}
24 pub struct StringBuffer(Arc<Mutex<String>>);
25 impl Output for StringBuffer {
26 fn locked_write(&self, data: &[u8]) {
27 self.0.lock().unwrap().push_str(&String::from_utf8(data.to_vec()).unwrap());
31 pub fn new() -> Self {
32 Self(Arc::new(Mutex::new(String::new())))
34 pub fn into_string(self) -> String {
35 Arc::try_unwrap(self.0).unwrap().into_inner().unwrap()
39 pub struct TestLogger<Out : Output> {
43 impl<Out: Output> TestLogger<Out> {
44 pub fn new(id: String, out: Out) -> TestLogger<Out> {
45 TestLogger { id, out }
49 struct LockedWriteAdapter<'a, Out: Output>(&'a Out);
50 impl<'a, Out: Output> Write for LockedWriteAdapter<'a, Out> {
51 fn write(&mut self, data: &[u8]) -> Result<usize, std::io::Error> {
52 self.0.locked_write(data);
55 fn flush(&mut self) -> Result<(), std::io::Error> { Ok(()) }
58 impl<Out: Output> Logger for TestLogger<Out> {
59 fn log(&self, record: Record) {
60 write!(LockedWriteAdapter(&self.out),
61 "{:<5} {} [{} : {}] {}\n", record.level.to_string(), self.id, record.module_path, record.line, record.args)