Skip to content

Commit

Permalink
Tweaks
Browse files Browse the repository at this point in the history
Signed-off-by: Carlos Agüero <[email protected]>
  • Loading branch information
caguero committed Jul 5, 2024
1 parent 55fa79d commit d24b2cb
Show file tree
Hide file tree
Showing 3 changed files with 71 additions and 53 deletions.
49 changes: 30 additions & 19 deletions include/gz/common/ConsoleNew.hh
Original file line number Diff line number Diff line change
Expand Up @@ -17,23 +17,23 @@
#ifndef GZ_COMMON_CONSOLENEW_HH_
#define GZ_COMMON_CONSOLENEW_HH_

#include <iostream>
#include <fstream>
#include <iostream>
#include <memory>
#include <sstream>
#include <string>

#include <gz/common/Export.hh>
#include "gz/common/Filesystem.hh"
#include <gz/common/Util.hh>
#include <gz/utils/ImplPtr.hh>
#include "gz/common/Filesystem.hh"

#include <spdlog/logger.h>
#include <spdlog/spdlog.h>

namespace gz::common
{

/// \brief Gazebo Console and File logging class.
/// \brief Gazebo console and file logging class.
/// This will configure spdlog with a sane set of defaults for logging to the
/// console as well as a file.
class GZ_COMMON_VISIBLE ConsoleNew
Expand All @@ -46,17 +46,21 @@ namespace gz::common
///\param[in] _mode Color mode.
public: void SetColorMode(spdlog::color_mode _mode);

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

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

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

/// \brief Access the global gz console logger
public: static ConsoleNew& Root();
/// \brief Access the global gz console logger.
/// \return The gz consoler logger.
public: static ConsoleNew &Root();

/// \brief Implementation Pointer.
GZ_UTILS_UNIQUE_IMPL_PTR(dataPtr)
Expand Down Expand Up @@ -106,27 +110,34 @@ namespace gz::common
#define gztrace gz::common::LogMessage( \
__FILE__, __LINE__, spdlog::level::trace).stream()

void gzLogInit(const std::string &directory, const std::string &filename)
/// \brief Initialize the Gazebo log.
/// \param[in] _directory Directory to log.
/// \param[in] _filename Filename to log.
void gzLogInit(const std::string &_directory, const std::string &_filename)
{
auto &root = gz::common::ConsoleNew::Root();

std::string logPath;
if (!directory.empty())
if (!_directory.empty())
{
logPath = _directory;
} else if (!gz::common::env(GZ_HOMEDIR, logPath))
{
logPath = directory;
} else if(!gz::common::env(GZ_HOMEDIR, logPath)) {
root.Logger().error("Missing HOME environment variable. No log file will be generated.");
root.Logger().error(
"Missing HOME environment variable. No log file will be generated.");
return;
}

if(!gz::common::createDirectories(logPath))
if (!gz::common::createDirectories(logPath))
{
root.Logger().error("Failed to create output log directory {}", logPath.c_str());
root.Logger().error("Failed to create output log directory {}",
logPath.c_str());
return;
}

logPath = gz::common::joinPaths(logPath, filename);
root.Logger().info("Setting log file output destination to {}", logPath.c_str());
logPath = gz::common::joinPaths(logPath, _filename);
root.Logger().info("Setting log file output destination to {}",
logPath.c_str());
gz::common::ConsoleNew::Root().SetLogDestination(logPath);
spdlog::set_default_logger(root.LoggerPtr());
}
Expand Down
64 changes: 32 additions & 32 deletions src/ConsoleNew.cc
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright (C) 2016 Open Source Robotics Foundation
* 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.
Expand All @@ -18,19 +18,18 @@
#include <sstream>
#include <string>

#include <gz/common/ConsoleNew.hh>
#include <gz/common/config.hh>
#include <gz/common/ConsoleNew.hh>
#include <gz/common/Util.hh>
#include <gz/utils/NeverDestroyed.hh>

#include <spdlog/spdlog.h>
#include <spdlog/sinks/stdout_color_sinks.h>
#include <spdlog/sinks/basic_file_sink.h>
#include <spdlog/sinks/dist_sink.h>
#include <spdlog/sinks/stdout_color_sinks.h>
#include <spdlog/spdlog.h>

namespace {
/// \brief Custom log sink that routes to stdout/stderr in Gazebo conventions
/// \brief Custom log sink that routes to stdout/stderr in Gazebo conventions.
class GzSplitSink : public spdlog::sinks::sink
{
/// \brief Class destructor.
Expand All @@ -44,42 +43,42 @@ class GzSplitSink : public spdlog::sinks::sink
_msg.level == spdlog::level::err ||
_msg.level == spdlog::level::critical)
{
stderr.log(_msg);
this->stderr.log(_msg);
}
else
stdout.log(_msg);
this->stdout.log(_msg);
}

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

/// \brief Set the logging pattern.
/// \param[in] _pattern The logging pattern.
public: void set_pattern(const std::string &_pattern) override
{
stdout.set_pattern(_pattern);
stderr.set_pattern(_pattern);
this->stdout.set_pattern(_pattern);
this->stderr.set_pattern(_pattern);
}

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

/// \brief Set the color mode.
/// \param[in] _mode Color mode.
public: void set_color_mode(spdlog::color_mode _mode)
{
stdout.set_color_mode(_mode);
stderr.set_color_mode(_mode);
this->stdout.set_color_mode(_mode);
this->stderr.set_color_mode(_mode);
}

