Program Listing for File logs.hpp

Return to documentation for file (include/yasmin/logs.hpp)

// Copyright (C) 2024  Miguel Ángel González Santamarta
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

#ifndef YASMIN_LOGS_HPP
#define YASMIN_LOGS_HPP

#include <cstdarg>
#include <cstdio>
#include <cstring>

namespace yasmin {

typedef void (*LogFunction)(const char *file, const char *function, int line,
                            const char *text, ...);

// Declare function pointers for logging at different severity levels
extern LogFunction log_error;
extern LogFunction log_warn;
extern LogFunction log_info;
extern LogFunction log_debug;

inline const char *extract_filename(const char *path) {
  const char *filename = std::strrchr(path, '/');
  if (!filename) {
    filename = std::strrchr(path, '\\'); // handle Windows-style paths
  }
  return filename ? filename + 1 : path;
}

// Macros for logging with automatic file and function information
#define YASMIN_LOG_ERROR(text, ...)                                            \
  yasmin::log_error(extract_filename(__FILE__), __FUNCTION__, __LINE__, text,  \
                    ##__VA_ARGS__)
#define YASMIN_LOG_WARN(text, ...)                                             \
  yasmin::log_warn(extract_filename(__FILE__), __FUNCTION__, __LINE__, text,   \
                   ##__VA_ARGS__)
#define YASMIN_LOG_INFO(text, ...)                                             \
  yasmin::log_info(extract_filename(__FILE__), __FUNCTION__, __LINE__, text,   \
                   ##__VA_ARGS__)
#define YASMIN_LOG_DEBUG(text, ...)                                            \
  yasmin::log_debug(extract_filename(__FILE__), __FUNCTION__, __LINE__, text,  \
                    ##__VA_ARGS__)

void set_loggers(LogFunction error, LogFunction warn, LogFunction info,
                 LogFunction debug);

void set_default_loggers();

} // namespace yasmin

#endif // YASMIN_LOGS_HPP