log.cpp

  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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
#include <planet/comms/signal.hpp>
#include <planet/log.hpp>
#include <planet/queue/tspsc.hpp>
#include <planet/serialise/chrono.hpp>
#include <planet/serialise/load_buffer.hpp>
#include <planet/telemetry/counter.hpp>
#include <planet/telemetry/rate.hpp>
#include <planet/time/checkpointer.hpp>

#include <felspar/io/warden.poll.hpp>
#include <felspar/memory/hexdump.hpp>

#include <iostream>
#include <thread>


using namespace std::literals;


thread_local planet::serialise::save_buffer planet::log::detail::ab;


namespace {
    constexpr std::string_view log_root_directory = LOG_ROOT_DIRECTORY;


    auto g_start_time() {
        static auto st = std::chrono::steady_clock::now();
        return st;
    }
    [[maybe_unused]] auto const g_started = g_start_time();


    auto &printers_mutex() {
        static std::mutex m;
        return m;
    }
    auto &printers() {
        static std::map<std::string_view, planet::log::detail::formatter const *>
                m;
        return m;
    }


    void show(planet::serialise::load_buffer &, std::size_t, std::string_view);
    void
            show(planet::serialise::box &b,
                 std::size_t const depth,
                 std::string_view const separator) {
        if (auto printer = printers().find(b.name);
            printer == printers().end()) {
            std::cout << b.name << " v" << int(b.version) << " size "
                      << b.content.size() << " bytes\n";
            show(b.content, depth + 1, separator);
        } else {
            printer->second->print(std::cout, b);
        }
    }
    void
            show(planet::serialise::load_buffer &lb,
                 std::size_t const depth,
                 std::string_view const separator) {
        if (depth) { std::cout << std::string(depth, ' '); }
        while (not lb.empty()) {
            auto const mv = static_cast<std::uint8_t>(lb.cmemory()[0]);
            if (mv > 0 and mv < 80) {
                auto b = load_type<planet::serialise::box>(lb);
                show(b, depth, separator);
            } else {
                auto const m = lb.extract_marker();
                switch (m) {
                case planet::serialise::marker::empty:
                    std::cout << "empty";
                    break;

                case planet::serialise::marker::std_byte_array: {
                    auto const size = lb.extract_size_t();
                    auto s = lb.split(size);
                    felspar::memory::hexdump(std::cout, s);
                    break;
                }

                case planet::serialise::marker::u8:
                    std::cout << std::to_string(lb.extract<std::uint8_t>());
                    break;

                case planet::serialise::marker::b_true:
                    std::cout << "true";
                    break;
                case planet::serialise::marker::b_false:
                    std::cout << "false";
                    break;

                case planet::serialise::marker::i32le:
                    std::cout << std::to_string(lb.extract<std::int32_t>());
                    break;
                case planet::serialise::marker::u32le:
                    std::cout << std::to_string(lb.extract<std::uint32_t>());
                    break;
                case planet::serialise::marker::i64le:
                    std::cout << std::to_string(lb.extract<std::int64_t>());
                    break;
                case planet::serialise::marker::u64le:
                    std::cout << std::to_string(lb.extract<std::uint64_t>());
                    break;

                case planet::serialise::marker::f32le:
                    std::cout << lb.extract<float>();
                    break;
                case planet::serialise::marker::f128le:
                    std::cout << lb.extract<long double>();
                    break;

                case planet::serialise::marker::poly_list: {
                    auto const count = lb.extract_size_t();
                    std::cout << "(poly-list with " << count << " items)\n";
                    for (std::size_t index{}; index < count; ++index) {
                        show(lb, depth + 1, separator);
                    }
                    break;
                }

                case planet::serialise::marker::u8string8: {
                    auto const buffer = lb.split(lb.extract_size_t());
                    std::cout << std::string_view{
                            reinterpret_cast<char const *>(buffer.data()),
                            buffer.size()};
                    break;
                }

                default:
                    std::cerr << "unknown marker [" << to_string(m) << " - 0x"
                              << std::hex << static_cast<unsigned>(m)
                              << std::dec << ']';
                    return;
                }
            }
            if (not lb.empty()) { std::cout << separator; }
        }
    }


