Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Move spdlog::logger to gz-utils #134

Merged
merged 19 commits into from
Aug 20, 2024
1 change: 1 addition & 0 deletions .github/ci/packages.apt
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
libgz-cmake4-dev
libspdlog-dev
4 changes: 3 additions & 1 deletion CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,13 @@ if(NOT GZ_UTILS_VENDOR_CLI11)
gz_find_package(CLI11 REQUIRED_BY cli PKGCONFIG_IGNORE)
endif()

gz_find_package(spdlog REQUIRED_BY log)
caguero marked this conversation as resolved.
Show resolved Hide resolved

#============================================================================
# Configure the build
#============================================================================
gz_configure_build(QUIT_IF_BUILD_ERRORS
COMPONENTS cli)
COMPONENTS cli log)

#============================================================================
# Create package information
Expand Down
12 changes: 12 additions & 0 deletions examples/log/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
cmake_minimum_required(VERSION 3.5 FATAL_ERROR)
caguero marked this conversation as resolved.
Show resolved Hide resolved
project(gz-utils-logger-demo)

# Find the Gazebo Libraries used directly by the example
find_package(gz-utils3 REQUIRED COMPONENTS log)
set(GZ_UTILS_VER ${gz-utils3_VERSION_MAJOR})

add_executable(${PROJECT_NAME} main.cc)
target_link_libraries(
${PROJECT_NAME}
gz-utils${GZ_UTILS_VER}::log
)
37 changes: 37 additions & 0 deletions examples/log/main.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/*
* Copyright (C) 2024 Open Source Robotics Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/

#include <filesystem>
#include <gz/utils/log/Logger.hh>

//////////////////////////////////////////////////
int main(int argc, char** argv)
{
gz::utils::log::Logger logger("my_logger");
logger.RawLogger().set_level(spdlog::level::trace);

std::filesystem::path logDir = std::filesystem::temp_directory_path();
std::filesystem::path logFile = "my_log.txt";
std::filesystem::path logPath = logDir / logFile;

logger.SetLogDestination(logPath);
logger.RawLogger().trace("trace");
logger.RawLogger().info("info");
logger.RawLogger().warn("warn");
logger.RawLogger().error("error");
logger.RawLogger().critical("critical");
}
1 change: 1 addition & 0 deletions log/include/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
add_subdirectory(gz/utils)
caguero marked this conversation as resolved.
Show resolved Hide resolved
1 change: 1 addition & 0 deletions log/include/gz/utils/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
gz_install_all_headers(COMPONENT log)
57 changes: 57 additions & 0 deletions log/include/gz/utils/log/Logger.hh
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
/*
* Copyright (C) 2024 Open Source Robotics Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef GZ_UTILS_LOG_LOGGER_HH_
#define GZ_UTILS_LOG_LOGGER_HH_

#include <spdlog/spdlog.h>
#include <memory>
#include <string>
#include <gz/utils/ImplPtr.hh>

namespace gz::utils::log
{
/// \brief Gazebo console and file logging class.
caguero marked this conversation as resolved.
Show resolved Hide resolved
/// This will configure spdlog with a sane set of defaults for logging to the
/// console as well as a file.
class GZ_UTILS_VISIBLE Logger
caguero marked this conversation as resolved.
Show resolved Hide resolved
{
/// \brief Class constructor.
/// \param[in] _loggerName Logger name.
public: explicit Logger(const std::string &_loggerName);

/// \brief Set the log destination filename.
/// \param[in] _filename Log file name.
public: void SetLogDestination(const std::string &_filename);

/// \brief Get the log destination filename.
/// \return Log file name.
public: std::string LogDestination() const;

/// \brief Access the underlying spdlog logger.
/// \return The spdlog logger.
public: [[nodiscard]] spdlog::logger &RawLogger() const;

/// \brief Access the underlying spdlog logger, with ownership.
/// \return The spdlog logger.
public: [[nodiscard]] std::shared_ptr<spdlog::logger> RawLoggerPtr() const;

/// \brief Implementation Pointer.
GZ_UTILS_UNIQUE_IMPL_PTR(dataPtr)
};
}

#endif // GZ_UTILS_LOG_LOGGER_HH_
213 changes: 213 additions & 0 deletions log/include/gz/utils/log/SplitSink.hh
Original file line number Diff line number Diff line change
@@ -0,0 +1,213 @@
/*
* Copyright (C) 2024 Open Source Robotics Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/

#ifndef GZ_UTILS_LOG_SPLITSINK_HH_
#define GZ_UTILS_LOG_SPLITSINK_HH_

#include <memory>
#include <mutex>
#include <string>
#include <utility>
#include <vector>

#include <spdlog/details/log_msg.h>
#include <spdlog/details/null_mutex.h>
#include <spdlog/pattern_formatter.h>
#include <spdlog/sinks/base_sink.h>
#include <spdlog/sinks/ringbuffer_sink.h>
#include <spdlog/sinks/stdout_color_sinks.h>

namespace gz::utils::log
{
/// \brief Logging sink for spdlog that logs in Gazebo-conventions.
caguero marked this conversation as resolved.
Show resolved Hide resolved
///
/// This will route messages with severity (warn, err, critical) to stderr,
/// and all other levels (info, debug, trace) to stdout.
template<typename Mutex>
caguero marked this conversation as resolved.
Show resolved Hide resolved
class SplitConsoleSink : public spdlog::sinks::base_sink<Mutex>
{
/// \brief Class constructor.
public: SplitConsoleSink() = default;

/// \brief No copy constructor.
public: SplitConsoleSink(const SplitConsoleSink &) = delete;

/// \brief No asignment operator.
public: SplitConsoleSink &operator=(const SplitConsoleSink &) = delete;

/// \brief Try to log a message.
/// \param[in] _msg The message to log.
protected: void sink_it_(const spdlog::details::log_msg &_msg) override
{
if (!this->should_log(_msg.level))
return;

if (_msg.level == spdlog::level::warn ||
_msg.level == spdlog::level::err ||
_msg.level == spdlog::level::critical)
{
this->stderr.log(_msg);
}
else
this->stdout.log(_msg);
}

/// \brief Flush messages.
protected: void flush_() override
{
this->stdout.flush();
this->stderr.flush();
}

/// \brief Set the logging pattern.
/// \param[in] _pattern The logging pattern.
protected: void set_pattern_(const std::string &_pattern) override
{
this->set_formatter(
spdlog::details::make_unique<spdlog::pattern_formatter>(_pattern));
}

/// \brief Set the new formatter.
/// \param[in] _sinkFormatter The formatter.
protected: void set_formatter_(
std::unique_ptr<spdlog::formatter> _sinkFormatter) override
{
spdlog::sinks::base_sink<Mutex>::formatter_ = std::move(_sinkFormatter);
this->stdout.set_formatter(
spdlog::sinks::base_sink<Mutex>::formatter_->clone());
this->stderr.set_formatter(
spdlog::sinks::base_sink<Mutex>::formatter_->clone());
}

/// \brief Standard output.
private: spdlog::sinks::stdout_color_sink_st stdout;

/// \brief Standard error.
private: spdlog::sinks::stderr_color_sink_st stderr;
};

using SplitConsoleSinkMt = SplitConsoleSink<std::mutex>;
using SplitConsoleSinkSt = SplitConsoleSink<spdlog::details::null_mutex>;
caguero marked this conversation as resolved.
Show resolved Hide resolved

/// \brief Logging sink for spdlog that logs in Gazebo-conventions
///
/// This will route messages with severity (warn, err, critical) to stderr,
/// and all other levels (info, debug, trace) to stdout
template<typename Mutex, size_t numItems>
class SplitRingBufferSink: public spdlog::sinks::base_sink<Mutex>
caguero marked this conversation as resolved.
Show resolved Hide resolved
{
/// \brief Class constructor.
public: SplitRingBufferSink() = default;

/// \brief No copy constructor.
public: SplitRingBufferSink(const SplitRingBufferSink &) = delete;

/// \brief No asignment operator.
public: SplitRingBufferSink &operator=(const SplitRingBufferSink &) = delete;

/// \brief ToDo.
/// \param[in] _lim
/// \return
public: std::vector<spdlog::details::log_msg_buffer> last_raw_stdout(
size_t _lim = 0)
{
return this->stdout.last_raw(_lim);
}

/// \brief ToDo.
/// \param[in] _lim
/// \return
public: std::vector<spdlog::details::log_msg_buffer> last_raw_stderr(
size_t _lim = 0)
{
return this->stderr.last_raw(_lim);
}

/// \brief ToDo.
/// \param[in] _lim
/// \return
public: std::vector<std::string> last_formatted_stdout(size_t _lim = 0)
{
return this->stdout.last_formatted(_lim);
}

/// \brief ToDo.
/// \param[in] _lim
/// \return
public: std::vector<std::string> last_formatted_stderr(size_t _lim = 0)
{
return this->stderr.last_formatted(_lim);
}

/// \brief ToDo.
/// \param[in] _lim
/// \return
protected: void sink_it_(const spdlog::details::log_msg &_msg) override
{
if (!this->should_log(_msg.level))
return;

if (_msg.level == spdlog::level::warn ||
_msg.level == spdlog::level::err ||
_msg.level == spdlog::level::critical)
{
this->stderr.log(_msg);
}
else
this->stdout.log(_msg);
}

/// \brief Flush messages.
protected: void flush_() override
{
this->stdout.flush();
this->stderr.flush();
}

/// \brief Set the logging pattern.
/// \param[in] _pattern The logging pattern.
protected: void set_pattern_(const std::string &_pattern) override
{
this->set_formatter_(
spdlog::details::make_unique<spdlog::pattern_formatter>(_pattern));
}

/// \brief Set the new formatter.
/// \param[in] _sinkFormatter The formatter.
protected: void set_formatter_(
std::unique_ptr<spdlog::formatter> sinkFormatter) override
{
spdlog::sinks::base_sink<Mutex>::formatter_ = std::move(sinkFormatter);
this->stdout.set_formatter(
spdlog::sinks::base_sink<Mutex>::formatter_->clone());
this->stderr.set_formatter(
spdlog::sinks::base_sink<Mutex>::formatter_->clone());
}


/// \brief Standard output.
private: spdlog::sinks::ringbuffer_sink_st stdout {numItems};

/// \brief Standard error.
private: spdlog::sinks::ringbuffer_sink_st stderr {numItems};
};

template <size_t numItems>
using SplitRingBufferSinkMt = SplitRingBufferSink<std::mutex, numItems>;

} // namespace gz::utils::log
#endif // GZ_UTILS_LOG_SPLITSINK_HH__
15 changes: 15 additions & 0 deletions log/src/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
gz_get_libsources_and_unittests(sources gtest_sources)

gz_add_component(log
SOURCES ${sources}
INDEPENDENT_FROM_PROJECT_LIB
GET_TARGET_NAME gz_utils_log_target_name)

target_link_libraries(${gz_utils_log_target_name}
PUBLIC
spdlog::spdlog)

gz_build_tests(TYPE UNIT
SOURCES ${gtest_sources}
LIB_DEPS ${gz_utils_log_target_name}
)
Loading