Debian Codegraph @

third_party/rust/glean-core/src/fd_logger.rs

raw
1 // This Source Code Form is subject to the terms of the Mozilla Public
2 // License, v. 2.0. If a copy of the MPL was not distributed with this
3 // file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5 use std::fs::File;
6 use std::io::Write;
7 use std::sync::RwLock;
8
9 #[cfg(target_os = "windows")]
10 use std::os::windows::io::FromRawHandle;
11
12 #[cfg(target_os = "windows")]
13 use std::ffi::c_void;
14
15 #[cfg(not(target_os = "windows"))]
16 use std::os::unix::io::FromRawFd;
17
18 use serde::Serialize;
19
20 /// An implementation of log::Log that writes log messages in JSON format to a
21 /// file descriptor/handle. The logging level is ignored in this implementation:
22 /// it is up to the receiver of these log messages (on the language binding
23 /// side) to filter the log messages based on their level.
24 /// The JSON payload of each message in an object with the following keys:
25 /// - `level` (string): One of the logging levels defined here:
26 /// https://docs.rs/log/0.4.11/log/enum.Level.html
27 /// - `message` (string): The logging message.
28 pub struct FdLogger {
29 pub file: RwLock<File>,
30 }
31
32 #[derive(Serialize)]
33 struct FdLoggingRecord {
34 level: String,
35 message: String,
36 target: String,
37 }
38
39 #[cfg(target_os = "windows")]
40 unsafe fn get_file_from_fd(fd: u64) -> File {
41 File::from_raw_handle(fd as *mut c_void)
42 }
43
44 #[cfg(not(target_os = "windows"))]
45 unsafe fn get_file_from_fd(fd: u64) -> File {
46 File::from_raw_fd(fd as i32)
47 }
48
49 impl FdLogger {
50 pub unsafe fn new(fd: u64) -> Self {
51 FdLogger {
52 file: RwLock::new(get_file_from_fd(fd)),
53 }
54 }
55 }
56
57 impl log::Log for FdLogger {
58 fn enabled(&self, _metadata: &log::Metadata) -> bool {
59 // This logger always emits logging messages of any level, and the
60 // language binding consuming these messages is responsible for
61 // filtering and routing them.
62 true
63 }
64
65 fn log(&self, record: &log::Record) {
66 // Normally, classes implementing the Log trait would filter based on
67 // the log level here. But in this case, we want to emit all log
68 // messages and let the logging system in the language binding filter
69 // and route them.
70 let payload = FdLoggingRecord {
71 level: record.level().to_string(),
72 message: record.args().to_string(),
73 target: record.target().to_string(),
74 };
75 let _ = writeln!(
76 self.file.write().unwrap(),
77 "{}",
78 serde_json::to_string(&payload).unwrap()
79 );
80 }
81
82 fn flush(&self) {
83 let _ = self.file.write().unwrap().flush();
84 }
85 }