Rust捕获全局panic并记录进程退出日志的方法

 更新时间:2024年04月24日 09:25:00   作者:会编程的大白熊  
本文提供了捕获全局panic并记录进程退出日志的方法,首先使用 panic::set_hook 注册异常处理及panic 触发异常,结合实例代码给大家介绍的非常详细,感兴趣的朋友跟随小编一起看看吧

本文提供了捕获全局panic并记录进程退出日志的方法。

1. 使用 panic::set_hook 注册异常处理

use human_panic::setup_panic;
use log::error;
use std::{boxed::Box, panic};
fn hook(panic_info: &panic::PanicInfo) {
    if cfg!(debug_assertions) {
        let err_message = format!("panic occurred {:?}", panic_info);
        error!("{}", err_message);
    } else {
        let err_message = match panic_info.payload().downcast_ref::<&str>() {
            Option::Some(&str) => {
                let err_message = format!(
                    "panic info: {:?}, occurred in {:?}",
                    str,
                    panic_info.location()
                );
                err_message
            }
            Option::None => {
                let err_message =
                    format!("panic occurred in {:?}", panic_info.location());
                err_message
            }
        };
        error!("{}", err_message);
    }
}
/// 注册异常处理函数
/// 在panic发出后,在panic运行时之前,触发钩子函数去处理这个panic信息。
/// panic信息被保存在PanicInfo结构体中。
pub fn register_panic_hook() {
    panic::set_hook(Box::new(|panic_info| {
        hook(panic_info);
    }));
    // setup_panic!();
}

2. panic 触发异常

use core_utils::panic::register_panic_hook;
use core_utils::panic::register_panic_hook;
use env_logger;
use log::LevelFilter;
use std::thread;
use std::time::Duration;
#[test]
fn test_panic_set_hook() {
    let _ = env_logger::builder()
        .is_test(true)
        .filter(None, LevelFilter::Debug)
        .try_init();
    register_panic_hook();
    thread::spawn(|| {
        panic!("child thread panic");
    });
    thread::sleep(Duration::from_millis(100));
}

日志如下

debug模式

[2024-04-20T05:32:30Z ERROR core_utils::panic] panic occurred PanicInfo { payload: Any { .. }, message: Some(child thread panic), location: Location { file: "core_utils/tests/test_panic.rs", line: 16, col: 9 }, can_unwind: true, force_no_backtrace: false }

release模式

[2024-04-20T05:41:06Z ERROR core_utils::panic] panic info: "child thread panic", occurred in Some(Location { file: "core_utils/tests/test_panic.rs", line: 17, col: 9 })

3. unwrap 触发异常

#[test]
fn test_panic_unwrap() {
    let _ = env_logger::builder()
        .is_test(true)
        .filter(None, LevelFilter::Debug)
        .try_init();
    register_panic_hook();
    thread::spawn(|| {
        let _ = "abc".parse::<i32>().unwrap();
    });
    thread::sleep(Duration::from_millis(100));
}

日志如下

debug模式

[2024-04-20T05:38:22Z ERROR core_utils::panic] panic occurred PanicInfo { payload: Any { .. }, message: Some(called `Result::unwrap()` on an `Err` value: ParseIntError { kind: InvalidDigit }), location: Location { file: "core_utils/tests/test_panic.rs", line: 33, col: 38 }, can_unwind: true, force_no_backtrace: false }

release模式

注意:unwrap触发的异常会导致 panic_info.payload().downcast_ref::<&str>()返回结果为 None

[2024-04-20T05:42:34Z ERROR core_utils::panic] panic occurred in Some(Location { file: "core_utils/tests/test_panic.rs", line: 33, col: 38 })

4. 使用 human_panic

human_panic只能在非debug模式且环境变量RUST_BACKTRACE未设置的情况下才会生效。

注册 hook

use human_panic::setup_panic;
pub fn register_panic_hook() {
    setup_panic!();
}

模拟release环境异常

use core_utils::panic::register_panic_hook;
use env_logger;
use human_panic::setup_panic;
use log::error;
use std::thread;
use std::time::Duration;
fn main() {
    env_logger::init();
    register_panic_hook();
    thread::spawn(|| {
        panic!("error");
        // let _ = "abc".parse::<i32>().unwrap();
    });
    thread::sleep(Duration::from_secs(1));
}
cargo run --bin human_panic --release

panic发生时会在在临时文件夹下面创建一个报告文件

Well, this is embarrassing.
core_utils had a problem and crashed. To help us diagnose the problem you can send us a crash report.
We have generated a report file at "/var/folders/gx/hn6l2rd56cx0lcwnkblxqvmr0000gn/T/report-93547ab5-9341-4212-a9af-6d2f17d6311d.toml". Submit an issue or email with the subject of "core_utils Crash Report" and include the report as an attachment.
We take privacy seriously, and do not perform any automated error collection. In order to improve the software, we rely on people to submit reports.
Thank you kindly!

