如何将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)即可看到修改后日志生效输出,。

相关推荐
迅易科技5 小时前
从场景验证到Agent上线:迅易 × WorkBuddy如何帮助企业建设AI能力?
人工智能·ai·腾讯云
神奇霸王龙6 小时前
GB/T 46886 闭环屠夫:5 旗舰多模态 LLM 工业质检实测
人工智能·计算机视觉·ai·开源·ai编程·本地部署
三声三视7 小时前
uni-app 鸿蒙端传参变成 [object Object]?顺着源码追到 ArkTS router 底层才搞明白
人工智能·ai·uni-app·aigc·ai编程·harmonyos
fthux7 小时前
“装闭”,让装修套路“装”不下去
人工智能·ai·开源·github·open source
doiito9 小时前
【AI 应用】从“外国人味”到地道中文:kokoroi-rs v0.1.2 架构升级深度解析
ai·rust·系统设计
GPUStack10 小时前
怎么优雅地在GPUStack上使用minerU?
ai·大模型·llm·gpu·vllm·gpu集群·gpustack
CIO_Alliance13 小时前
企业AI化转型如何用AI+iPaaS实现降本增效?
人工智能·低代码·机器学习·ai·ipaas·系统集成·企业级ai化转型
小阿鑫13 小时前
一个 AI 应用开发程序员的一天,都在屏幕前忙些什么?
ai·程序员·agent·rd270q·明基rd270q
吨吨ai14 小时前
2026年7月更新:ChatGPT、Codex、Pro、Plus 背后的 AI Determinism 问题(GPT-5.6 工程化技术分享)
人工智能·gpt·chatgpt
猿的天空15 小时前
机器人双手迎来全栈训练系统:灵初智能EgoSteer让灵巧手无所不能
网络·人工智能·计算机·ai·程序员·机器人·编程