spdlog/sink/
win_debug_sink.rs1use std::{ffi::OsStr, iter::once};
2
3use crate::{
4 formatter::{Formatter, FormatterContext},
5 sink::{GetSinkProp, Sink, SinkProp},
6 ErrorHandler, LevelFilter, Record, Result, StringBuf,
7};
8
9pub struct WinDebugSink {
11 prop: SinkProp,
12}
13
14impl WinDebugSink {
15 #[must_use]
28 pub fn builder() -> WinDebugSinkBuilder {
29 WinDebugSinkBuilder {
30 prop: SinkProp::default(),
31 }
32 }
33
34 #[allow(clippy::new_without_default)]
36 #[deprecated(
37 since = "0.3.0",
38 note = "it may be removed in the future, use `WinDebugSink::builder()` instead"
39 )]
40 #[must_use]
41 pub fn new() -> WinDebugSink {
42 WinDebugSink::builder().build().unwrap()
43 }
44}
45
46impl GetSinkProp for WinDebugSink {
47 fn prop(&self) -> &SinkProp {
48 &self.prop
49 }
50}
51
52impl Sink for WinDebugSink {
53 fn log(&self, record: &Record) -> Result<()> {
54 #[cfg(windows)] use std::os::windows::ffi::OsStrExt;
56
57 let mut string_buf = StringBuf::new();
58 let mut ctx = FormatterContext::new();
59 self.prop
60 .formatter()
61 .format(record, &mut string_buf, &mut ctx)?;
62
63 let wide: Vec<u16> = OsStr::new(&string_buf)
64 .encode_wide()
65 .chain(once(0))
66 .collect();
67 let wide = wide.as_ptr();
68
69 unsafe { winapi::um::debugapi::OutputDebugStringW(wide) }
70
71 Ok(())
72 }
73
74 fn flush(&self) -> Result<()> {
75 Ok(())
76 }
77}
78
79#[allow(missing_docs)]
80pub struct WinDebugSinkBuilder {
81 prop: SinkProp,
82}
83
84impl WinDebugSinkBuilder {
85 #[must_use]
92 pub fn level_filter(self, level_filter: LevelFilter) -> Self {
93 self.prop.set_level_filter(level_filter);
94 self
95 }
96
97 #[must_use]
101 pub fn formatter<F>(self, formatter: F) -> Self
102 where
103 F: Formatter + 'static,
104 {
105 self.prop.set_formatter(formatter);
106 self
107 }
108
109 #[must_use]
113 pub fn error_handler<F: Into<ErrorHandler>>(self, handler: F) -> Self {
114 self.prop.set_error_handler(handler);
115 self
116 }
117
118 pub fn build(self) -> Result<WinDebugSink> {
122 let sink = WinDebugSink { prop: self.prop };
123 Ok(sink)
124 }
125}