在Unix上将C++ std :: clog重定向到syslog

kri*_*iss 26 c++ syslog stream clog

我在Unix上使用C++程序,将消息发送到syslog.

当前代码使用与printf类似的syslog系统调用.

现在我宁愿为此目的使用流,通常是内置的std :: clog.但是clog只是将输出重定向到stderr,而不是syslog,这对我来说没用,因为我还将stderr和stdout用于其他目的.

我在另一个答案 中看到,使用rdbuf()将它重定向到一个文件很容易,但我看不到应用该方法来调用syslog,因为openlog没有返回一个文件处理程序我可以用来绑定它的流.

有没有其他方法可以做到这一点?(看起来非常基本的unix编程)?

编辑:我正在寻找一个不使用外部库的解决方案.@Chris提出的建议可能是一个良好的开端,但仍然有点模糊,无法成为公认的答案.

编辑:使用Boost.IOStreams是好的,因为我的项目已经使用了Boost.

可以与外部库链接,但也是一个关注点,因为它是GPL代码.依赖性也是一种负担,因为它们可能与其他组件冲突,在我的Linux发行版上不可用,引入第三方错误等.如果这是唯一的解决方案,我可以考虑完全避免流......(遗憾).

eat*_*ter 34

我也需要像这样简单的东西,所以我把它放在一起:

log.h:

#include <streambuf>
#include <syslog.h>
enum LogPriority {
    kLogEmerg   = LOG_EMERG,   // system is unusable
    kLogAlert   = LOG_ALERT,   // action must be taken immediately
    kLogCrit    = LOG_CRIT,    // critical conditions
    kLogErr     = LOG_ERR,     // error conditions
    kLogWarning = LOG_WARNING, // warning conditions
    kLogNotice  = LOG_NOTICE,  // normal, but significant, condition
    kLogInfo    = LOG_INFO,    // informational message
    kLogDebug   = LOG_DEBUG    // debug-level message
};

std::ostream& operator<< (std::ostream& os, const LogPriority& log_priority);

class Log : public std::basic_streambuf<char, std::char_traits<char> > {
public:
    explicit Log(std::string ident, int facility);

protected:
    int sync();
    int overflow(int c);

private:
    friend std::ostream& operator<< (std::ostream& os, const LogPriority& log_priority);
    std::string buffer_;
    int facility_;
    int priority_;
    char ident_[50];
};
Run Code Online (Sandbox Code Playgroud)

log.cc:

#include <cstring>
#include <ostream>
#include "log.h"

Log::Log(std::string ident, int facility) {
    facility_ = facility;
    priority_ = LOG_DEBUG;
    strncpy(ident_, ident.c_str(), sizeof(ident_));
    ident_[sizeof(ident_)-1] = '\0';

    openlog(ident_, LOG_PID, facility_);
}

int Log::sync() {
    if (buffer_.length()) {
        syslog(priority_, "%s", buffer_.c_str());
        buffer_.erase();
        priority_ = LOG_DEBUG; // default to debug for each message
    }
    return 0;
}

int Log::overflow(int c) {
    if (c != EOF) {
        buffer_ += static_cast<char>(c);
    } else {
        sync();
    }
    return c;
}

std::ostream& operator<< (std::ostream& os, const LogPriority& log_priority) {
    static_cast<Log *>(os.rdbuf())->priority_ = (int)log_priority;
    return os;
}
Run Code Online (Sandbox Code Playgroud)

main()我初始化clog:

std::clog.rdbuf(new Log("foo", LOG_LOCAL0));
Run Code Online (Sandbox Code Playgroud)

然后每当我想记录时,它很容易:

std::clog << kLogNotice << "test log message" << std::endl;

std::clog << "the default is debug level" << std::endl;
Run Code Online (Sandbox Code Playgroud)


Chr*_*s K 13

您可以定义一个调用syslog的streambuf.例如:

// Pseudo-code
class syslog_streambuf : public streambuf { 
private: 
    void internal_log(string& log) { 
        syslog(..., log, ...); 
    }
public: 
    int sputc ( char c ) { 
        internal_log(...); 
    }
    streamsize sputn ( const char * s, streamsize n ) { 
        internal_log(...); 
    } 
}
Run Code Online (Sandbox Code Playgroud)

然后你只需编写以下内容来重定向clog:

clog.rdbuf( new syslog_streambuf ); 
Run Code Online (Sandbox Code Playgroud)

您可能需要覆盖更多功能,这里是对streambuf api的一个很好的参考.


Inn*_*der 5

另一个版本的部分灵感来自于食客.它本身不重定向std :: clog,但使用熟悉的流语法.

#ifndef SYSLOG_HPP
#define SYSLOG_HPP

#include <ostream>
#include <streambuf>
#include <string>

#include <syslog.h>

namespace log
{

enum level
{
    emergency = LOG_EMERG,
    alert     = LOG_ALERT,
    critical  = LOG_CRIT,
    error     = LOG_ERR,
    warning   = LOG_WARNING,
    notice    = LOG_NOTICE,
    info      = LOG_INFO,
    debug     = LOG_DEBUG,
};

enum type
{
    auth   = LOG_AUTH,
    cron   = LOG_CRON,
    daemon = LOG_DAEMON,
    local0 = LOG_LOCAL0,
    local1 = LOG_LOCAL1,
    local2 = LOG_LOCAL2,
    local3 = LOG_LOCAL3,
    local4 = LOG_LOCAL4,
    local5 = LOG_LOCAL5,
    local6 = LOG_LOCAL6,
    local7 = LOG_LOCAL7,
    print  = LOG_LPR,
    mail   = LOG_MAIL,
    news   = LOG_NEWS,
    user   = LOG_USER,
    uucp   = LOG_UUCP,
};

}

class syslog_stream;

class syslog_streambuf: public std::basic_streambuf<char>
{
public:
    explicit syslog_streambuf(const std::string& name, log::type type):
        std::basic_streambuf<char>()
    {
        openlog(name.size() ? name.data() : nullptr, LOG_PID, type);
    }
    ~syslog_streambuf() override { closelog(); }

protected:
    int_type overflow(int_type c = traits_type::eof()) override
    {
        if(traits_type::eq_int_type(c, traits_type::eof()))
            sync();
        else buffer += traits_type::to_char_type(c);

        return c;
    }

    int sync() override
    {
        if(buffer.size())
        {
            syslog(level, "%s", buffer.data());

            buffer.clear();
            level = ini_level;
        }
        return 0;
    }

    friend class syslog_stream;
    void set_level(log::level new_level) noexcept { level = new_level; }

private:
    static constexpr log::level ini_level = log::info;
    log::level level = ini_level;

    std::string buffer;
};

class syslog_stream: public std::basic_ostream<char>
{
public:
    explicit syslog_stream(const std::string& name = std::string(), log::type type = log::user):
        std::basic_ostream<char>(&streambuf),
        streambuf(name, type)
    { }

    syslog_stream& operator<<(log::level level) noexcept
    {
        streambuf.set_level(level);
        return (*this);
    }

private:
    syslog_streambuf streambuf;
};

#endif // SYSLOG_HPP
Run Code Online (Sandbox Code Playgroud)

要使用它,您可以执行以下操作:

syslog_stream clog;

clog << "Hello, world!" << std::endl;
clog << log::emergency << "foo" << "bar" << "baz" << 42 << std::endl;
Run Code Online (Sandbox Code Playgroud)