aboutsummaryrefslogtreecommitdiffstats
path: root/yage/core/logsink.cpp
blob: 6680c7731795d06b2cbcfabdb5e5a2eaf3048d20 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
/** ---------------------------------------------------------------------------
 * @file: logsink.cpp
 *
 * Copyright (c) 2017 Yann Herklotz Grave <ymherklotz@gmail.com>
 * MIT License, see LICENSE file for more details.
 * ----------------------------------------------------------------------------
 */

#include "logsink.h"

#include <chrono>
#include <ctime>
#include <fstream>
#include <iomanip>
#include <iostream>

namespace yage
{

LogSink::LogSink(const LogSink &sink) : wrapper_(sink.wrapper_->clone()) {}

LogSink::LogSink(LogSink &&sink) : wrapper_(std::move(sink.wrapper_)) {}

LogSink &LogSink::operator=(const LogSink &sink)
{
    wrapper_.reset(sink.wrapper_->clone());
    return *this;
}

LogSink &LogSink::operator=(LogSink &&sink)
{
    wrapper_ = std::move(sink.wrapper_);
    return *this;
}

bool LogSink::operator==(const LogSink &sink)
{
    return (wrapper_.get() == sink.wrapper_.get());
}

void LogSink::write(const LogMessage::Meta &meta, const std::string &msg) const
{
    wrapper_->write(meta, msg);
}

LogSink makeConsoleSink()
{
    return [](const LogMessage::Meta &meta, const std::string &msg) {
        std::cout << msg << "\n";
    };
}

namespace
{

class FileSink
{
public:
    FileSink(std::string &&filename)
        : fileHandle_(std::make_shared<std::ofstream>(filename))
    {
        if (!fileHandle_->good()) {
            throw std::runtime_error("Could not open file: " + filename);
        }
    }

    FileSink(const std::string filename)
        : fileHandle_(std::make_shared<std::ofstream>(filename))
    {
        if (!fileHandle_->good()) {
            throw std::runtime_error("Could not open file: " + filename);
        }
    }

    ~FileSink() = default;

    void operator()(const LogMessage::Meta &meta, const std::string &msg) const
    {
        using namespace std::chrono;

        auto now        = system_clock::now();
        auto time_t     = system_clock::to_time_t(now);
        auto local_time = std::localtime(&time_t);

        (*fileHandle_) << std::put_time(local_time, "[%H:%M:%S] ") << msg
                       << " (" << meta.fileName << ":" << meta.lineNo << ")\n";
    }

private:
    std::shared_ptr<std::ofstream> fileHandle_;
};

} // namespace

LogSink makeFileSink(const std::string &filename)
{
    return FileSink(filename);
}

LogSink makeFileSink(std::string &&filename)
{
    return FileSink(filename);
}

} // namespace yage