    void print(planet::log::message const &m) {
        std::cout << std::fixed
                  << static_cast<double>(
                             (m.logged - g_start_time()).count() / 1e9)
                  << std::defaultfloat << ' ';
        switch (m.level) {
        case planet::log::level::debug:
            std::cout << "\33[0;37mDBUG\33[0;39m ";
            break;
        case planet::log::level::info:
            std::cout << "\33[0;32mINFO\33[0;39m ";
            break;
        case planet::log::level::warning:
            std::cout << "\33[1;33mWARN\33[0;39m ";
            break;
        case planet::log::level::error:
            std::cout << "\33[0;31mERRR\33[0;39m ";
            break;
        case planet::log::level::critical:
            std::cout << "\33[0;31mCRIT\33[0;39m ";
            break;
        }
        planet::serialise::load_buffer buffer{m.payload.cmemory()};
        show(buffer, 0, " ");
        std::string_view fn{m.location.file_name()};
        if (not log_root_directory.empty()
            and fn.starts_with(log_root_directory)) {
            fn.remove_prefix(log_root_directory.size() + 1);
        }
        std::cout << " \33[0;37m" << m.location.function_name() << ' ' << fn
                  << ':' << m.location.line() << ':' << m.location.column()
                  << "\33[0;39m" << std::endl;
    }


    planet::telemetry::counter debug_count{"planet_log_message_debug"};
    planet::telemetry::counter info_count{"planet_log_message_info"};
    planet::telemetry::counter warning_count{"planet_log_message_warning"};
    planet::telemetry::counter error_count{"planet_log_message_error"};


    struct log_thread {
        felspar::io::poll_warden warden;
        planet::queue::tspsc<planet::log::message> messages;
        planet::comms::signal signal{warden};
        planet::comms::signal terminate{warden};

        log_thread() {}
        ~log_thread() {
            if (thread.joinable()) { stop_thread(); }
        }
        void stop_thread() {
            terminate.send({});
            thread.join();
        }
        std::thread thread{[this]() {
            try {
                warden.run(
                        +[](felspar::io::warden &, log_thread *ltp)
                                -> felspar::io::warden::task<void> {
                            co_await ltp->run_loops();
                        },
                        this);
            } catch (...) { std::terminate(); }
        }};
        felspar::io::warden::task<void> run_loops() {
            felspar::io::warden::starter<> tasks;
            tasks.post(*this, &log_thread::display_performance_loop);
            tasks.post(*this, &log_thread::display_log_messages_loop);
            std::array<std::byte, 1> buffer;
            co_await terminate.read_some(buffer);
        }

        void print_performance(std::scoped_lock<std::mutex> *lock = nullptr) {
            planet::telemetry::performance::current_values(
                    planet::log::detail::ab);
            auto const bytes = planet::log::detail::ab.complete();
            planet::log::logged_performance_counters lgc{.counters = bytes};
            {
                std::cout << "\33[0;32mPerformance counters "
                          << static_cast<double>(
                                     (lgc.logged - g_start_time()).count()
                                     / 1e9)
                          << "\33[0;39m\n  ";
                planet::serialise::load_buffer lb{bytes.cmemory()};
                if (lock) {
                    show(lb, 0, "\n  ");
                } else {
                    std::scoped_lock _{printers_mutex()};
                    show(lb, 0, "\n  ");
                }
                std::cout << std::endl;
            }
            {
                save(planet::log::detail::ab, lgc);
                auto const lb = planet::log::detail::ab.complete();
                for (auto *out : std::array{
                             planet::log::profile_output.load(),
                             planet::log::log_output.load()}) {
                    if (out) {
                        (*out).write(
                                reinterpret_cast<char const *>(lb.data()),
                                lb.size());
                    }
                }
            }
        }
        felspar::io::warden::task<void> display_performance_loop() {
            planet::log::info("Starting performance counter loop");
            while (true) {
                co_await warden.sleep(1s);
                print_performance();
            }
        }


