openthread_fuchsia/
logging.rs

1// Copyright 2021 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5use openthread::prelude::*;
6use std::ffi::CStr;
7
8pub const fn tracing_level_from(log_level: ot::LogLevel) -> log::Level {
9    match log_level {
10        ot::LogLevel::None => log::Level::Error,
11        ot::LogLevel::Crit => log::Level::Error,
12        ot::LogLevel::Warn => log::Level::Warn,
13        ot::LogLevel::Note => log::Level::Info,
14        ot::LogLevel::Info => log::Level::Info,
15        ot::LogLevel::Debg => log::Level::Debug,
16    }
17}
18
19pub const fn ot_log_level_from(log_level: log::Level) -> ot::LogLevel {
20    match log_level {
21        log::Level::Error => ot::LogLevel::Crit,
22        log::Level::Warn => ot::LogLevel::Warn,
23        log::Level::Info => ot::LogLevel::Info,
24        log::Level::Debug => ot::LogLevel::Debg,
25        log::Level::Trace => ot::LogLevel::Debg,
26    }
27}
28
29#[no_mangle]
30unsafe extern "C" fn otPlatLogLine(
31    log_level: otsys::otLogLevel,
32    _: otsys::otLogRegion, // otLogRegion is deprecated.
33    line: *const ::std::os::raw::c_char,
34) {
35    let line = CStr::from_ptr(line);
36    let tracing_level = tracing_level_from(log_level.into());
37
38    match line.to_str() {
39        // Log line isn't valid UTF-8, display it directly.
40        Ok(line) => match tracing_level {
41            log::Level::Error => log::error!(tag = "ot"; "{line}"),
42            log::Level::Warn => log::warn!(tag = "ot"; "{line}"),
43            log::Level::Info => log::info!(tag = "ot"; "{line}"),
44            log::Level::Debug => log::debug!(tag = "ot"; "{line}"),
45            log::Level::Trace => log::trace!(tag = "ot"; "{line}"),
46        },
47
48        // Log line isn't valid UTF-8, try rendering with escaping.
49        Err(_) => match tracing_level {
50            log::Level::Error => log::error!(tag = "ot"; "{line:?}"),
51            log::Level::Warn => log::warn!(tag = "ot"; "{line:?}"),
52            log::Level::Info => log::info!(tag = "ot"; "{line:?}"),
53            log::Level::Debug => log::debug!(tag = "ot"; "{line:?}"),
54            log::Level::Trace => log::trace!(tag = "ot"; "{line:?}"),
55        },
56    }
57}
58
59#[no_mangle]
60unsafe extern "C" fn otPlatLogHandleLevelChanged(log_level: otsys::otLogLevel) {
61    let tracing_level = tracing_level_from(log_level.into());
62
63    log::info!(
64        tag = "openthread_fuchsia";
65        "otPlatLogHandleLevelChanged: {log_level} (Tracing: {tracing_level})"
66    );
67}