lib.rs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652
  1. //! A logging framework for eBPF programs.
  2. //!
  3. //! This is the user space side of the [Aya] logging framework. For the eBPF
  4. //! side, see the `aya-log-ebpf` crate.
  5. //!
  6. //! `aya-log` provides the [BpfLogger] type, which reads log records created by
  7. //! `aya-log-ebpf` and logs them using the [log] crate. Any logger that
  8. //! implements the [Log] trait can be used with this crate.
  9. //!
  10. //! # Example:
  11. //!
  12. //! This example uses the [env_logger] crate to log messages to the terminal.
  13. //!
  14. //! ```no_run
  15. //! # let mut bpf = aya::Bpf::load(&[]).unwrap();
  16. //! use aya_log::BpfLogger;
  17. //!
  18. //! // initialize env_logger as the default logger
  19. //! env_logger::init();
  20. //!
  21. //! // start reading aya-log records and log them using the default logger
  22. //! BpfLogger::init(&mut bpf).unwrap();
  23. //! ```
  24. //!
  25. //! With the following eBPF code:
  26. //!
  27. //! ```ignore
  28. //! # let ctx = ();
  29. //! use aya_log_ebpf::{debug, error, info, trace, warn};
  30. //!
  31. //! error!(&ctx, "this is an error message 🚨");
  32. //! warn!(&ctx, "this is a warning message ⚠️");
  33. //! info!(&ctx, "this is an info message ℹ️");
  34. //! debug!(&ctx, "this is a debug message ️🐝");
  35. //! trace!(&ctx, "this is a trace message 🔍");
  36. //! ```
  37. //! Outputs:
  38. //!
  39. //! ```text
  40. //! 21:58:55 [ERROR] xxx: [src/main.rs:35] this is an error message 🚨
  41. //! 21:58:55 [WARN] xxx: [src/main.rs:36] this is a warning message ⚠️
  42. //! 21:58:55 [INFO] xxx: [src/main.rs:37] this is an info message ℹ️
  43. //! 21:58:55 [DEBUG] (7) xxx: [src/main.rs:38] this is a debug message ️🐝
  44. //! 21:58:55 [TRACE] (7) xxx: [src/main.rs:39] this is a trace message 🔍
  45. //! ```
  46. //!
  47. //! [Aya]: https://docs.rs/aya
  48. //! [env_logger]: https://docs.rs/env_logger
  49. //! [Log]: https://docs.rs/log/0.4.14/log/trait.Log.html
  50. //! [log]: https://docs.rs/log
  51. //!
  52. use std::{
  53. fmt::{LowerHex, UpperHex},
  54. io, mem,
  55. net::{Ipv4Addr, Ipv6Addr},
  56. ptr, slice, str,
  57. sync::Arc,
  58. };
  59. use aya_log_common::{Argument, DisplayHint, RecordField, LOG_BUF_CAPACITY, LOG_FIELDS};
  60. use bytes::BytesMut;
  61. use log::{error, Level, Log, Record};
  62. use thiserror::Error;
  63. use aya::{
  64. maps::{
  65. perf::{AsyncPerfEventArray, PerfBufferError},
  66. MapError,
  67. },
  68. util::online_cpus,
  69. Bpf, Pod,
  70. };
  71. /// Log messages generated by `aya_log_ebpf` using the [log] crate.
  72. ///
  73. /// For more details see the [module level documentation](crate).
  74. pub struct BpfLogger;
  75. impl BpfLogger {
  76. /// Starts reading log records created with `aya-log-ebpf` and logs them
  77. /// with the default logger. See [log::logger].
  78. pub fn init(bpf: &mut Bpf) -> Result<BpfLogger, Error> {
  79. BpfLogger::init_with_logger(bpf, DefaultLogger {})
  80. }
  81. /// Starts reading log records created with `aya-log-ebpf` and logs them
  82. /// with the given logger.
  83. pub fn init_with_logger<T: Log + 'static>(
  84. bpf: &mut Bpf,
  85. logger: T,
  86. ) -> Result<BpfLogger, Error> {
  87. let logger = Arc::new(logger);
  88. let mut logs: AsyncPerfEventArray<_> = bpf.map_mut("AYA_LOGS")?.try_into()?;
  89. for cpu_id in online_cpus().map_err(Error::InvalidOnlineCpu)? {
  90. let mut buf = logs.open(cpu_id, None)?;
  91. let log = logger.clone();
  92. tokio::spawn(async move {
  93. let mut buffers = (0..10)
  94. .map(|_| BytesMut::with_capacity(LOG_BUF_CAPACITY))
  95. .collect::<Vec<_>>();
  96. loop {
  97. let events = buf.read_events(&mut buffers).await.unwrap();
  98. #[allow(clippy::needless_range_loop)]
  99. for i in 0..events.read {
  100. let buf = &mut buffers[i];
  101. log_buf(buf, &*log).unwrap();
  102. }
  103. }
  104. });
  105. }
  106. Ok(BpfLogger {})
  107. }
  108. }
  109. pub trait Formatter<T> {
  110. fn format(v: T) -> String;
  111. }
  112. pub struct DefaultFormatter;
  113. impl<T> Formatter<T> for DefaultFormatter
  114. where
  115. T: ToString,
  116. {
  117. fn format(v: T) -> String {
  118. v.to_string()
  119. }
  120. }
  121. pub struct LowerHexFormatter;
  122. impl<T> Formatter<T> for LowerHexFormatter
  123. where
  124. T: LowerHex,
  125. {
  126. fn format(v: T) -> String {
  127. format!("{:x}", v)
  128. }
  129. }
  130. pub struct UpperHexFormatter;
  131. impl<T> Formatter<T> for UpperHexFormatter
  132. where
  133. T: UpperHex,
  134. {
  135. fn format(v: T) -> String {
  136. format!("{:X}", v)
  137. }
  138. }
  139. pub struct Ipv4Formatter;
  140. impl<T> Formatter<T> for Ipv4Formatter
  141. where
  142. T: Into<Ipv4Addr>,
  143. {
  144. fn format(v: T) -> String {
  145. v.into().to_string()
  146. }
  147. }
  148. pub struct Ipv6Formatter;
  149. impl<T> Formatter<T> for Ipv6Formatter
  150. where
  151. T: Into<Ipv6Addr>,
  152. {
  153. fn format(v: T) -> String {
  154. v.into().to_string()
  155. }
  156. }
  157. trait Format {
  158. fn format(&self, last_hint: Option<DisplayHint>) -> Result<String, ()>;
  159. }
  160. impl Format for u32 {
  161. fn format(&self, last_hint: Option<DisplayHint>) -> Result<String, ()> {
  162. match last_hint {
  163. Some(DisplayHint::Default) => Ok(DefaultFormatter::format(self)),
  164. Some(DisplayHint::LowerHex) => Ok(LowerHexFormatter::format(self)),
  165. Some(DisplayHint::UpperHex) => Ok(UpperHexFormatter::format(self)),
  166. Some(DisplayHint::Ipv4) => Ok(Ipv4Formatter::format(*self)),
  167. Some(DisplayHint::Ipv6) => Err(()),
  168. _ => Ok(DefaultFormatter::format(self)),
  169. }
  170. }
  171. }
  172. impl Format for [u8; 16] {
  173. fn format(&self, last_hint: Option<DisplayHint>) -> Result<String, ()> {
  174. match last_hint {
  175. Some(DisplayHint::Default) => Err(()),
  176. Some(DisplayHint::LowerHex) => Err(()),
  177. Some(DisplayHint::UpperHex) => Err(()),
  178. Some(DisplayHint::Ipv4) => Err(()),
  179. Some(DisplayHint::Ipv6) => Ok(Ipv6Formatter::format(*self)),
  180. _ => Err(()),
  181. }
  182. }
  183. }
  184. impl Format for [u16; 8] {
  185. fn format(&self, last_hint: Option<DisplayHint>) -> Result<String, ()> {
  186. match last_hint {
  187. Some(DisplayHint::Default) => Err(()),
  188. Some(DisplayHint::LowerHex) => Err(()),
  189. Some(DisplayHint::UpperHex) => Err(()),
  190. Some(DisplayHint::Ipv4) => Err(()),
  191. Some(DisplayHint::Ipv6) => Ok(Ipv6Formatter::format(*self)),
  192. _ => Err(()),
  193. }
  194. }
  195. }
  196. macro_rules! impl_format {
  197. ($type:ident) => {
  198. impl Format for $type {
  199. fn format(&self, last_hint: Option<DisplayHint>) -> Result<String, ()> {
  200. match last_hint {
  201. Some(DisplayHint::Default) => Ok(DefaultFormatter::format(self)),
  202. Some(DisplayHint::LowerHex) => Ok(LowerHexFormatter::format(self)),
  203. Some(DisplayHint::UpperHex) => Ok(UpperHexFormatter::format(self)),
  204. Some(DisplayHint::Ipv4) => Err(()),
  205. Some(DisplayHint::Ipv6) => Err(()),
  206. _ => Ok(DefaultFormatter::format(self)),
  207. }
  208. }
  209. }
  210. };
  211. }
  212. impl_format!(i8);
  213. impl_format!(i16);
  214. impl_format!(i32);
  215. impl_format!(i64);
  216. impl_format!(isize);
  217. impl_format!(u8);
  218. impl_format!(u16);
  219. impl_format!(u64);
  220. impl_format!(usize);
  221. macro_rules! impl_format_float {
  222. ($type:ident) => {
  223. impl Format for $type {
  224. fn format(&self, last_hint: Option<DisplayHint>) -> Result<String, ()> {
  225. match last_hint {
  226. Some(DisplayHint::Default) => Ok(DefaultFormatter::format(self)),
  227. Some(DisplayHint::LowerHex) => Err(()),
  228. Some(DisplayHint::UpperHex) => Err(()),
  229. Some(DisplayHint::Ipv4) => Err(()),
  230. Some(DisplayHint::Ipv6) => Err(()),
  231. _ => Ok(DefaultFormatter::format(self)),
  232. }
  233. }
  234. }
  235. };
  236. }
  237. impl_format_float!(f32);
  238. impl_format_float!(f64);
  239. #[derive(Copy, Clone, Debug)]
  240. struct DefaultLogger;
  241. impl Log for DefaultLogger {
  242. fn enabled(&self, metadata: &log::Metadata) -> bool {
  243. log::logger().enabled(metadata)
  244. }
  245. fn log(&self, record: &Record) {
  246. log::logger().log(record)
  247. }
  248. fn flush(&self) {
  249. log::logger().flush()
  250. }
  251. }
  252. #[derive(Error, Debug)]
  253. pub enum Error {
  254. #[error("error opening log event array")]
  255. MapError(#[from] MapError),
  256. #[error("error opening log buffer")]
  257. PerfBufferError(#[from] PerfBufferError),
  258. #[error("invalid /sys/devices/system/cpu/online format")]
  259. InvalidOnlineCpu(#[source] io::Error),
  260. }
  261. fn log_buf(mut buf: &[u8], logger: &dyn Log) -> Result<(), ()> {
  262. let mut target = None;
  263. let mut level = Level::Trace;
  264. let mut module = None;
  265. let mut file = None;
  266. let mut line = None;
  267. let mut num_args = None;
  268. for _ in 0..LOG_FIELDS {
  269. let (attr, rest) = unsafe { TagLenValue::<'_, RecordField>::try_read(buf)? };
  270. match attr.tag {
  271. RecordField::Target => {
  272. target = Some(std::str::from_utf8(attr.value).map_err(|_| ())?);
  273. }
  274. RecordField::Level => {
  275. level = unsafe { ptr::read_unaligned(attr.value.as_ptr() as *const _) }
  276. }
  277. RecordField::Module => {
  278. module = Some(std::str::from_utf8(attr.value).map_err(|_| ())?);
  279. }
  280. RecordField::File => {
  281. file = Some(std::str::from_utf8(attr.value).map_err(|_| ())?);
  282. }
  283. RecordField::Line => {
  284. line = Some(u32::from_ne_bytes(attr.value.try_into().map_err(|_| ())?));
  285. }
  286. RecordField::NumArgs => {
  287. num_args = Some(usize::from_ne_bytes(attr.value.try_into().map_err(|_| ())?));
  288. }
  289. }
  290. buf = rest;
  291. }
  292. let mut full_log_msg = String::new();
  293. let mut last_hint: Option<DisplayHint> = None;
  294. for _ in 0..num_args.ok_or(())? {
  295. let (attr, rest) = unsafe { TagLenValue::<'_, Argument>::try_read(buf)? };
  296. match attr.tag {
  297. Argument::DisplayHint => {
  298. last_hint = Some(unsafe { ptr::read_unaligned(attr.value.as_ptr() as *const _) });
  299. }
  300. Argument::I8 => {
  301. full_log_msg.push_str(
  302. &i8::from_ne_bytes(attr.value.try_into().map_err(|_| ())?)
  303. .format(last_hint.take())?,
  304. );
  305. }
  306. Argument::I16 => {
  307. full_log_msg.push_str(
  308. &i16::from_ne_bytes(attr.value.try_into().map_err(|_| ())?)
  309. .format(last_hint.take())?,
  310. );
  311. }
  312. Argument::I32 => {
  313. full_log_msg.push_str(
  314. &i32::from_ne_bytes(attr.value.try_into().map_err(|_| ())?)
  315. .format(last_hint.take())?,
  316. );
  317. }
  318. Argument::I64 => {
  319. full_log_msg.push_str(
  320. &i64::from_ne_bytes(attr.value.try_into().map_err(|_| ())?)
  321. .format(last_hint.take())?,
  322. );
  323. }
  324. Argument::Isize => {
  325. full_log_msg.push_str(
  326. &isize::from_ne_bytes(attr.value.try_into().map_err(|_| ())?)
  327. .format(last_hint.take())?,
  328. );
  329. }
  330. Argument::U8 => {
  331. full_log_msg.push_str(
  332. &u8::from_ne_bytes(attr.value.try_into().map_err(|_| ())?)
  333. .format(last_hint.take())?,
  334. );
  335. }
  336. Argument::U16 => {
  337. full_log_msg.push_str(
  338. &u16::from_ne_bytes(attr.value.try_into().map_err(|_| ())?)
  339. .format(last_hint.take())?,
  340. );
  341. }
  342. Argument::U32 => {
  343. full_log_msg.push_str(
  344. &u32::from_ne_bytes(attr.value.try_into().map_err(|_| ())?)
  345. .format(last_hint.take())?,
  346. );
  347. }
  348. Argument::U64 => {
  349. full_log_msg.push_str(
  350. &u64::from_ne_bytes(attr.value.try_into().map_err(|_| ())?)
  351. .format(last_hint.take())?,
  352. );
  353. }
  354. Argument::Usize => {
  355. full_log_msg.push_str(
  356. &usize::from_ne_bytes(attr.value.try_into().map_err(|_| ())?)
  357. .format(last_hint.take())?,
  358. );
  359. }
  360. Argument::F32 => {
  361. full_log_msg.push_str(
  362. &f32::from_ne_bytes(attr.value.try_into().map_err(|_| ())?)
  363. .format(last_hint.take())?,
  364. );
  365. }
  366. Argument::F64 => {
  367. full_log_msg.push_str(
  368. &f64::from_ne_bytes(attr.value.try_into().map_err(|_| ())?)
  369. .format(last_hint.take())?,
  370. );
  371. }
  372. Argument::ArrU8Len16 => {
  373. let value: [u8; 16] = attr.value.try_into().map_err(|_| ())?;
  374. full_log_msg.push_str(&value.format(last_hint.take())?);
  375. }
  376. Argument::ArrU16Len8 => {
  377. let ptr = attr.value.as_ptr().cast::<u16>();
  378. let slice = unsafe { slice::from_raw_parts(ptr, 8) };
  379. let mut value: [u16; 8] = Default::default();
  380. value.copy_from_slice(slice);
  381. full_log_msg.push_str(&value.format(last_hint.take())?);
  382. }
  383. Argument::Str => match str::from_utf8(attr.value) {
  384. Ok(v) => {
  385. full_log_msg.push_str(v);
  386. }
  387. Err(e) => error!("received invalid utf8 string: {}", e),
  388. },
  389. }
  390. buf = rest;
  391. }
  392. logger.log(
  393. &Record::builder()
  394. .args(format_args!("{}", full_log_msg))
  395. .target(target.ok_or(())?)
  396. .level(level)
  397. .module_path(module)
  398. .file(file)
  399. .line(line)
  400. .build(),
  401. );
  402. logger.flush();
  403. Ok(())
  404. }
  405. struct TagLenValue<'a, T: Pod> {
  406. tag: T,
  407. value: &'a [u8],
  408. }
  409. impl<'a, T: Pod> TagLenValue<'a, T> {
  410. unsafe fn try_read(mut buf: &'a [u8]) -> Result<(TagLenValue<'a, T>, &'a [u8]), ()> {
  411. if buf.len() < mem::size_of::<T>() + mem::size_of::<usize>() {
  412. return Err(());
  413. }
  414. let tag = ptr::read_unaligned(buf.as_ptr() as *const T);
  415. buf = &buf[mem::size_of::<T>()..];
  416. let len = usize::from_ne_bytes(buf[..mem::size_of::<usize>()].try_into().unwrap());
  417. buf = &buf[mem::size_of::<usize>()..];
  418. if buf.len() < len {
  419. return Err(());
  420. }
  421. Ok((
  422. TagLenValue {
  423. tag,
  424. value: &buf[..len],
  425. },
  426. &buf[len..],
  427. ))
  428. }
  429. }
  430. #[cfg(test)]
  431. mod test {
  432. use super::*;
  433. use aya_log_common::{write_record_header, WriteToBuf};
  434. use log::logger;
  435. use testing_logger;
  436. fn new_log(args: usize) -> Result<(usize, Vec<u8>), ()> {
  437. let mut buf = vec![0; 8192];
  438. let len = write_record_header(
  439. &mut buf,
  440. "test",
  441. aya_log_common::Level::Info,
  442. "test",
  443. "test.rs",
  444. 123,
  445. args,
  446. )?;
  447. Ok((len, buf))
  448. }
  449. #[test]
  450. fn test_str() {
  451. testing_logger::setup();
  452. let (len, mut input) = new_log(1).unwrap();
  453. "test"
  454. .write(&mut input[len..])
  455. .expect("could not write to the buffer");
  456. let logger = logger();
  457. let _ = log_buf(&input, logger);
  458. testing_logger::validate(|captured_logs| {
  459. assert_eq!(captured_logs.len(), 1);
  460. assert_eq!(captured_logs[0].body, "test");
  461. assert_eq!(captured_logs[0].level, Level::Info);
  462. });
  463. }
  464. #[test]
  465. fn test_str_with_args() {
  466. testing_logger::setup();
  467. let (mut len, mut input) = new_log(2).unwrap();
  468. len += "hello "
  469. .write(&mut input[len..])
  470. .expect("could not write to the buffer");
  471. "test".write(&mut input[len..]).unwrap();
  472. let logger = logger();
  473. let _ = log_buf(&input, logger);
  474. testing_logger::validate(|captured_logs| {
  475. assert_eq!(captured_logs.len(), 1);
  476. assert_eq!(captured_logs[0].body, "hello test");
  477. assert_eq!(captured_logs[0].level, Level::Info);
  478. });
  479. }
  480. #[test]
  481. fn test_display_hint_default() {
  482. testing_logger::setup();
  483. let (mut len, mut input) = new_log(3).unwrap();
  484. len += "default hint: ".write(&mut input[len..]).unwrap();
  485. len += DisplayHint::Default.write(&mut input[len..]).unwrap();
  486. 14.write(&mut input[len..]).unwrap();
  487. let logger = logger();
  488. let _ = log_buf(&input, logger);
  489. testing_logger::validate(|captured_logs| {
  490. assert_eq!(captured_logs.len(), 1);
  491. assert_eq!(captured_logs[0].body, "default hint: 14");
  492. assert_eq!(captured_logs[0].level, Level::Info);
  493. });
  494. }
  495. #[test]
  496. fn test_display_hint_lower_hex() {
  497. testing_logger::setup();
  498. let (mut len, mut input) = new_log(3).unwrap();
  499. len += "lower hex: ".write(&mut input[len..]).unwrap();
  500. len += DisplayHint::LowerHex.write(&mut input[len..]).unwrap();
  501. 200.write(&mut input[len..]).unwrap();
  502. let logger = logger();
  503. let _ = log_buf(&input, logger);
  504. testing_logger::validate(|captured_logs| {
  505. assert_eq!(captured_logs.len(), 1);
  506. assert_eq!(captured_logs[0].body, "lower hex: c8");
  507. assert_eq!(captured_logs[0].level, Level::Info);
  508. });
  509. }
  510. #[test]
  511. fn test_display_hint_upper_hex() {
  512. testing_logger::setup();
  513. let (mut len, mut input) = new_log(3).unwrap();
  514. len += "upper hex: ".write(&mut input[len..]).unwrap();
  515. len += DisplayHint::UpperHex.write(&mut input[len..]).unwrap();
  516. 200.write(&mut input[len..]).unwrap();
  517. let logger = logger();
  518. let _ = log_buf(&input, logger);
  519. testing_logger::validate(|captured_logs| {
  520. assert_eq!(captured_logs.len(), 1);
  521. assert_eq!(captured_logs[0].body, "upper hex: C8");
  522. assert_eq!(captured_logs[0].level, Level::Info);
  523. });
  524. }
  525. #[test]
  526. fn test_display_hint_ipv4() {
  527. testing_logger::setup();
  528. let (mut len, mut input) = new_log(3).unwrap();
  529. len += "ipv4: ".write(&mut input[len..]).unwrap();
  530. len += DisplayHint::Ipv4.write(&mut input[len..]).unwrap();
  531. // 10.0.0.1 as u32
  532. 167772161u32.write(&mut input[len..]).unwrap();
  533. let logger = logger();
  534. let _ = log_buf(&input, logger);
  535. testing_logger::validate(|captured_logs| {
  536. assert_eq!(captured_logs.len(), 1);
  537. assert_eq!(captured_logs[0].body, "ipv4: 10.0.0.1");
  538. assert_eq!(captured_logs[0].level, Level::Info);
  539. });
  540. }
  541. #[test]
  542. fn test_display_hint_ipv6_arr_u8_len_16() {
  543. testing_logger::setup();
  544. let (mut len, mut input) = new_log(3).unwrap();
  545. len += "ipv6: ".write(&mut input[len..]).unwrap();
  546. len += DisplayHint::Ipv6.write(&mut input[len..]).unwrap();
  547. // 2001:db8::1:1 as byte array
  548. let ipv6_arr: [u8; 16] = [
  549. 0x20, 0x01, 0x0d, 0xb8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
  550. 0x00, 0x01,
  551. ];
  552. ipv6_arr.write(&mut input[len..]).unwrap();
  553. let logger = logger();
  554. let _ = log_buf(&input, logger);
  555. testing_logger::validate(|captured_logs| {
  556. assert_eq!(captured_logs.len(), 1);
  557. assert_eq!(captured_logs[0].body, "ipv6: 2001:db8::1:1");
  558. assert_eq!(captured_logs[0].level, Level::Info);
  559. });
  560. }
  561. #[test]
  562. fn test_display_hint_ipv6_arr_u16_len_8() {
  563. testing_logger::setup();
  564. let (mut len, mut input) = new_log(3).unwrap();
  565. len += "ipv6: ".write(&mut input[len..]).unwrap();
  566. len += DisplayHint::Ipv6.write(&mut input[len..]).unwrap();
  567. // 2001:db8::1:1 as u16 array
  568. let ipv6_arr: [u16; 8] = [
  569. 0x2001, 0x0db8, 0x0000, 0x0000, 0x0000, 0x0000, 0x0001, 0x0001,
  570. ];
  571. ipv6_arr.write(&mut input[len..]).unwrap();
  572. let logger = logger();
  573. let _ = log_buf(&input, logger);
  574. testing_logger::validate(|captured_logs| {
  575. assert_eq!(captured_logs.len(), 1);
  576. assert_eq!(captured_logs[0].body, "ipv6: 2001:db8::1:1");
  577. assert_eq!(captured_logs[0].level, Level::Info);
  578. });
  579. }
  580. }