我编写了以下代码,使用rsyslog on remote unix machine
将日志从my windows machine
发送到远程syslog(boost-log
)。我正在使用syslog_backend
。
#include <boost/config.hpp>
#if !defined(BOOST_WINDOWS)
#define BOOST_LOG_USE_NATIVE_SYSLOG
#endif
#include <string>
#include <iostream>
#include <boost/smart_ptr/shared_ptr.hpp>
#include <boost/log/common.hpp>
#include <boost/log/expressions.hpp>
#include <boost/log/attributes.hpp>
#include <boost/log/sinks/sync_frontend.hpp>
#include <boost/log/sinks/syslog_backend.hpp>
namespace logging = boost::log;
namespace attrs = boost::log::attributes;
namespace src = boost::log::sources;
namespace sinks = boost::log::sinks;
namespace expr = boost::log::expressions;
namespace keywords = boost::log::keywords;
using boost::shared_ptr;
using namespace std;
class AlertsForSyslog
{
string hostname;
string message;
src::severity_logger<> lg;
boost::shared_ptr< sinks::synchronous_sink< sinks::syslog_backend > > sink;
public :
AlertsForSyslog(string hostname);
int sendMessageToSyslog(string message);
void dd();
};
AlertsForSyslog::AlertsForSyslog(string hostname)
{
this->hostname = hostname;
sink = boost::shared_ptr<sinks::synchronous_sink< sinks::syslog_backend >>(new sinks::synchronous_sink< sinks::syslog_backend >());
}
int AlertsForSyslog::sendMessageToSyslog(string message)
{
this->message = message;
sink->set_formatter
(
expr::format("%1%")
%expr::smessage
);
sink->locked_backend()->set_target_address(hostname);
// Add the sink to the core
logging::core::get()->add_sink(sink);
return 0;
}
void AlertsForSyslog::dd()
{
BOOST_LOG_SEV(lg, sinks::syslog::alert) << message ;
}
int main()
{
cout << "hello";
AlertsForSyslog n1 = AlertsForSyslog("172.16.72.239");
n1.sendMessageToSyslog("from n1");
AlertsForSyslog n2 = AlertsForSyslog("172.16.72.239");
n2.sendMessageToSyslog("from n2");
AlertsForSyslog n3 = AlertsForSyslog("172.16.72.239");
n3.sendMessageToSyslog("from n3");
n1.dd();
n2.dd();
n3.dd();
return 0;
}
以上代码为我提供了我的unix计算机/var/log/messages
中的以下输出:
Apr 4 21:33:58 mypc from n1
Apr 4 21:33:58 mypc from n1
Apr 4 21:33:58 mypc from n1
Apr 4 21:33:58 mypc from n2
Apr 4 21:33:58 mypc from n2
Apr 4 21:33:58 mypc from n3
Apr 4 21:33:58 mypc from n3
Apr 4 21:33:58 mypc from n2
Apr 4 21:33:58 mypc from n3
1)为什么在所有3个接收器上发送相同的消息(“来自n1”)?
2)我的应用程序要求是:应用程序将启动多个线程,并且每个线程将创建AlertsForSyslog
对象,因此每个线程都希望独立发送日志。
3)有什么办法可以实现?就我而言,shared_ptr
到底在做什么?有人可以帮忙吗?
我想编写一个在上述情况下可以输出的代码:
Apr 4 21:33:58 mypc from n1
Apr 4 21:33:58 mypc from n2
Apr 4 21:33:58 mypc from n3
有人可以在上面的代码中建议任何更正吗? 在我的应用程序中,线程1将创建对象n1,而不是主函数,线程2将创建对象n2,依此类推...