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
use super::{Format, LevelFilter};
use bytes::Bytes;
use crossbeam_channel as channel;
use std::io::Write;
use std::sync::Arc;
use std::thread;

/// A destination for log entries written by `Logger` instances.
pub struct LogSink {
  /// Format of the log sink.
  pub(super) format: Format,
  /// Default level for new `Logger` instances.
  pub(super) default_level: LevelFilter,
  /// Sender half of the channel to send log messages for writing.
  sender: Option<channel::Sender<Bytes>>,
  /// Join handle for the thread that writes messages.
  handle: Option<thread::JoinHandle<()>>,
}

impl LogSink {
  /// Creates a new log sink for the given `writer`.
  ///
  /// This function creates a background thread that writes entries sent to the
  /// sink by `Logger` instances.
  pub fn new<W: Write + Send + 'static>(
    mut writer: W,
    format: Format,
    default_level: LevelFilter,
  ) -> Arc<Self> {
    let (sender, receiver) = channel::unbounded::<Bytes>();

    let handle = thread::spawn(move || {
      for bytes in receiver.into_iter() {
        writer
          .write_all(&bytes)
          .expect("could not write bytes to sink writer");

        writer.flush().expect("could not flush sink writer");
      }
    });

    Arc::new(LogSink {
      sender: Some(sender),
      handle: Some(handle),
      format,
      default_level,
    })
  }

  /// Sends the given `Bytes` to be written to the sink.
  pub(super) fn send(&self, entry: Bytes) {
    if let Some(ref sender) = self.sender {
      sender.send(entry);
    }
  }
}

// Implement `Drop` to close the channel and join the background thread.
impl Drop for LogSink {
  fn drop(&mut self) {
    self.sender.take();

    if let Some(handle) = self.handle.take() {
      handle.join().expect("could not join with LogSink thread");
    }
  }
}