Debian Codegraph @

third_party/rust/android_logger/src/lib.rs

raw
1 // Copyright 2016 The android_logger Developers
2 //
3 // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
4 // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
5 // http://opensource.org/licenses/MIT>, at your option. This file may not be
6 // copied, modified, or distributed except according to those terms.
7
8 //! A logger which writes to android output.
9 //!
10 //! ## Example
11 //!
12 //! ```
13 //! #[macro_use] extern crate log;
14 //! extern crate android_logger;
15 //!
16 //! use log::LevelFilter;
17 //! use android_logger::Config;
18 //!
19 //! /// Android code may not have obvious "main", this is just an example.
20 //! fn main() {
21 //! android_logger::init_once(
22 //! Config::default().with_max_level(LevelFilter::Trace),
23 //! );
24 //!
25 //! debug!("this is a debug {}", "message");
26 //! error!("this is printed by default");
27 //! }
28 //! ```
29 //!
30 //! ## Example with module path filter
31 //!
32 //! It is possible to limit log messages to output from a specific crate,
33 //! and override the logcat tag name (by default, the crate name is used):
34 //!
35 //! ```
36 //! #[macro_use] extern crate log;
37 //! extern crate android_logger;
38 //!
39 //! use log::LevelFilter;
40 //! use android_logger::{Config,FilterBuilder};
41 //!
42 //! fn main() {
43 //! android_logger::init_once(
44 //! Config::default()
45 //! .with_max_level(LevelFilter::Trace)
46 //! .with_tag("mytag")
47 //! .with_filter(FilterBuilder::new().parse("debug,hello::crate=trace").build()),
48 //! );
49 //!
50 //! // ..
51 //! }
52 //! ```
53 //!
54 //! ## Example with a custom log formatter
55 //!
56 //! ```
57 //! use android_logger::Config;
58 //!
59 //! android_logger::init_once(
60 //! Config::default()
61 //! .with_max_level(log::LevelFilter::Trace)
62 //! .format(|f, record| write!(f, "my_app: {}", record.args()))
63 //! )
64 //! ```
65
66 #[cfg(target_os = "android")]
67 extern crate android_log_sys as log_ffi;
68 extern crate once_cell;
69 use once_cell::sync::OnceCell;
70 #[macro_use]
71 extern crate log;
72
73 extern crate env_logger;
74
75 use log::{Level, LevelFilter, Log, Metadata, Record};
76 #[cfg(target_os = "android")]
77 use log_ffi::LogPriority;
78 use std::ffi::{CStr, CString};
79 use std::fmt;
80 use std::mem::{self, MaybeUninit};
81 use std::ptr;
82
83 pub use env_logger::filter::{Builder as FilterBuilder, Filter};
84 pub use env_logger::fmt::Formatter;
85
86 pub(crate) type FormatFn = Box<dyn Fn(&mut dyn fmt::Write, &Record) -> fmt::Result + Sync + Send>;
87
88 /// Output log to android system.
89 #[cfg(target_os = "android")]
90 fn android_log(prio: log_ffi::LogPriority, tag: &CStr, msg: &CStr) {
91 unsafe {
92 log_ffi::__android_log_write(
93 prio as log_ffi::c_int,
94 tag.as_ptr() as *const log_ffi::c_char,
95 msg.as_ptr() as *const log_ffi::c_char,
96 )
97 };
98 }
99
100 /// Dummy output placeholder for tests.
101 #[cfg(not(target_os = "android"))]
102 fn android_log(_priority: Level, _tag: &CStr, _msg: &CStr) {}
103
104 /// Underlying android logger backend
105 pub struct AndroidLogger {
106 config: OnceCell<Config>,
107 }
108
109 impl AndroidLogger {
110 /// Create new logger instance from config
111 pub fn new(config: Config) -> AndroidLogger {
112 AndroidLogger {
113 config: OnceCell::from(config),
114 }
115 }
116
117 fn config(&self) -> &Config {
118 self.config.get_or_init(Config::default)
119 }
120 }
121
122 static ANDROID_LOGGER: OnceCell<AndroidLogger> = OnceCell::new();
123
124 const LOGGING_TAG_MAX_LEN: usize = 23;
125 const LOGGING_MSG_MAX_LEN: usize = 4000;
126
127 impl Default for AndroidLogger {
128 /// Create a new logger with default config
129 fn default() -> AndroidLogger {
130 AndroidLogger {
131 config: OnceCell::from(Config::default()),
132 }
133 }
134 }
135
136 impl Log for AndroidLogger {
137 fn enabled(&self, metadata: &Metadata) -> bool {
138 let config = self.config();
139 // todo: consider __android_log_is_loggable.
140 metadata.level() <= config.log_level.unwrap_or_else(log::max_level)
141 }
142
143 fn log(&self, record: &Record) {
144 let config = self.config();
145
146 if !self.enabled(record.metadata()) {
147 return;
148 }
149
150 // this also checks the level, but only if a filter was
151 // installed.
152 if !config.filter_matches(record) {
153 return;
154 }
155
156 // tag must not exceed LOGGING_TAG_MAX_LEN
157 let mut tag_bytes: [MaybeUninit<u8>; LOGGING_TAG_MAX_LEN + 1] = uninit_array();
158
159 let module_path = record.module_path().unwrap_or_default().to_owned();
160
161 // If no tag was specified, use module name
162 let custom_tag = &config.tag;
163 let tag = custom_tag
164 .as_ref()
165 .map(|s| s.as_bytes())
166 .unwrap_or_else(|| module_path.as_bytes());
167
168 // truncate the tag here to fit into LOGGING_TAG_MAX_LEN
169 self.fill_tag_bytes(&mut tag_bytes, tag);
170 // use stack array as C string
171 let tag: &CStr = unsafe { CStr::from_ptr(mem::transmute(tag_bytes.as_ptr())) };
172
173 // message must not exceed LOGGING_MSG_MAX_LEN
174 // therefore split log message into multiple log calls
175 let mut writer = PlatformLogWriter::new(record.level(), tag);
176
177 // If a custom tag is used, add the module path to the message.
178 // Use PlatformLogWriter to output chunks if they exceed max size.
179 let _ = match (custom_tag, &config.custom_format) {
180 (_, Some(format)) => format(&mut writer, record),
181 (Some(_), _) => fmt::write(
182 &mut writer,
183 format_args!("{}: {}", module_path, *record.args()),
184 ),
185 _ => fmt::write(&mut writer, *record.args()),
186 };
187
188 // output the remaining message (this would usually be the most common case)
189 writer.flush();
190 }
191
192 fn flush(&self) {}
193 }
194
195 impl AndroidLogger {
196 fn fill_tag_bytes(&self, array: &mut [MaybeUninit<u8>], tag: &[u8]) {
197 if tag.len() > LOGGING_TAG_MAX_LEN {
198 for (input, output) in tag
199 .iter()
200 .take(LOGGING_TAG_MAX_LEN - 2)
201 .chain(b"..\0".iter())
202 .zip(array.iter_mut())
203 {
204 output.write(*input);
205 }
206 } else {
207 for (input, output) in tag.iter().chain(b"\0".iter()).zip(array.iter_mut()) {
208 output.write(*input);
209 }
210 }
211 }
212 }
213
214 /// Filter for android logger.
215 #[derive(Default)]
216 pub struct Config {
217 log_level: Option<LevelFilter>,
218 filter: Option<env_logger::filter::Filter>,
219 tag: Option<CString>,
220 custom_format: Option<FormatFn>,
221 }
222
223 impl Config {
224 // TODO: Remove on 0.13 version release.
225 /// **DEPRECATED**, use [`Config::with_max_level()`] instead.
226 #[deprecated(note = "use `.with_max_level()` instead")]
227 pub fn with_min_level(self, level: Level) -> Self {
228 self.with_max_level(level.to_level_filter())
229 }
230
231 /// Changes the maximum log level.
232 ///
233 /// Note, that `Trace` is the maximum level, because it provides the
234 /// maximum amount of detail in the emitted logs.
235 ///
236 /// If `Off` level is provided, then nothing is logged at all.
237 ///
238 /// [`log::max_level()`] is considered as the default level.
239 pub fn with_max_level(mut self, level: LevelFilter) -> Self {
240 self.log_level = Some(level);
241 self
242 }
243
244 fn filter_matches(&self, record: &Record) -> bool {
245 if let Some(ref filter) = self.filter {
246 filter.matches(record)
247 } else {
248 true
249 }
250 }
251
252 pub fn with_filter(mut self, filter: env_logger::filter::Filter) -> Self {
253 self.filter = Some(filter);
254 self
255 }
256
257 pub fn with_tag<S: Into<Vec<u8>>>(mut self, tag: S) -> Self {
258 self.tag = Some(CString::new(tag).expect("Can't convert tag to CString"));
259 self
260 }
261
262 /// Sets the format function for formatting the log output.
263 /// ```
264 /// # use android_logger::Config;
265 /// android_logger::init_once(
266 /// Config::default()
267 /// .with_max_level(log::LevelFilter::Trace)
268 /// .format(|f, record| write!(f, "my_app: {}", record.args()))
269 /// )
270 /// ```
271 pub fn format<F>(mut self, format: F) -> Self
272 where
273 F: Fn(&mut dyn fmt::Write, &Record) -> fmt::Result + Sync + Send + 'static,
274 {
275 self.custom_format = Some(Box::new(format));
276 self
277 }
278 }
279
280 pub struct PlatformLogWriter<'a> {
281 #[cfg(target_os = "android")]
282 priority: LogPriority,
283 #[cfg(not(target_os = "android"))]
284 priority: Level,
285 len: usize,
286 last_newline_index: usize,
287 tag: &'a CStr,
288 buffer: [MaybeUninit<u8>; LOGGING_MSG_MAX_LEN + 1],
289 }
290
291 impl<'a> PlatformLogWriter<'a> {
292 #[cfg(target_os = "android")]
293 pub fn new_with_priority(priority: log_ffi::LogPriority, tag: &CStr) -> PlatformLogWriter {
294 #[allow(deprecated)] // created an issue #35 for this
295 PlatformLogWriter {
296 priority,
297 len: 0,
298 last_newline_index: 0,
299 tag,
300 buffer: uninit_array(),
301 }
302 }
303
304 #[cfg(target_os = "android")]
305 pub fn new(level: Level, tag: &CStr) -> PlatformLogWriter {
306 Self::new_with_priority(
307 match level {
308 Level::Warn => LogPriority::WARN,
309 Level::Info => LogPriority::INFO,
310 Level::Debug => LogPriority::DEBUG,
311 Level::Error => LogPriority::ERROR,
312 Level::Trace => LogPriority::VERBOSE,
313 },
314 tag,
315 )
316 }
317
318 #[cfg(not(target_os = "android"))]
319 pub fn new(level: Level, tag: &CStr) -> PlatformLogWriter {
320 #[allow(deprecated)] // created an issue #35 for this
321 PlatformLogWriter {
322 priority: level,
323 len: 0,
324 last_newline_index: 0,
325 tag,
326 buffer: uninit_array(),
327 }
328 }
329
330 /// Flush some bytes to android logger.
331 ///
332 /// If there is a newline, flush up to it.
333 /// If ther was no newline, flush all.
334 ///
335 /// Not guaranteed to flush everything.
336 fn temporal_flush(&mut self) {
337 let total_len = self.len;
338
339 if total_len == 0 {
340 return;
341 }
342
343 if self.last_newline_index > 0 {
344 let copy_from_index = self.last_newline_index;
345 let remaining_chunk_len = total_len - copy_from_index;
346
347 self.output_specified_len(copy_from_index);
348 self.copy_bytes_to_start(copy_from_index, remaining_chunk_len);
349 self.len = remaining_chunk_len;
350 } else {
351 self.output_specified_len(total_len);
352 self.len = 0;
353 }
354 self.last_newline_index = 0;
355 }
356
357 /// Flush everything remaining to android logger.
358 pub fn flush(&mut self) {
359 let total_len = self.len;
360
361 if total_len == 0 {
362 return;
363 }
364
365 self.output_specified_len(total_len);
366 self.len = 0;
367 self.last_newline_index = 0;
368 }
369
370 /// Output buffer up until the \0 which will be placed at `len` position.
371 fn output_specified_len(&mut self, len: usize) {
372 let mut last_byte = MaybeUninit::new(b'\0');
373
374 mem::swap(&mut last_byte, unsafe {
375 self.buffer.get_unchecked_mut(len)
376 });
377
378 let msg: &CStr = unsafe { CStr::from_ptr(self.buffer.as_ptr().cast()) };
379 android_log(self.priority, self.tag, msg);
380
381 unsafe { *self.buffer.get_unchecked_mut(len) = last_byte };
382 }
383
384 /// Copy `len` bytes from `index` position to starting position.
385 fn copy_bytes_to_start(&mut self, index: usize, len: usize) {
386 let dst = self.buffer.as_mut_ptr();
387 let src = unsafe { self.buffer.as_ptr().add(index) };
388 unsafe { ptr::copy(src, dst, len) };
389 }
390 }
391
392 impl<'a> fmt::Write for PlatformLogWriter<'a> {
393 fn write_str(&mut self, s: &str) -> fmt::Result {
394 let mut incomming_bytes = s.as_bytes();
395
396 while !incomming_bytes.is_empty() {
397 let len = self.len;
398
399 // write everything possible to buffer and mark last \n
400 let new_len = len + incomming_bytes.len();
401 let last_newline = self.buffer[len..LOGGING_MSG_MAX_LEN]
402 .iter_mut()
403 .zip(incomming_bytes)
404 .enumerate()
405 .fold(None, |acc, (i, (output, input))| {
406 output.write(*input);
407 if *input == b'\n' {
408 Some(i)
409 } else {
410 acc
411 }
412 });
413
414 // update last \n index
415 if let Some(newline) = last_newline {
416 self.last_newline_index = len + newline;
417 }
418
419 // calculate how many bytes were written
420 let written_len = if new_len <= LOGGING_MSG_MAX_LEN {
421 // if the len was not exceeded
422 self.len = new_len;
423 new_len - len // written len
424 } else {
425 // if new length was exceeded
426 self.len = LOGGING_MSG_MAX_LEN;
427 self.temporal_flush();
428
429 LOGGING_MSG_MAX_LEN - len // written len
430 };
431
432 incomming_bytes = &incomming_bytes[written_len..];
433 }
434
435 Ok(())
436 }
437 }
438
439 /// Send a log record to Android logging backend.
440 ///
441 /// This action does not require initialization. However, without initialization it
442 /// will use the default filter, which allows all logs.
443 pub fn log(record: &Record) {
444 ANDROID_LOGGER
445 .get_or_init(AndroidLogger::default)
446 .log(record)
447 }
448
449 /// Initializes the global logger with an android logger.
450 ///
451 /// This can be called many times, but will only initialize logging once,
452 /// and will not replace any other previously initialized logger.
453 ///
454 /// It is ok to call this at the activity creation, and it will be
455 /// repeatedly called on every lifecycle restart (i.e. screen rotation).
456 pub fn init_once(config: Config) {
457 let log_level = config.log_level;
458 let logger = ANDROID_LOGGER.get_or_init(|| AndroidLogger::new(config));
459
460 if let Err(err) = log::set_logger(logger) {
461 debug!("android_logger: log::set_logger failed: {}", err);
462 } else if let Some(level) = log_level {
463 log::set_max_level(level);
464 }
465 }
466
467 // FIXME: When `maybe_uninit_uninit_array ` is stabilized, use it instead of this helper
468 fn uninit_array<const N: usize, T>() -> [MaybeUninit<T>; N] {
469 // SAFETY: Array contains MaybeUninit, which is fine to be uninit
470 unsafe { MaybeUninit::uninit().assume_init() }
471 }
472
473 #[cfg(test)]
474 mod tests {
475 use super::*;
476 use std::fmt::Write;
477 use std::sync::atomic::{AtomicBool, Ordering};
478
479 #[test]
480 fn check_config_values() {
481 // Filter is checked in config_filter_match below.
482 let config = Config::default()
483 .with_max_level(LevelFilter::Trace)
484 .with_tag("my_app");
485
486 assert_eq!(config.log_level, Some(LevelFilter::Trace));
487 assert_eq!(config.tag, Some(CString::new("my_app").unwrap()));
488 }
489
490 #[test]
491 fn log_calls_formatter() {
492 static FORMAT_FN_WAS_CALLED: AtomicBool = AtomicBool::new(false);
493 let config = Config::default()
494 .with_max_level(LevelFilter::Info)
495 .format(|_, _| {
496 FORMAT_FN_WAS_CALLED.store(true, Ordering::SeqCst);
497 Ok(())
498 });
499 let logger = AndroidLogger::new(config);
500
501 logger.log(&Record::builder().level(Level::Info).build());
502
503 assert!(FORMAT_FN_WAS_CALLED.load(Ordering::SeqCst));
504 }
505
506 #[test]
507 fn logger_enabled_threshold() {
508 let logger = AndroidLogger::new(Config::default().with_max_level(LevelFilter::Info));
509
510 assert!(logger.enabled(&log::MetadataBuilder::new().level(Level::Warn).build()));
511 assert!(logger.enabled(&log::MetadataBuilder::new().level(Level::Info).build()));
512 assert!(!logger.enabled(&log::MetadataBuilder::new().level(Level::Debug).build()));
513 }
514
515 // Test whether the filter gets called correctly. Not meant to be exhaustive for all filter
516 // options, as these are handled directly by the filter itself.
517 #[test]
518 fn config_filter_match() {
519 let info_record = Record::builder().level(Level::Info).build();
520 let debug_record = Record::builder().level(Level::Debug).build();
521
522 let info_all_filter = env_logger::filter::Builder::new().parse("info").build();
523 let info_all_config = Config::default().with_filter(info_all_filter);
524
525 assert!(info_all_config.filter_matches(&info_record));
526 assert!(!info_all_config.filter_matches(&debug_record));
527 }
528
529 #[test]
530 fn fill_tag_bytes_truncates_long_tag() {
531 let logger = AndroidLogger::new(Config::default());
532 let too_long_tag: [u8; LOGGING_TAG_MAX_LEN + 20] = [b'a'; LOGGING_TAG_MAX_LEN + 20];
533
534 let mut result: [MaybeUninit<u8>; LOGGING_TAG_MAX_LEN + 1] = uninit_array();
535 logger.fill_tag_bytes(&mut result, &too_long_tag);
536
537 let mut expected_result = [b'a'; LOGGING_TAG_MAX_LEN - 2].to_vec();
538 expected_result.extend("..\0".as_bytes());
539 assert_eq!(unsafe { assume_init_slice(&result) }, expected_result);
540 }
541
542 #[test]
543 fn fill_tag_bytes_keeps_short_tag() {
544 let logger = AndroidLogger::new(Config::default());
545 let short_tag: [u8; 3] = [b'a'; 3];
546
547 let mut result: [MaybeUninit<u8>; LOGGING_TAG_MAX_LEN + 1] = uninit_array();
548 logger.fill_tag_bytes(&mut result, &short_tag);
549
550 let mut expected_result = short_tag.to_vec();
551 expected_result.push(0);
552 assert_eq!(unsafe { assume_init_slice(&result[..4]) }, expected_result);
553 }
554
555 #[test]
556 fn platform_log_writer_init_values() {
557 let tag = CStr::from_bytes_with_nul(b"tag\0").unwrap();
558
559 let writer = PlatformLogWriter::new(Level::Warn, tag);
560
561 assert_eq!(writer.tag, tag);
562 // Android uses LogPriority instead, which doesn't implement equality checks
563 #[cfg(not(target_os = "android"))]
564 assert_eq!(writer.priority, Level::Warn);
565 }
566
567 #[test]
568 fn temporal_flush() {
569 let mut writer = get_tag_writer();
570
571 writer
572 .write_str("12\n\n567\n90")
573 .expect("Unable to write to PlatformLogWriter");
574
575 assert_eq!(writer.len, 10);
576 writer.temporal_flush();
577 // Should have flushed up until the last newline.
578 assert_eq!(writer.len, 3);
579 assert_eq!(writer.last_newline_index, 0);
580 assert_eq!(
581 unsafe { assume_init_slice(&writer.buffer[..writer.len]) },
582 "\n90".as_bytes()
583 );
584
585 writer.temporal_flush();
586 // Should have flushed all remaining bytes.
587 assert_eq!(writer.len, 0);
588 assert_eq!(writer.last_newline_index, 0);
589 }
590
591 #[test]
592 fn flush() {
593 let mut writer = get_tag_writer();
594 writer
595 .write_str("abcdefghij\n\nklm\nnopqr\nstuvwxyz")
596 .expect("Unable to write to PlatformLogWriter");
597
598 writer.flush();
599
600 assert_eq!(writer.last_newline_index, 0);
601 assert_eq!(writer.len, 0);
602 }
603
604 #[test]
605 fn last_newline_index() {
606 let mut writer = get_tag_writer();
607
608 writer
609 .write_str("12\n\n567\n90")
610 .expect("Unable to write to PlatformLogWriter");
611
612 assert_eq!(writer.last_newline_index, 7);
613 }
614
615 #[test]
616 fn output_specified_len_leaves_buffer_unchanged() {
617 let mut writer = get_tag_writer();
618 let log_string = "abcdefghij\n\nklm\nnopqr\nstuvwxyz";
619 writer
620 .write_str(log_string)
621 .expect("Unable to write to PlatformLogWriter");
622
623 writer.output_specified_len(5);
624
625 assert_eq!(
626 unsafe { assume_init_slice(&writer.buffer[..log_string.len()]) },
627 log_string.as_bytes()
628 );
629 }
630
631 #[test]
632 fn copy_bytes_to_start() {
633 let mut writer = get_tag_writer();
634 writer
635 .write_str("0123456789")
636 .expect("Unable to write to PlatformLogWriter");
637
638 writer.copy_bytes_to_start(3, 2);
639
640 assert_eq!(
641 unsafe { assume_init_slice(&writer.buffer[..10]) },
642 "3423456789".as_bytes()
643 );
644 }
645
646 #[test]
647 fn copy_bytes_to_start_nop() {
648 let test_string = "Test_string_with\n\n\n\nnewlines\n";
649 let mut writer = get_tag_writer();
650 writer
651 .write_str(test_string)
652 .expect("Unable to write to PlatformLogWriter");
653
654 writer.copy_bytes_to_start(0, 20);
655 writer.copy_bytes_to_start(10, 0);
656
657 assert_eq!(
658 unsafe { assume_init_slice(&writer.buffer[..test_string.len()]) },
659 test_string.as_bytes()
660 );
661 }
662
663 fn get_tag_writer() -> PlatformLogWriter<'static> {
664 PlatformLogWriter::new(Level::Warn, CStr::from_bytes_with_nul(b"tag\0").unwrap())
665 }
666
667 unsafe fn assume_init_slice<T>(slice: &[MaybeUninit<T>]) -> &[T] {
668 &*(slice as *const [MaybeUninit<T>] as *const [T])
669 }
670 }