Skip to content

File logger.hpp

File List > include > nebula_core_common > loggers > logger.hpp

Go to the documentation of this file

// Copyright 2024 TIER IV, Inc.
//
// 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.

#pragma once

#include <chrono>
#include <cstdint>
#include <map>
#include <memory>
#include <mutex>
#include <set>
#include <sstream>
#include <stdexcept>
#include <string>
#include <string_view>
#include <utility>

#define NEBULA_LOG_STREAM(log_func, stream_args)                     \
  {                                                                  \
    log_func(::nebula::drivers::loggers::detail::LazyMessage{[&]() { \
      std::stringstream ss{};                                        \
      ss << stream_args;                                             \
      return ss.str();                                               \
    }});                                                             \
  }

namespace nebula::drivers::loggers
{

namespace detail
{

template <typename MakeMessageT>
struct LazyMessage
{
  MakeMessageT make_message;

  operator std::string() const { return make_message(); }  // NOLINT(runtime/explicit)
};

template <typename MakeMessageT>
LazyMessage(MakeMessageT) -> LazyMessage<MakeMessageT>;

}  // namespace detail

class Logger
{
public:
  class Filtered
  {
  public:
    void debug(const std::string & message) const
    {
      if (target_) target_->debug(message);
    }
    void info(const std::string & message) const
    {
      if (target_) target_->info(message);
    }
    void warn(const std::string & message) const
    {
      if (target_) target_->warn(message);
    }
    void error(const std::string & message) const
    {
      if (target_) target_->error(message);
    }

    template <typename MakeMessageT>
    void debug(const detail::LazyMessage<MakeMessageT> & message) const
    {
      if (target_) target_->debug(message.make_message());
    }
    template <typename MakeMessageT>
    void info(const detail::LazyMessage<MakeMessageT> & message) const
    {
      if (target_) target_->info(message.make_message());
    }
    template <typename MakeMessageT>
    void warn(const detail::LazyMessage<MakeMessageT> & message) const
    {
      if (target_) target_->warn(message.make_message());
    }
    template <typename MakeMessageT>
    void error(const detail::LazyMessage<MakeMessageT> & message) const
    {
      if (target_) target_->error(message.make_message());
    }

    explicit operator bool() const { return target_ != nullptr; }

  private:
    friend class Logger;
    explicit Filtered(Logger * target) : target_(target) {}

    Logger * target_;
  };

  virtual ~Logger() = default;

  virtual void debug(const std::string & message) = 0;
  virtual void info(const std::string & message) = 0;
  virtual void warn(const std::string & message) = 0;
  virtual void error(const std::string & message) = 0;

  virtual std::shared_ptr<Logger> child(const std::string & name) = 0;

  Filtered throttled(
    std::chrono::nanoseconds period, const char * file = __builtin_FILE(),
    uint32_t line = __builtin_LINE())
  {
    if (period.count() < 0) {
      throw std::invalid_argument("Throttle period must not be negative");
    }

    const uint64_t period_ns = static_cast<uint64_t>(period.count());
    const uint64_t now_ns = steady_now_ns();

    std::lock_guard lock(filter_mutex_);
    auto [it, is_first_call] = throttle_last_passed_ns_.try_emplace(CallSite{file, line}, now_ns);
    if (is_first_call) {
      return Filtered(this);
    }

    auto & last_passed_ns = it->second;
    if (now_ns - last_passed_ns < period_ns) {
      return Filtered(nullptr);
    }

    last_passed_ns = now_ns;
    return Filtered(this);
  }

  Filtered once(const char * file = __builtin_FILE(), uint32_t line = __builtin_LINE())
  {
    std::lock_guard lock(filter_mutex_);
    const bool is_first_call = once_passed_.emplace(file, line).second;
    return Filtered(is_first_call ? this : nullptr);
  }

protected:
  virtual uint64_t steady_now_ns() const
  {
    return static_cast<uint64_t>(std::chrono::duration_cast<std::chrono::nanoseconds>(
                                   std::chrono::steady_clock::now().time_since_epoch())
                                   .count());
  }

private:
  using CallSite = std::pair<std::string_view, uint32_t>;

  std::mutex filter_mutex_;
  std::map<CallSite, uint64_t> throttle_last_passed_ns_;
  std::set<CallSite> once_passed_;
};

}  // namespace nebula::drivers::loggers