如何将rust日志输出到android终端

本博客所有文章除特别声明外,均采用CC BY-NC-SA 4.0许可协议。转载请注明来自 唯你

背景

在 Rust 中,使用 println!打印日志时,输出实际上是发送到标准输出(stdout),而 Android Logcat 专门用于处理和显示应用程序的日志信息,此环境下标准输出实现被重新定义。这意味着 Rust 日志输出不会出现在 Logcat 中。

android_logger直接与 Android 的日志系统集成,确保日志信息可以按预期出现在 Logcat 中。

配置

android_logger 使用如下

注意这里使用的是 android_logger0.11.0 版本,若使用最新版本可能需要做相关 api 调整。

cargo.toml 中增加如下依赖

toml 复制代码
[dependencies]
log = "0.4"

[target.'cfg(target_os = "android")'.dependencies]
android_logger = "0.11.0"

同时引入 log 的原因:

  • log 是一个日志记录的抽象库,提供了一套统一的接口,用于记录日志消息(如 info!、warn!、error! 等)。而 android_logger 是 log 针对 android 平台的一种具体实现。
  • 虽然 android_logger 本身依赖 log,你或许以为不必再额外引用 log,但实际上 android_logger 中类似 log::LevelFilter 和 log::Level::Debug 依然依赖 log 库。

初始化

rust 复制代码
#[cfg(target_os = "android")]
fn init_logging() {
    android_logger::init_once(
        android_logger::Config::default()
            .with_min_level(log::Level::Debug)
            .with_tag("flutter"),
    );
}

注意此处 with_min_level 级别,若为 debug 则打印时最使用必须是 debug 及以上,用 info 基本是无法打印显示在 logcat 中的

使用

rust 文件使用如下

rust 复制代码
extern crate android_logger;

添加打印

rust 复制代码
impl PlatformTextureWithProvider for BoxedPixelData {
    fn create_texture(
        engine_handle: i64,
        payload_provider: Arc<dyn PayloadProvider<Self>>,
    ) -> Result<PlatformTexture<BoxedPixelData>> {
        //使用示例
        log::debug!("2222222223 create_texture");
        log::debug!("this is a debug {}", "raynor");

        PlatformTexture::new(engine_handle, Some(payload_provider))
    }
}

连接 android 设备执行 flutter run 后,logcat 日志输出如下:

复制代码
√ Built build\app\outputs\flutter-apk\app-debug.apk
Installing build\app\outputs\flutter-apk\app-debug.apk...           6.3s
W/FlutterAnimationAdvance( 3237): FlutterAnimationAdvance getInstance()
D/flutter ( 3237): irondash_texture::platform::platform_impl: 2222222223 create_texture
D/flutter ( 3237): irondash_texture::platform::platform_impl: this is a debug raynor

注意

因为每次运行都会重新编译库文件,没必要在 rust 中每次修改日志后执行 cargo clean。 直接运行对于平台支持命令(如 flutter 的话 flutter run)即可看到修改后日志生效输出,。

相关推荐
OEC小胖胖9 天前
DeepSeek导出文档
人工智能·效率工具·知识管理·ai工作流·deepseek
苡~1 个月前
【claude skill系列 - 01】Claude Skill 系列专栏 - 大纲
效率工具·ai 编程·claude code·claude api·weelinking
antzou1 个月前
Word批量转PDF
办公软件·效率工具·word转pdf
JcJc错别字在线检查1 个月前
JCJC:一款 API-First 的硬核剪贴板管理工具
效率工具·剪贴板工具
antzou1 个月前
Eclipse RCP企业级应用实践——POST API
eclipse·效率工具·开发者工具·post api
realhuizhu2 个月前
拒绝“拼凑”:用AI指令做学术文献海的“淘金客”
生成式ai·ai写作·效率工具·文献综述·学术研究
antzou3 个月前
嵌入式数据库管理
数据库·办公软件·h2·效率工具
antzou3 个月前
Excel文件拆分
办公软件·效率工具·excel拆分
antzou3 个月前
Excel文件合并
办公软件·效率工具·excel合并
antzou3 个月前
文本转Excel
办公软件·效率工具·txt转excel·scv转excel