要自定义 dev_err 的输出格式,您需要重写内核中的错误日志记录功能。这需要编写一个新的内核模块并在 init_module() 函数中注册它。以下是一个简单的示例,展示了如何创建一个自定义的错误日志记录器,它将错误消息的前缀更改为 "MyApp: "。
my_error_logger.c 的新文件,并添加以下代码:#include <linux/module.h>#include <linux/kernel.h>#include <linux/init.h>#include <linux/console.h>#include <linux/ printk.h>#define MY_APP_PREFIX "MyApp: "static void my_error_log(const char *fmt, ...){ va_list args; char buf[512]; va_start(args, fmt); vsnprintf(buf, sizeof(buf), fmt, args); va_end(args); printk(MY_APP_PREFIX "%s\n", buf);}static int __init my_error_logger_init(void){ printk(KERN_INFO "MyApp error logger initialized\n"); return 0;}static void __exit my_error_logger_exit(void){ printk(KERN_INFO "MyApp error logger unloaded\n");}module_init(my_error_logger_init);module_exit(my_error_logger_exit);MODULE_LICENSE("GPL");MODULE_AUTHOR("Your Name");MODULE_DESCRIPTION("Custom error logger for MyApp");然后,使用以下命令编译内核模块:make -C /lib/modules/$(uname -r)/build M=$(pwd) modules安装编译后的模块:sudo make modules_install加载模块:sudo insmod my_error_logger.ko现在,每当内核中出现错误时,它们都将带有 "MyApp: " 前缀。请注意,这只是一个简单的示例,您可以根据需要修改 my_error_log() 函数以自定义输出格式。