简体   繁体   English

有没有办法从 Linux 下的 C++ 应用程序实时监控系统日志?

[英]Is there a way to monitor syslog in realtime from a C++ application under Linux?

I'm on an ARM Linux board that has some USB issues when a USB 1.1 device is connected or disconnected to the USB 3.0 ports, in that case a kernel message is generated, something like: I'm on an ARM Linux board that has some USB issues when a USB 1.1 device is connected or disconnected to the USB 3.0 ports, in that case a kernel message is generated, something like:

[14720.301195@0] usb 1-1.4: urb status -32 [14720.301195@0] usb 1-1.4:城市状态-32

This message literally floods the syslog repeating itself hundreds of times.这条消息从字面上淹没了系统日志,重复了数百次。 My application needs to intercept this message as soon as possible and perform some actions such as release some peripherals and re-instantiate some objects.我的应用程序需要尽快拦截此消息并执行一些操作,例如释放一些外围设备并重新实例化一些对象。 Since the error is generated only while other USB 1.1 devices are open and in use, as soon as I release them the error disappears.由于仅在其他 USB 1.1 设备打开并正在使用时才生成错误,因此一旦我释放它们,错误就会消失。 This seems the only way to prevent the message flood.这似乎是防止消息泛滥的唯一方法。

I've tried with polling on the bash command:我试过对 bash 命令进行轮询:

tail -n 1 /var/log/syslog尾 -n 1 /var/log/syslog

but apparently the log file isn't updated quickly enough, even if I mount /var/log/ in a ram disk (ramfs).但显然日志文件的更新速度不够快,即使我将 /var/log/ 挂载在 ram 磁盘 (ramfs) 中也是如此。

I don't know how else I could "connect" to the syslog and read the messages in real-time, as soon as they are generated.我不知道我还能如何“连接”到系统日志并在生成消息后实时读取消息。

Try to use the -f (follow) flag.尝试使用-f (跟随)标志。

tail -f /var/log/syslog尾 -f /var/log/syslog

Then you don't need to poll it every time.然后你不需要每次都轮询它。 The following seems to work on my Linux:以下似乎适用于我的 Linux:

#include <iostream>
#include <memory>

using namespace std;

int main()
{
    unique_ptr<FILE, decltype(&pclose)> pipe(popen("tail -f /var/log/syslog", "r"), pclose);
    if (!pipe)
        throw runtime_error("popen failed");

    array<char, 4096> buffer;
    while (fgets(buffer.data(), buffer.size(), pipe.get()))
        cout << "SYSLOG: " << buffer.data() << endl;
}

and can be debugged with:并且可以通过以下方式进行调试:

python -c 'import syslog; syslog.syslog("Hello syslog")'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM