Loading...
Searching...
No Matches
EonLogger.h
Go to the documentation of this file.
1/*
2** This file is part of eOn.
3**
4** SPDX-License-Identifier: BSD-3-Clause
5**
6** Copyright (c) 2010--present, eOn Development Team
7** All rights reserved.
8**
9** Repo:
10** https://github.com/TheochemUI/eOn
11*/
12#pragma once
13
14#include "quill/Backend.h"
15#include "quill/Frontend.h"
16#include "quill/LogMacros.h"
17#include "quill/Logger.h"
18#include "quill/sinks/ConsoleSink.h"
19#include "quill/sinks/FileSink.h"
20#include <atomic>
21#include <chrono>
22#include <filesystem>
23#include <mutex>
24#include <source_location>
25#include <string>
26#include <string_view>
27#include <system_error>
28
29namespace eonc::log {
30
31// Logger name constants for internal use
32namespace detail {
33inline constexpr std::string_view kDefaultLoggerName{"combi"};
34inline constexpr std::string_view kTracebackLoggerName{"_traceback"};
36inline constexpr std::chrono::milliseconds kBackendSleep{1};
37} // namespace detail
38
43[[nodiscard]] inline quill::Logger *init_client() noexcept {
44 static std::once_flag once;
45 std::call_once(once, [] {
46 if (quill::Frontend::get_logger(std::string(detail::kDefaultLoggerName))) {
47 return;
48 }
49 try {
50 quill::BackendOptions backend_options;
51 // The backend thread sleeps this long when its queues are empty. At
52 // 10 us it woke about 13,000 times a second beside the force loop;
53 // at 1 ms a line reaches its sink at most 1 ms late. Order is kept
54 // either way, and Backend::stop and flush_log drain the queues.
55 backend_options.sleep_duration = detail::kBackendSleep;
56 backend_options.transit_event_buffer_initial_capacity = 2048;
57 backend_options.log_timestamp_ordering_grace_period =
58 std::chrono::microseconds{0};
59 backend_options.sink_min_flush_interval = std::chrono::milliseconds{100};
60 backend_options.check_printable_char = {};
61 try {
62 quill::Backend::start(backend_options);
63 } catch (...) {
64 }
65 auto console_sink =
66 quill::Frontend::create_or_get_sink<quill::ConsoleSink>("console");
67 auto file_sink = quill::Frontend::create_or_get_sink<quill::FileSink>(
68 "client_quill.log",
69 []() {
70 quill::FileSinkConfig cfg;
71 cfg.set_open_mode('w');
72 return cfg;
73 }(),
74 quill::FileEventNotifier{});
75 auto *logger = quill::Frontend::create_or_get_logger(
76 "combi", {std::move(console_sink), std::move(file_sink)},
77 quill::PatternFormatterOptions{"%(message)"},
78 quill::ClockSourceType::System);
79 logger->set_log_level(quill::LogLevel::TraceL3);
80 auto trace_csink =
81 quill::Frontend::create_or_get_sink<quill::ConsoleSink>(
82 "trace_console");
83 auto trace_fsink = quill::Frontend::create_or_get_sink<quill::FileSink>(
84 "client_traceback.log",
85 []() {
86 quill::FileSinkConfig cfg;
87 cfg.set_open_mode('w');
88 return cfg;
89 }(),
90 quill::FileEventNotifier{});
91 quill::Frontend::create_or_get_logger(
92 "_traceback", {std::move(trace_csink), std::move(trace_fsink)},
93 quill::PatternFormatterOptions{
94 " [%(log_level)] [%(source_location)] [%(caller_function)] \n "
95 "%(message)\n[end %(log_level)]"},
96 quill::ClockSourceType::System);
97 } catch (...) {
98 }
99 });
100 return quill::Frontend::get_logger(std::string(detail::kDefaultLoggerName));
101}
102
111[[nodiscard]] inline quill::Logger *get() noexcept {
112 static std::atomic<quill::Logger *> cached_logger{nullptr};
113 if (quill::Logger *l = cached_logger.load(std::memory_order_relaxed)) {
114 return l;
115 }
116
117 if (auto *logger = quill::Frontend::get_logger(
118 std::string(detail::kDefaultLoggerName))) {
119 cached_logger.store(logger, std::memory_order_relaxed);
120 return logger;
121 }
122
123 // Fallback for Python bindings/tests that didn't run ClientEON's main()
124 static quill::Logger *fallback = []() -> quill::Logger * {
125 try {
126 quill::Backend::start();
127 } catch (...) {
128 } // Ignore if backend already started
129
130 try {
131 auto console_sink =
132 quill::Frontend::create_or_get_sink<quill::ConsoleSink>(
133 "fallback_console");
134 return quill::Frontend::create_or_get_logger(
135 "combi", std::move(console_sink),
136 quill::PatternFormatterOptions{"%(message)"},
137 quill::ClockSourceType::System);
138 } catch (...) {
139 return nullptr;
140 }
141 }();
142 if (fallback)
143 cached_logger.store(fallback, std::memory_order_relaxed);
144 return fallback;
145}
146
155[[nodiscard]] inline quill::Logger *traceback() noexcept {
156 static std::atomic<quill::Logger *> cached{nullptr};
157 if (quill::Logger *l = cached.load(std::memory_order_relaxed)) {
158 return l;
159 }
160 if (auto *logger = quill::Frontend::get_logger(
161 std::string(detail::kTracebackLoggerName))) {
162 cached.store(logger, std::memory_order_relaxed);
163 return logger;
164 }
165 return nullptr;
166}
167
177[[nodiscard]] inline quill::Logger *
178get_file(std::string_view name, std::string_view filename,
179 std::string_view pattern = "%(message)") {
180 // If the logger already exists, return it immediately.
181 // Quill strictly checks configuration matches on recreation and throws if
182 // PatternFormatterOptions differ, which crashes instances (like
183 // Dimer/Optimizers) that are created multiple times in loops (e.g., NEB).
184 if (auto *existing = quill::Frontend::get_logger(std::string(name))) {
185 return existing;
186 }
187 static std::mutex file_logger_mutex;
188 std::lock_guard<std::mutex> lock(file_logger_mutex);
189 if (auto *existing = quill::Frontend::get_logger(std::string(name))) {
190 return existing;
191 }
192
193 try {
194 // Durable absolute path: optimizers open "_lbfgs.log" etc. under CWD.
195 // Job integration fixtures chdir into /tmp/eon_test_job_* then delete that
196 // tree when the case ends, while Quill's process-lifetime FileSink still
197 // flushes — "fopen failed after 3 attempts". Keep logs under a stable
198 // temp subdir instead of the disposable workdir.
199 namespace fs = std::filesystem;
200 fs::path path{std::string(filename)};
201 if (!path.is_absolute()) {
202 static const fs::path log_dir = [] {
203 fs::path d = fs::temp_directory_path() / "eon_logs";
204 std::error_code ec;
205 fs::create_directories(d, ec);
206 return d;
207 }();
208 path = log_dir / path.filename();
209 }
210 quill::FileSinkConfig cfg;
211 cfg.set_open_mode('w');
212 auto file_sink = quill::Frontend::create_or_get_sink<quill::FileSink>(
213 path.string(), cfg);
214 return quill::Frontend::create_or_get_logger(
215 std::string(name), std::move(file_sink),
216 quill::PatternFormatterOptions{std::string(pattern)},
217 quill::ClockSourceType::System);
218 } catch (...) {
219 return get(); // Fallback to default combi logger if creation fails
220 }
221}
222
238struct Scoped {
239 [[no_unique_address]] quill::Logger *logger{nullptr};
240
241 Scoped() noexcept : logger(get()) {}
242
243 // Implicit conversion to Logger* for seamless use with QUILL_LOG_* macros
244 operator quill::Logger *() const noexcept { return logger; }
245
246 // Support QUILL_LOG_ macro pointer dereference
247 quill::Logger *operator->() const noexcept { return logger; }
248
249 // Allow dynamic re-assignment (e.g. switching to _traceback logger)
250 Scoped &operator=(quill::Logger *l) noexcept {
251 logger = l;
252 return *this;
253 }
254
255 // Explicit access if needed
256 [[nodiscard]] quill::Logger *ptr() const noexcept { return logger; }
257};
258
275 [[no_unique_address]] quill::Logger *logger{nullptr};
276
277 FileScoped(std::string_view name, std::string_view filename,
278 std::string_view pattern = "%(message)") noexcept
279 : logger(get_file(name, filename, pattern)) {}
280
281 operator quill::Logger *() const noexcept { return logger; }
282 // Support QUILL_LOG_ macro pointer dereference
283 quill::Logger *operator->() const noexcept { return logger; }
284 FileScoped &operator=(quill::Logger *l) noexcept {
285 logger = l;
286 return *this;
287 }
288 [[nodiscard]] quill::Logger *ptr() const noexcept { return logger; }
289};
290
291} // namespace eonc::log
292
293// Force MSVC to evaluate __VA_ARGS__ properly
294#define EONC_EXPAND(x) x
295
304#define EONC_LOG_TRACE(...) \
305 do { \
306 if (auto *l = eonc::log::get()) { \
307 EONC_EXPAND(QUILL_LOG_TRACE_L1(l, __VA_ARGS__)); \
308 } \
309 } while (0)
310#define EONC_LOG_DEBUG(...) \
311 do { \
312 if (auto *l = eonc::log::get()) { \
313 EONC_EXPAND(QUILL_LOG_DEBUG(l, __VA_ARGS__)); \
314 } \
315 } while (0)
316#define EONC_LOG_INFO(...) \
317 do { \
318 if (auto *l = eonc::log::get()) { \
319 EONC_EXPAND(QUILL_LOG_INFO(l, __VA_ARGS__)); \
320 } \
321 } while (0)
322#define EONC_LOG_WARNING(...) \
323 do { \
324 if (auto *l = eonc::log::get()) { \
325 EONC_EXPAND(QUILL_LOG_WARNING(l, __VA_ARGS__)); \
326 } \
327 } while (0)
328#define EONC_LOG_ERROR(...) \
329 do { \
330 if (auto *l = eonc::log::get()) { \
331 EONC_EXPAND(QUILL_LOG_ERROR(l, __VA_ARGS__)); \
332 } \
333 } while (0)
334#define EONC_LOG_CRITICAL(...) \
335 do { \
336 if (auto *l = eonc::log::get()) { \
337 EONC_EXPAND(QUILL_LOG_CRITICAL(l, __VA_ARGS__)); \
338 } \
339 } while (0)
constexpr std::string_view kTracebackLoggerName
Definition EonLogger.h:34
constexpr std::chrono::milliseconds kBackendSleep
Idle sleep of the client's logging backend thread.
Definition EonLogger.h:36
constexpr std::string_view kDefaultLoggerName
Definition EonLogger.h:33
quill::Logger * init_client() noexcept
Start the client backend and the combi / traceback loggers once.
Definition EonLogger.h:43
quill::Logger * get() noexcept
Get or create the default "combi" logger.
Definition EonLogger.h:111
quill::Logger * traceback() noexcept
Get or create the "_traceback" logger for traceback logging.
Definition EonLogger.h:155
quill::Logger * get_file(std::string_view name, std::string_view filename, std::string_view pattern="%(message)")
Get or create a named logger with a file sink.
Definition EonLogger.h:178
quill::Logger * logger
Definition EonLogger.h:275
FileScoped(std::string_view name, std::string_view filename, std::string_view pattern="%(message)") noexcept
Definition EonLogger.h:277
quill::Logger * operator->() const noexcept
Definition EonLogger.h:283
quill::Logger * ptr() const noexcept
Definition EonLogger.h:288
FileScoped & operator=(quill::Logger *l) noexcept
Definition EonLogger.h:284
Scoped() noexcept
Definition EonLogger.h:241
quill::Logger * ptr() const noexcept
Definition EonLogger.h:256
quill::Logger * operator->() const noexcept
Definition EonLogger.h:247
quill::Logger * logger
Definition EonLogger.h:239
Scoped & operator=(quill::Logger *l) noexcept
Definition EonLogger.h:250