C++ 同时记录到控制台和日志文件

Ale*_*der 5 c++ logging stream

我有一个基类,例如“ProcessingThread”,它有几个派生类。每个派生都有一个特定的名称,例如“DerivationOne”,“DerivationTwo”,......现在对我来说似乎很有用,有一个格式化的输出到控制台,打印如下内容:

[DerivationOne]: Action X took place!
[DerivationTwo]: Action Y took place!
[DerivationTwo]: Action Z took place!
Run Code Online (Sandbox Code Playgroud)

同时,它应该将每个内容写入派生特定的日志文件。我想到了一个可以以标准方式调用的类,例如“custom_out <<“Write stuff” << std::endl;” 并使用单个流生成两个流,一个在控制台中运行并格式化,第二个是日志文件,而不在前面格式化名称 [name]。

有没有标准的方法来做到这一点?也许普通记录器已经支持这样的行为?也许我可以以某种方式从 std::stream 派生来实现这一点?最好的(或至少是好的)方法是什么?

Jiv*_*son 2

这是我在评论中讨论的想法的入门套件。您将需要决定如何处理写入磁盘文件的错误 - 返回 false、抛出异常或其他。我编辑它以返回真/假。True 表示没有错误。工作正在进行中。

#include <iostream>
#include <mutex>
#include <string>
#include <fstream>
#include <string_view>
#include <iomanip>

namespace dj {

    inline bool print(std::ostream& out) {
        return !!(out << std::endl);
    }

    template<typename T>
    bool print(std::ostream& out, T&& value)
    {
        return !!(out << std::forward<T>(value) << std::endl);
    }

    template<typename First, typename ... Rest>
    bool print(std::ostream& out, First&& first, Rest&& ... rest)
    {
        return !!(out << std::forward<First>(first)) && print(out, std::forward<Rest>(rest)...);
    }

    inline std::mutex logger_mtx;

    class log_stream {
    public:
        log_stream(std::string_view str, std::ostream& ifile)
            : name(str)
            , file(ifile)
        {
            std::string s{ "[" };
            name = s + name + "] ";
        }

        template <typename... Args>
        bool operator() (Args&&... args) {
            bool OK = print(file, std::forward<Args>(args)...);
            {
                std::lock_guard<std::mutex> lck(logger_mtx);
                print(std::cout, name, std::forward<Args>(args)...);
                if (!OK) {
                    print(std::cout, name, "-- Error writing to log file. --");
                }
            }
            return OK;
        }

    private:
        std::string name;
        std::ostream& file;
    };


}
int main()
{
    std::ofstream outfile("DerivationOne.log.txt");
    dj::log_stream log("DerivationOne", outfile);

    std::ofstream outfile2; // ERROR. File not opened
    dj::log_stream log2("DerivationTwo", outfile2);

    log("Life. See ", 42, ", meaning of.");
    bool OK = 
      log2("log", std::setw(4), 2.01, " That's all, folks. -", 30, '-');
    std::cout << (OK ? "OK" : "So not OK") << std::endl;
}
Run Code Online (Sandbox Code Playgroud)