rust - 捕获全局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"""
  • 6
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要配置rust-analyzer的代码提示,你可以按照以下步骤进行操作: 1. 确保已经在你的项目中安装了rust-analyzer插件。你可以在VSCode的插件市场中搜索并安装"rust-analyzer"插件。 2. 打开VSCode的设置(可以通过菜单栏的"文件" -> "首选项" -> "设置"或者使用快捷键Ctrl + ,打开设置)。 3. 在设置页面的搜索框中输入"rust-analyzer",找到相关的设置选项。 4. 根据你的需求,配置下列常用的代码提示相关的设置: - "rust-analyzer.enable": 设置为true以启用rust-analyzer插件。 - "rust-analyzer.completion.enable": 设置为true以启用代码补全功能。 - "rust-analyzer.completion.addCallArgumentSnippets": 设置为true以自动添加函数调用时的参数提示。 - "rust-analyzer.completion.addCallParenthesis": 设置为true以自动添加函数调用时的括号。 - "rust-analyzer.completion.postfix.enable": 设置为true以启用后缀代码补全功能,例如`.if`、`.let`等。 - "rust-analyzer.hover.enable": 设置为true以启用悬停提示功能。 - "rust-analyzer.inlayHints.enable": 设置为true以启用内联提示功能。 5. 根据你的需求,可以进一步自定义配置rust-analyzer的代码提示行为。你可以在设置中找到更多相关的选项,并根据注释进行配置。 6. 保存设置,并重启VSCode使更改生效。 通过以上步骤,你可以根据自己的喜好和需求来配置rust-analyzer的代码提示功能。请注意,具体的配置选项可能会因rust-analyzer插件版本的不同而有所差异,请参考插件的官方文档或参考其它资源获取更多定制化的配置信息。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值