/// \brief Standard output.
Expand All @@ -102,23 +101,25 @@ LogMessage::LogMessage(const char* _file, int _line,
/////////////////////////////////////////////////
LogMessage::~LogMessage()
{
gz::common::ConsoleNew::Root().Logger().log(sourceLocation, severity, ss.str());
gz::common::ConsoleNew::Root().Logger().log(
this->sourceLocation, this->severity, this->ss.str());
}

/////////////////////////////////////////////////
std::ostream& LogMessage::stream()
std::ostream &LogMessage::stream()
{
return ss;
return this->ss;
}

/// \brief Private data for the ConsoleNew class.
class ConsoleNew::Implementation
{
public:
explicit Implementation(const std::string &_loggerName):
consoleSink(std::make_shared<GzSplitSink>()),
sinks(std::make_shared<spdlog::sinks::dist_sink_mt>()),
logger(std::make_shared<spdlog::logger>(_loggerName, sinks))
/// \brief Constructor.
/// \param[in] _loggerName Logger name.
public: explicit Implementation(const std::string &_loggerName)
: consoleSink(std::make_shared<GzSplitSink>()),
sinks(std::make_shared<spdlog::sinks::dist_sink_mt>()),
logger(std::make_shared<spdlog::logger>(_loggerName, sinks))
{
}

Expand All @@ -136,13 +137,13 @@ class ConsoleNew::Implementation
};

/////////////////////////////////////////////////
ConsoleNew::ConsoleNew(const std::string &_loggerName):
dataPtr(gz::utils::MakeUniqueImpl<Implementation>(_loggerName))
ConsoleNew::ConsoleNew(const std::string &_loggerName)
: dataPtr(gz::utils::MakeUniqueImpl<Implementation>(_loggerName))
{
// Add the console sink as a destination
// Add the console sink as a destination.
this->dataPtr->sinks->add_sink(this->dataPtr->consoleSink);

// Configure the logger
// Configure the logger.
this->dataPtr->logger->set_level(spdlog::level::info);
this->dataPtr->logger->flush_on(spdlog::level::err);

Expand All @@ -159,17 +160,16 @@ void ConsoleNew::SetColorMode(spdlog::color_mode _mode)
/////////////////////////////////////////////////
void ConsoleNew::SetLogDestination(const std::string &_filename)
{
if (this->dataPtr->fileSink != nullptr)
{
if (this->dataPtr->fileSink)
this->dataPtr->sinks->remove_sink(this->dataPtr->fileSink);
}

this->dataPtr->fileSink =
std::make_shared<spdlog::sinks::basic_file_sink_mt>(_filename, true);
this->dataPtr->sinks->add_sink(this->dataPtr->fileSink);
}

/////////////////////////////////////////////////
spdlog::logger& ConsoleNew::Logger() const
spdlog::logger &ConsoleNew::Logger() const
{
return *this->dataPtr->logger;
}
Expand All @@ -181,7 +181,7 @@ std::shared_ptr<spdlog::logger> ConsoleNew::LoggerPtr() const
}

/////////////////////////////////////////////////
ConsoleNew& ConsoleNew::Root()
ConsoleNew &ConsoleNew::Root()
{
static gz::utils::NeverDestroyed<ConsoleNew> root{"gz"};
return root.Access();
Expand Down
11 changes: 9 additions & 2 deletions src/ConsoleNew_TEST.cc
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@

#include <spdlog/spdlog.h>

class ConsoleNew_TEST : public ::testing::Test {
class ConsoleNew_TEST : public ::testing::Test
{
protected: void SetUp() override
{
this->temp = std::make_unique<gz::common::TempDirectory>(
Expand All @@ -38,10 +39,11 @@ class ConsoleNew_TEST : public ::testing::Test {
EXPECT_TRUE(gz::common::unsetenv(GZ_HOMEDIR));
}

/// \brief Temporary directory to run test in
/// \brief Temporary directory to run test in.
private: std::unique_ptr<gz::common::TempDirectory> temp;
};

/////////////////////////////////////////////////
TEST_F(ConsoleNew_TEST, NonRootLogger)
{
gz::common::ConsoleNew test_console("test");
Expand All @@ -54,6 +56,7 @@ TEST_F(ConsoleNew_TEST, NonRootLogger)
test_logger.log(spdlog::level::critical, "This is a critical error message");
}

/////////////////////////////////////////////////
TEST_F(ConsoleNew_TEST, RootLogger)
{
auto gz_logger = gz::common::ConsoleNew::Root().Logger();
Expand All @@ -65,6 +68,7 @@ TEST_F(ConsoleNew_TEST, RootLogger)
gz_logger.log(spdlog::level::critical, "This is a critical error message");
}

/////////////////////////////////////////////////
TEST_F(ConsoleNew_TEST, RootLoggerColor)
{
gz::common::ConsoleNew::Root().SetColorMode(spdlog::color_mode::always);
Expand All @@ -76,6 +80,7 @@ TEST_F(ConsoleNew_TEST, RootLoggerColor)
spdlog::get("gz")->log(spdlog::level::critical, "This is a critical error message");
}

/////////////////////////////////////////////////
TEST_F(ConsoleNew_TEST, RootLoggerNoColor)
{
gz::common::ConsoleNew::Root().SetColorMode(spdlog::color_mode::never);
Expand All @@ -87,6 +92,7 @@ TEST_F(ConsoleNew_TEST, RootLoggerNoColor)
spdlog::get("gz")->critical("This is a critical message");
}

/////////////////////////////////////////////////
TEST_F(ConsoleNew_TEST, RootLoggerMacros)
{
gztrace << "This is a trace message";
Expand All @@ -97,6 +103,7 @@ TEST_F(ConsoleNew_TEST, RootLoggerMacros)
gzcrit << "This is a critical message";
}

/////////////////////////////////////////////////
TEST_F(ConsoleNew_TEST, LogToFile)
{
gzLogInit("", "test.log");
Expand Down

0 comments on commit d24b2cb

Please sign in to comment.