        felspar::io::warden::task<void> display_log_messages_loop() {
            std::cout << std::setprecision(9);
            while (true) {
                auto block = messages.consume();
                if (block.empty()) {
                    std::array<std::byte, 16> buffer;
                    co_await signal.read_some(buffer);
                } else {
                    auto out = planet::log::log_output.load();
                    std::scoped_lock print_lock{printers_mutex()};
                    for (auto const &message : block) {
                        if (out) {
                            save(planet::log::detail::ab, message);
                            auto const bytes =
                                    planet::log::detail::ab.complete();
                            (*out).write(
                                    reinterpret_cast<char const *>(bytes.data()),
                                    bytes.size());
                        }
                        print(message);
                        switch (message.level) {
                        case planet::log::level::debug: ++debug_count; break;
                        case planet::log::level::info: ++info_count; break;
                        case planet::log::level::warning:
                            ++warning_count;
                            break;
                        case planet::log::level::error: ++error_count; break;
                        case planet::log::level::critical:

TODO We should probably print the rest of the log messages we have before we exit the game.

291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
                            std::cout
                                    << "\33[0;31mA Critical log message is forcing an unclean shutdown\33[0;39m"
                                    << std::endl;
                            print_performance(&print_lock);
                            for (auto *flushing : std::array{
                                         planet::log::profile_output.load(),
                                         planet::log::log_output.load()}) {
                                if (flushing) { flushing->flush(); }
                            }
                            std::exit(120);
                        }
                    }
                }
            }
        }
    };

    auto &g_log_thread() {
        static log_thread lt;
        return lt;
    }
}


void planet::log::stop_thread() {
    auto &thread = g_log_thread();
    thread.stop_thread();
    thread.print_performance();
}


void planet::log::detail::critical_log_encountered() {

Wait for a bit here.

The terminate that is actually meaningful is the one a few lines above which will cause the program to terminate after dealing with the log message this is called from. The one here is just to ensure that this function doesn't actually return.

331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
    std::this_thread::sleep_for(2s);
    std::exit(121);
}


namespace {
    planet::telemetry::counter message_count{"planet_log_message_count"};
    planet::telemetry::real_time_rate message_rate{
            "planet_log_message_rate", 2s};
}
void planet::log::detail::write_log(
        level const l,
        serialise::shared_bytes b,
        felspar::source_location const &loc) {
    auto &lt = g_log_thread();
    lt.messages.push({l, std::move(b), loc});
    lt.signal.send({});
    ++message_count;
    message_rate.tick();
}


void planet::log::pretty_print(
        serialise::load_buffer &lb,
        std::size_t const depth,
        std::string_view const prefix) {
    show(lb, depth, prefix);
}
void planet::log::pretty_print(
        serialise::box &b,
        std::size_t const depth,
        std::string_view const prefix) {
    if (depth) { std::cout << std::string(depth, ' '); }
    show(b, depth, prefix);
}

planet::log::detail::formatter

371
372
373
374
375
376
377
378
planet::log::detail::formatter::formatter(std::string_view const n)
: box_name{n} {
    std::scoped_lock _{printers_mutex()};
    printers()[box_name] = this;
}


planet::log::detail::formatter::~formatter() {

Because we don't control the destruction order it's possible for a formatter to be destroyed after the global in this translation unit has gone. Because these are all static functions anyway it's fine to just let this "leak".

385
386
387
    // std::scoped_lock _{printers_mutex()};
    // printers().erase(printers().find(box_name));
}

planet::log::counters

393
394
395
396
auto planet::log::counters::current() noexcept -> counters {
    return {debug_count.value(), info_count.value(), warning_count.value(),
            error_count.value()};
}

planet::log::file_header

402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
void planet::log::write_file_headers() {
    detail::ab.save_box(file_header::box, g_start_time(), log_root_directory);
    auto const bytes = detail::ab.complete();
    for (auto *out : std::array{
                 planet::log::log_output.load(),
                 planet::log::profile_output.load()}) {
        if (out) {
            (*out).write(
                    reinterpret_cast<char const *>(bytes.data()), bytes.size());
        }
    }
}
void planet::log::load_fields(serialise::box &b, file_header &f) {
    b.fields(f.base_time, f.file_prefix);
    b.check_empty_or_throw();
}

planet::log::logged_performance_counters

423
424
425
426
void planet::log::save(
        serialise::save_buffer &ab, logged_performance_counters const l) {
    ab.save_box(l.box, l.logged, l.counters);
}

planet::log::message

432
433
434
void planet::log::save(serialise::save_buffer &ab, message const m) {
    ab.save_box(m.box, m.level, m.location, m.logged, m.payload);
}