-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
61 lines (54 loc) · 1.76 KB
/
main.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
#include <systemd/sd-journal.h>
#include <fmt/core.h>
#include <system_error>
#include <cassert>
#include <string>
#include <optional>
#include <utility>
#include <string_view>
#include <memory>
namespace {
using namespace std::literals;
struct journal_deleter {
void operator()(sd_journal* const p) const noexcept { sd_journal_close(p); }
};
auto open_journal(const int flags = SD_JOURNAL_LOCAL_ONLY) {
sd_journal* ret = nullptr;
const auto errc = sd_journal_open(&ret, flags);
if (errc < 0) {
throw std::system_error{ -errc, std::generic_category() };
}
assert(ret);
return std::unique_ptr<sd_journal, journal_deleter>{ret};
}
struct journal_field {
std::string name;
std::string value;
};
std::optional<journal_field> get_next_field(sd_journal* const journal) {
const void* data_ptr{};
size_t data_length{};
const auto status_code = sd_journal_enumerate_data(journal, &data_ptr, &data_length);
if (status_code == 0) return {};
if (status_code < 0) throw std::system_error{ -status_code, std::generic_category() };
assert(data_ptr);
assert(data_length > 0);
const char* const data_str_ptr = reinterpret_cast<const char*>(data_ptr);
const std::string_view data_sv{ data_str_ptr, data_length };
const auto eq_pos = data_sv.find('=');
assert(eq_pos != std::string_view::npos);
const auto field_name = data_sv.substr(0, eq_pos);
const auto field_value = data_sv.substr(eq_pos + 1);
return journal_field{std::string{field_name}, std::string{field_value}};
}
} // namespace <anonymous>
int main() {
const auto journal = open_journal();
SD_JOURNAL_FOREACH(journal.get()) {
std::optional<journal_field> field;
while((field = get_next_field(journal.get())).has_value()) {
fmt::print("{:10}: {}\n", field->name, field->value);
}
fmt::print("========\n");
}
}