Tomáš Pecka | a433681 | 2020-07-24 15:32:58 +0200 | [diff] [blame] | 1 | /* |
| 2 | * Copyright (C) 2016-2019 CESNET, https://photonics.cesnet.cz/ |
| 3 | * |
| 4 | * Written by Jan Kundrát <jan.kundrat@cesnet.cz> |
| 5 | * |
| 6 | */ |
| 7 | |
| 8 | #include <cstdio> |
| 9 | #include <cstdlib> |
| 10 | #include <inttypes.h> |
| 11 | #include <spdlog/sinks/systemd_sink.h> |
| 12 | #include <sys/stat.h> |
| 13 | #include <sys/types.h> |
| 14 | #include <unistd.h> |
| 15 | #include "utils/journal.h" |
| 16 | |
| 17 | namespace velia::utils { |
| 18 | |
| 19 | /** @short Is stderr connected to journald? Not thread safe. */ |
| 20 | bool isJournaldActive() |
| 21 | { |
| 22 | const auto stream = ::getenv("JOURNAL_STREAM"); |
| 23 | if (!stream) { |
| 24 | return false; |
| 25 | } |
| 26 | uintmax_t dev; |
| 27 | uintmax_t inode; |
| 28 | if (::sscanf(stream, "%" SCNuMAX ":%" SCNuMAX, &dev, &inode) != 2) { |
| 29 | return false; |
| 30 | } |
| 31 | struct stat buf; |
| 32 | if (fstat(STDERR_FILENO, &buf)) { |
| 33 | return false; |
| 34 | } |
| 35 | return static_cast<uintmax_t>(buf.st_dev) == dev && static_cast<uintmax_t>(buf.st_ino) == inode; |
| 36 | } |
| 37 | |
| 38 | namespace impl { |
| 39 | /** @short Provide better levels, see https://github.com/gabime/spdlog/pull/1292#discussion_r340777258 */ |
| 40 | template <typename Mutex> |
| 41 | class journald_sink : public spdlog::sinks::systemd_sink<Mutex> { |
| 42 | public: |
| 43 | journald_sink() |
| 44 | { |
| 45 | this->syslog_levels_ = {/* spdlog::level::trace */ LOG_DEBUG, |
| 46 | /* spdlog::level::debug */ LOG_INFO, |
| 47 | /* spdlog::level::info */ LOG_NOTICE, |
| 48 | /* spdlog::level::warn */ LOG_WARNING, |
| 49 | /* spdlog::level::err */ LOG_ERR, |
| 50 | /* spdlog::level::critical */ LOG_CRIT, |
| 51 | /* spdlog::level::off */ LOG_ALERT}; |
| 52 | } |
| 53 | }; |
| 54 | } |
| 55 | |
| 56 | std::shared_ptr<spdlog::sinks::sink> create_journald_sink() |
| 57 | { |
| 58 | return std::make_shared<impl::journald_sink<std::mutex>>(); |
| 59 | } |
| 60 | } |