libsclogging/logger.hpp

84 lines
2.6 KiB
C++

//
// logger.hpp
// libsclogging
//
// Created by Bob Polis at 2020-04-29
// Copyright (c) 2020 SwiftCoder. All rights reserved.
//
#ifndef _logger_H_
#define _logger_H_
#include <iostream>
#include <string>
namespace sc {
enum class loglevel {
undefined,
debug,
info,
warning,
error,
critical
};
constexpr bool operator>=(loglevel lhs, loglevel rhs) {
return static_cast<int>(lhs) >= static_cast<int>(rhs);
}
constexpr const char* loglevel_desc(loglevel lvl) {
switch (lvl) {
case loglevel::undefined: return "UNDEFINED"; break;
case loglevel::debug: return "DEBUG"; break;
case loglevel::info: return "INFO"; break;
case loglevel::warning: return "WARNING"; break;
case loglevel::error: return "ERROR"; break;
case loglevel::critical: return "CRITICAL"; break;
}
return "";
}
class logger {
public:
logger(const std::string& name, loglevel level);
void msg(loglevel level, const char* file, int line, const char* func);
template<typename T, typename... Args>
void msg(loglevel level, const char* file, int line, const char* func,
T value, Args... args) {
if (level >= _level) {
if (_topcall) {
_topcall = false;
write_prefix(level, file, line, func);
}
std::cerr << value;
msg(level, file, line, func, args...);
}
}
loglevel level() const { return _level; }
void level(loglevel level) { _level = level; }
private:
void write_prefix(loglevel level,
const char* file,
int line,
const char* func);
loglevel _level {loglevel::info};
bool _topcall {true};
std::string _name;
};
}
#define SCDebug(logger, ...) logger.msg(sc::loglevel::debug, __FILE__, __LINE__, __FUNCTION__, __VA_ARGS__)
#define SCInfo(logger, ...) logger.msg(sc::loglevel::info, __FILE__, __LINE__, __FUNCTION__, __VA_ARGS__)
#define SCWarning(logger, ...) logger.msg(sc::loglevel::warning, __FILE__, __LINE__, __FUNCTION__, __VA_ARGS__)
#define SCError(logger, ...) logger.msg(sc::loglevel::error, __FILE__, __LINE__, __FUNCTION__, __VA_ARGS__)
#define SCCritical(logger, ...) logger.msg(sc::loglevel::critical, __FILE__, __LINE__, __FUNCTION__, __VA_ARGS__)
#endif // _logger_H_