报告内容如下

"name" = "core_utils"
"operating_system" = "Mac OS 14.1.1 [64-bit]"
"crate_version" = "0.1.0"
"explanation" = """
Panic occurred in file 'core_utils/src/bin/human_panic.rs' at line 14
"""
"cause" = "error"
"method" = "Panic"
"backtrace" = """
   0: 0x105b840a5 - core::panicking::panic_fmt::h2aac8cf45f7ae617
   1: 0x1059fd7c6 - std::sys_common::backtrace::__rust_begin_short_backtrace::h4bae865db206eae3
   2: 0x1059fe2fd - core::ops::function::FnOnce::call_once{{vtable.shim}}::ha8d441119e8b7a5a
   3: 0x105b5a819 - std::sys::pal::unix::thread::Thread::new::thread_start::h679ffa03f8a73496
   4: 0x7ff801993202 - __pthread_start"""

到此这篇关于Rust捕获全局panic并记录进程退出日志的文章就介绍到这了,更多相关rust 捕获全局panic内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • rust使用Atomic创建全局变量和使用操作方法

    rust使用Atomic创建全局变量和使用操作方法

    从 Rust1.34 版本后,就正式支持原子类型,原子指的是一系列不可被 CPU 上下文交换的机器指令,这些指令组合在一起就形成了原子操作,这篇文章主要介绍了rust使用Atomic创建全局变量和使用,需要的朋友可以参考下
    2024-05-05
  • Rust 中判断两个 HashMap 是否相等

    Rust 中判断两个 HashMap 是否相等

    在Rust标准库中,HashMap 实现了 PartialEq 和 Eq trait,但是这些trait的实现是基于严格的结构相等性,包括元素的顺序,这篇文章主要介绍了Rust 中判断两个 HashMap 是否相等,需要的朋友可以参考下
    2024-04-04
  • Rust时间库Chrono最佳使用实践

    Rust时间库Chrono最佳使用实践

    本文介绍了Rust中常用的日期时间处理库chrono,对比了标准库std::time和chrono的功能和适用场景,并详细讲解了chrono的核心数据类型、主要操作、进阶功能以及最佳实践,感兴趣的朋友跟随小编一起看看吧
    2026-01-01
  • Rust字符串深度解析String与str的问题小结

    Rust字符串深度解析String与str的问题小结

    在Rust编程语言中,字符串处理是一个核心概念,但与其他语言不同的是,Rust提供了两种主要的字符串类型:String和&str,本文介绍Rust字符串深度解析String与str的问题,感兴趣的朋友跟随小编一起看看吧
    2026-03-03
  • Rust中引用的具体使用

    Rust中引用的具体使用

    在Rust语言中,引用机制是其所有权系统的重要组成部分,ust提供了两种类型的引用,不可变引用和可变引用,本文就来详细的介绍一下这两种的用法,感兴趣的可以了解一下
    2024-03-03
  • Rust中的Copy和Clone对比分析

    Rust中的Copy和Clone对比分析

    这篇文章主要介绍了Rust中的Copy和Clone及区别对比分析,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2023-04-04
  • Rust模块关键词和哈希表详解

    Rust模块关键词和哈希表详解

    文章介绍了Rust编程语言中模块系统、路径控制、as关键字、外部包的使用以及哈希表的操作,主要涵盖了如何通过pub关键字控制模块和结构体的可见性,文章还详细讲解了哈希表的创建、访问、所有权转移、更新操作,感兴趣的朋友一起看看吧
    2026-03-03
  • Rust编译错误:link.exe 未找到解决办法

    Rust编译错误:link.exe 未找到解决办法

    这篇文章主要介绍了Rust编译错误:link.exe 未找到解决办法的相关资料,这个错误通常是由于系统中缺少必要的编译工具或配置不正确导致的,文中将解决方案介绍的非常详细,需要的朋友可以参考下
    2026-02-02
  • 详解Rust调用tree-sitter支持自定义语言解析

    详解Rust调用tree-sitter支持自定义语言解析

    使用Rust语言结合tree-sitter库解析自定义语言需要定义语法、生成C解析器,并在Rust项目中集成,具体步骤包括创建grammar.js定义语法,使用tree-sitter-cli工具生成C解析器,以及在Rust项目中编写代码调用解析器,这一过程涉及到对tree-sitter的深入理解和Rust语言的应用技巧
    2024-09-09
  • Rust中::和.的区别解析

    Rust中::和.的区别解析

    Rust中的::和.是两种常用的操作符,分别用于访问命名空间中的成员和实例的字段或方法,感兴趣的朋友跟随小编一起看看吧
    2024-11-11

最新评论