我想成为特定系统日志的接收者。因此,从一个程序收集所有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;
}
关于linux - 如何充当系统日志接收器?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49631629/