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

相关推荐
垚森3 小时前
AI时代,让曾经的遗憾变成现实
ai
leonshi4 小时前
使用embedchain快速建立rag知识库,本地大模型
ai·rag·ollama
doiito12 小时前
【Agent Harness】Gliding Horse 上下文感知与智能压缩:让 Agent 的“注意力”永不偏移
ai·rust·架构设计·系统设计·ai agent
Augustzero1 天前
Codex Desktop 新建会话无法发送消息:一次由旧版 CLI 路径引发的故障排查
chatgpt·agent
doiito2 天前
【Agent Harness】Gliding Horse L2 作战地图深度优化:给多 Agent 上下文装上“精准导航”
ai·rust·架构设计·系统设计·ai agent
妙妙屋(zy)2 天前
Claude Code+CC-Switch+CC-Connect+飞书使用教程
ai
小七-七牛开发者2 天前
Coding Agent 规则管理:CLAUDE.md、Skills、Hooks、Subagents 到底怎么选?
ai·大模型·agent·claude·token·loop·mcp·claudecode·ai coding
xn71332 天前
ChatGPT 生图如何自动导入 Astro 内容站:base64 桥接、frontmatter 更新和封面校验
chatgpt
doiito3 天前
左脚踩右脚:让 LLM 自进化的 Agent 轨迹训练法——为什么它能补上主流范式的最后一块拼图
ai·系统设计
带刺的坐椅3 天前
从 Claude Code 隐私争议,看 SolonCode 的设计选择
ai·llm·agent·claudecode·soloncode·codingplan