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
76
77
78
79
80
81
82
83
use std::fs::File;
use std::io::Write;
use std::sync::RwLock;
#[cfg(target_os = "windows")]
use std::os::windows::io::FromRawHandle;
#[cfg(target_os = "windows")]
use std::ffi::c_void;
#[cfg(not(target_os = "windows"))]
use std::os::unix::io::FromRawFd;
use serde::Serialize;
pub struct FdLogger {
pub file: RwLock<File>,
}
#[derive(Serialize)]
struct FdLoggingRecord {
level: String,
message: String,
}
#[cfg(target_os = "windows")]
unsafe fn get_file_from_fd(fd: u64) -> File {
File::from_raw_handle(fd as *mut c_void)
}
#[cfg(not(target_os = "windows"))]
unsafe fn get_file_from_fd(fd: u64) -> File {
File::from_raw_fd(fd as i32)
}
impl FdLogger {
pub unsafe fn new(fd: u64) -> Self {
FdLogger {
file: RwLock::new(get_file_from_fd(fd)),
}
}
}
impl log::Log for FdLogger {
fn enabled(&self, _metadata: &log::Metadata) -> bool {
true
}
fn log(&self, record: &log::Record) {
let payload = FdLoggingRecord {
level: record.level().to_string(),
message: record.args().to_string(),
};
let _ = writeln!(
self.file.write().unwrap(),
"{}",
serde_json::to_string(&payload).unwrap()
);
}
fn flush(&self) {
let _ = self.file.write().unwrap().flush();
}
}