ORE Studio 0.0.4
Loading...
Searching...
No Matches
scoped_attribute.hpp
1/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
2 *
3 * Copyright (C) 2025 Marco Craveiro <marco.craveiro@gmail.com>
4 *
5 * This program is free software; you can redistribute it and/or modify it under
6 * the terms of the GNU General Public License as published by the Free Software
7 * Foundation; either version 3 of the License, or (at your option) any later
8 * version.
9 *
10 * This program is distributed in the hope that it will be useful, but WITHOUT
11 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
12 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
13 * details.
14 *
15 * You should have received a copy of the GNU General Public License along with
16 * this program; if not, write to the Free Software Foundation, Inc., 51
17 * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 *
19 */
20#ifndef ORES_LOGGING_SCOPED_ATTRIBUTE_HPP
21#define ORES_LOGGING_SCOPED_ATTRIBUTE_HPP
22
23#include <string>
24#include <optional>
25#include <boost/log/core.hpp>
26#include <boost/log/attributes/constant.hpp>
27#include <boost/log/attributes/attribute_set.hpp>
28
29namespace ores::logging {
30
58public:
59 using iterator = boost::log::attribute_set::iterator;
60
69 explicit scoped_attribute(const std::string& attribute_name) {
70 auto result = boost::log::core::get()->add_thread_attribute(
71 attribute_name,
72 boost::log::attributes::constant<bool>(true));
73 if (result.second) {
74 iterator_ = result.first;
75 }
76 }
77
79 if (iterator_.has_value()) {
80 boost::log::core::get()->remove_thread_attribute(*iterator_);
81 }
82 }
83
84 // Non-copyable
85 scoped_attribute(const scoped_attribute&) = delete;
86 scoped_attribute& operator=(const scoped_attribute&) = delete;
87
88 // Movable
89 scoped_attribute(scoped_attribute&& other) noexcept
90 : iterator_(std::move(other.iterator_)) {
91 other.iterator_.reset();
92 }
93
94 scoped_attribute& operator=(scoped_attribute&& other) noexcept {
95 if (this != &other) {
96 if (iterator_.has_value()) {
97 boost::log::core::get()->remove_thread_attribute(*iterator_);
98 }
99 iterator_ = std::move(other.iterator_);
100 other.iterator_.reset();
101 }
102 return *this;
103 }
104
105private:
106 std::optional<iterator> iterator_;
107};
108
109}
110
111#endif
Implements logging infrastructure for ORE Studio.
Definition boost_severity.hpp:28
RAII guard that adds a thread-local attribute to Boost.Log for the duration of its scope.
Definition scoped_attribute.hpp:57
scoped_attribute(const std::string &attribute_name)
Constructs a scoped attribute guard.
Definition scoped_attribute.hpp:69