Howto充当Syslog接收器



我想成为特定系统日志日志的接收者。因此,从一个程序中收集所有Syslog消息并将其推向用户。

有没有办法在syslog上"订阅"我的日志消息?

除了文件观看左右。

在我的情况下,它是针对rsyslog的,可以通过omuxsock模块完成。OmuxSock =="输出模块UNIX套接字"这是rsyslog的一部分。该模块将日志"写入"到UNIX套接字,该插座需要由接收程序创建。编辑:这是接收程序的示例:

#include <sys/un.h>
#include <sys/socket.h>
#include <unistd.h>
#include <iostream>
#include <sstream>
#include <vector>
using namespace std;
/*
this program acts as a receiver for rsyslog messages.
Just create a .conf file in /etc/rsyslog.d/ with the
following content:
$ModLoad omuxsock
$Template MyForwardTemplate,"%PRI%|%TIMESTAMP%|%HOSTNAME%|%syslogtag%|%msg%"
$OMUxSockSocket /tmp/mysock
*.* :omuxsock:;MyForwardTemplate
*/
vector<string> split(const string &s, char delim) {
    stringstream ss(s);
    string item;
    vector<string> tokens;
    while (getline(ss, item, delim)) {
        tokens.push_back(item);
    }
    return tokens;
}
int main(int argc, char* argv[])
{
    const char *mysocketpath = "/tmp/mysock";
    struct sockaddr_un namesock;
    char buffer[512] = { 0 };
    int fd;
    int ret;
    namesock.sun_family = AF_UNIX;
    strncpy(namesock.sun_path, (char *)mysocketpath, sizeof(namesock.sun_path));
    cerr << "creating the socket ..." << endl;
    fd = ::socket(AF_UNIX, SOCK_DGRAM, 0);
    cerr << "binding it to the socket path ..." << endl;
    ret = ::bind(fd, (struct sockaddr *) &namesock, sizeof(struct sockaddr_un));
    if(ret != 0) {
        cerr << "bind error: " << strerror(errno) << endl;
        ret = 1;
        goto exit;
    }
    do {
        memset(buffer, 0, 512);
        ret = ::read(fd, buffer, 512);
        if(ret > 0) {
            string s = buffer;
            vector<string> v = split(buffer, '|');
            if(v.size() == 5)
                cerr << v[0] << ", " << v[1] << ", " << v[2] << ", " << v[3] << ", " << v[4] << endl;
            else {
                for(string s : v) {
                    cerr << s << ", ";
                }
                cerr << endl;
            }
        }
    } while(ret > 0);
exit:
    close(fd);
    unlink(mysocketpath);
    return ret;
}

最新更新