Merge pull request 'nomacros' (#16) from nomacros into main

Reviewed-on: #16
This commit is contained in:
maxine
2024-08-13 16:21:49 -04:00
14 changed files with 525 additions and 507 deletions

View File

@@ -28,7 +28,7 @@ CPMAddPackage(
CPMAddPackage(
NAME mcolor
URL https://git.redacted.cc/maxine/mcolor/archive/Prerelease-1.zip
URL https://git.redacted.cc/maxine/mcolor/archive/Prerelease-4.zip
)
if (UNIX)
@@ -49,7 +49,7 @@ install(FILES ${jlog_HEADERS} DESTINATION include/${PROJECT_NAME})
#add_subdirectory(tests)
target_link_libraries(jlog PRIVATE Event mcolor)
target_link_libraries(jlog PUBLIC Event mcolor)
add_executable(LoggerDemo main.cpp)
target_link_libraries(LoggerDemo PUBLIC jlog)

View File

@@ -8,10 +8,11 @@ jlog is a C++ library for logging to file, console, and event callbacks.
* Modern (C++20)
* Static Library
* Color Output
* Color Output (Now in RGB!)
* Logs to file AND console!
* Idiomatic Event callback for hooking into your game engine gui!
* GCC and MSVC support
* No more macros for traceback!
## Installation
@@ -35,17 +36,15 @@ Using jlog is straightforward:
```cpp
#include <jlog.h>
#include <jlog/jlog.hpp>
int main() {
LOGLEVEL(jlog::severity::debug); // <- see jlog::severity for full list of log levels
INFO("This is barely useful information.");
DEBUG("Debugging Information");
VERBOSE("Yadda Yadda Yadda");
WARNING("Slight miscalculation!");
ERROR("Oops, something went wrong.");
FATAL("Unrecoverable Error!!!");
jlog::info("This is barely useful information.");
jlog::debug("Debugging Information");
jlog::verbose("Yadda Yadda Yadda");
jlog::warning("Slight miscalculation!");
jlog::error("Oops, something went wrong.");
jlog::fatal("Unrecoverable Error!!!");
return 0;
}
@@ -58,8 +57,6 @@ int main() {
## TODO
* Custom Contexts: Allow users to specify custom logging contexts for better organization.
* Disable & sort by context (other categories?)
* Documentation
* Thread Safety
* Memory Safety

BIN
img.png

Binary file not shown.

Before

Width:  |  Height:  |  Size: 39 KiB

After

Width:  |  Height:  |  Size: 152 KiB

130
include/jlog/formatter.hpp Normal file
View File

@@ -0,0 +1,130 @@
#pragma once
#include "token.hpp"
namespace jlog {
/// Returns a string timestamp in the format of 'YYYY-MM-DD hh:mm:ss.ms'
std::string get_timestamp();
/// Returns a pseudo-"stacktrace" formatted sequence of tokens.
/// @param func The function name/signature to trace back to. Should be provided by a __FUNCTION__ macro variant.
/// @param file The file name to trace back to. Should be provided by a __FILE__ macro variant.
/// @param line The source-code line to trace back to. Should be provided by a __LINE__ macro variant.
std::vector<token> trace_format(
const std::string &func,
const std::string &file,
int line);
/// Returns a formatted sequence of tokens given a severity and message.
/// @param severity_name The severity tag to prefix to the message. Could theoretically also be a context.
/// @param message The actual message to include
/// @param severity_cc The colorcode to assign to the severity.
std::vector<token> log_format(
const std::string &severity_name,
const std::string &message,
const Color4 &severity_cc = Colors::White);
/// Returns a more detailed formatted sequence of tokens.
/// @param severity_name The severity tag to prefix to the message. Could theoretically also be a context.
/// @param message The actual message to include
/// @param func The function name/signature to trace back to. Should be provided by a __FUNCTION__ macro variant.
/// @param file The file name to trace back to. Should be provided by a __FILE__ macro variant.
/// @param line The source-code line to trace back to. Should be provided by a __LINE__ macro variant.
/// @param severity_cc The colorcode to assign to the severity.
std::vector<token> log_format(
const std::string &severity_name,
const std::string &message,
const std::string &func,
const std::string &file,
int line,
const Color4 &severity_cc = Colors::White);
/// Returns a token sequence pre-formatted for the info LogTrace level.
/// @param message The message to send out.
std::vector<token> info_format(const std::string &message);
/// Returns a token sequence pre-formatted for the info LogTrace level.
/// @param message The message to send out.
/// @param func The function name/signature to trace back to. Should be provided by a __FUNCTION__ macro variant.
/// @param file The file name to trace back to. Should be provided by a __FILE__ macro variant.
/// @param line The source-code line to trace back to. Should be provided by a __LINE__ macro variant.
std::vector<token> info_detailed_format(
const std::string &message,
const std::string &func,
const std::string &file,
int line);
/// Returns a token sequence pre-formatted for the warning LogTrace level.
/// @param message The message to send out.
std::vector<token> warning_format(const std::string &message);
/// Returns a token sequence pre-formatted for the warning LogTrace level.
/// @param message The message to send out.
/// @param func The function name/signature to trace back to. Should be provided by a __FUNCTION__ macro variant.
/// @param file The file name to trace back to. Should be provided by a __FILE__ macro variant.
/// @param line The source-code line to trace back to. Should be provided by a __LINE__ macro variant.
std::vector<token> warning_detailed_format(
const std::string &message,
const std::string &func,
const std::string &file,
int line);
/// Returns a token sequence pre-formatted for the error LogTrace level.
/// @param message The message to send out.
std::vector<token> error_format(const std::string &message);
/// Returns a token sequence pre-formatted for the error LogTrace level.
/// @param message The message to send out.
/// @param func The function name/signature to trace back to. Should be provided by a __FUNCTION__ macro variant.
/// @param file The file name to trace back to. Should be provided by a __FILE__ macro variant.
/// @param line The source-code line to trace back to. Should be provided by a __LINE__ macro variant.
std::vector<token> error_detailed_format(
const std::string &message,
const std::string &func,
const std::string &file,
int line);
/// Returns a token sequence pre-formatted for the fatal LogTrace level.
/// @param message The message to send out.
std::vector<token> fatal_format(const std::string &message);
/// Returns a token sequence pre-formatted for the fatal LogTrace level.
/// @param message The message to send out.
/// @param func The function name/signature to trace back to. Should be provided by a __FUNCTION__ macro variant.
/// @param file The file name to trace back to. Should be provided by a __FILE__ macro variant.
/// @param line The source-code line to trace back to. Should be provided by a __LINE__ macro variant.
std::vector<token> fatal_detailed_format(
const std::string &message,
const std::string &func,
const std::string &file,
int line);
/// Returns a token sequence pre-formatted for the verbose LogTrace level.
/// @param message The message to send out.
std::vector<token> verbose_format(const std::string &message);
/// Returns a token sequence pre-formatted for the verbose LogTrace level.
/// @param message The message to send out.
/// @param func The function name/signature to trace back to. Should be provided by a __FUNCTION__ macro variant.
/// @param file The file name to trace back to. Should be provided by a __FILE__ macro variant.
/// @param line The source-code line to trace back to. Should be provided by a __LINE__ macro variant.
std::vector<token> verbose_detailed_format(
const std::string &message,
const std::string &func,
const std::string &file,
int line);
/// Returns a token sequence pre-formatted for the debug LogTrace level.
/// @param message The message to send out.
std::vector<token> debug_format(const std::string &message);
/// Returns a token sequence pre-formatted for the debug LogTrace level.
/// @param message The message to send out.
/// @param func The function name/signature to trace back to. Should be provided by a __FUNCTION__ macro variant.
/// @param file The file name to trace back to. Should be provided by a __FILE__ macro variant.
/// @param line The source-code line to trace back to. Should be provided by a __LINE__ macro variant.
std::vector<token> debug_detailed_format(
const std::string &message,
const std::string &func,
const std::string &file,
int line);
}

14
include/jlog/io.hpp Normal file
View File

@@ -0,0 +1,14 @@
#pragma once
#include <string>
namespace jlog
{
/// Writes an input string directly to standard output
/// @note Does not append a newline to the message.
void log_to_console(const std::string &message);
/// Writes an input string directly to the specified destination logfile
/// @note Does not append a newline to the message.
void log_to_file(const std::string &filename, const std::string &message);
}

View File

@@ -8,236 +8,27 @@
#pragma once
#include <string>
#include <map>
#include <Event.h>
#include <mcolor.h>
#include "token.hpp"
#include "formatter.hpp"
#include "source_location"
#include <jlog/logger.hpp>
#ifdef __linux__
#define FUNCTION __PRETTY_FUNCTION__
#endif
namespace jlog {
#ifdef _WIN32
#define FUNCTION __FUNCSIG__
#endif
using namespace mcolor;
namespace jlog
{
/// Built-in Global Loggers
extern Logger info;
extern Logger warning;
extern Logger error;
extern Logger fatal;
extern Logger verbose;
extern Logger debug;
/// Severity levels for logging. Higher numbers filter less messages out.
/// @see LOG_LEVEL macro
enum class severity : uint8_t
{
none, // Show no output
fatal, // Show only fatal errors
error, // Show fatal and not-necessarily-fatal errors
warning, // Show warnings additionally
verbose, // Show errors, warnings, and 'verbose' output (i.e. extra information)
debug, // Show debugging messages (Basically everything).
};
inline severity loglevel = severity::debug; // Default log level always debug
inline bool console_logging = true;
struct LogEntry
{
severity level;
std::string content;
std::string timestamp;
};
// TODO: Fully implement logging callback.
static Event<LogEntry> on_log = Event<LogEntry>();
inline std::vector<LogEntry> log_history;
/// A single piece of a logging message, with color code, content, and delimiter
/// These are strung together to build full logger messages in a flexible manner.
struct token
{
mcolor::ansiColors::Colors colorCode = mcolor::ansiColors::Colors::FG_DEFAULT;
std::string content = "";
std::string delimiter = "[]";
};
void set_default_logfile(const std::string& filename);
/// Returns a string timestamp in the format of 'YYYY-MM-DD hh:mm:ss.ms'
std::string get_timestamp();
/// Writes an input string directly to standard output
/// @note Does not append a newline to the message.
void log_to_console(const std::string& message);
/// Writes an input string directly to the default destination logfile
/// @note Does not append a newline to the message.
/// @see set_default_logfile()
void log_to_file(const std::string& message);
/// Writes an input string directly to the specified destination logfile
/// @note Does not append a newline to the message.
void log_to_file(const std::string& filename, const std::string& message);
/// Writes an input string directly to the specified output stream
/// @note Does not append a newline to the message.
void log_to_stream(std::ostream stream, const std::string& message);
/// These are helper functions designed to be wrapped around for easier custom logger building.
/// @note This file is implemented differently per-platform to handle differences in console color handling.
/// @see windows/jlog.cpp linux/jlog.cpp
std::string toks2msg(std::vector<token> tokens, std::function<std::string(token)> formatter);
std::string consoleMsgFormatter(token t);
std::string logfileMsgFormatter(token t);
std::string toks2consoleMsg(std::vector<token> tokens);
std::string toks2logfileMsg(std::vector<token> tokens);
/// Parses a sequence of tokens into a printable message, and logs to the following destinations:
/// standard output (console)
/// output file (default)
/// logging callback (Event)
/// @note This file is implemented differently per-platform to handle differences in console color handling.
/// @see windows/jlog.cpp linux/jlog.cpp
void log(const std::vector<token>& tokens, const std::string& filename);
void log(const std::vector<token>& tokens);
void ltlog(const std::vector<token>& tokens); // Just for debug purposes
#pragma region Generic Formatters
/// Returns a pseudo-"stacktrace" formatted sequence of tokens.
/// @param func The function name/signature to trace back to. Should be provided by a __FUNCTION__ macro variant.
/// @param file The file name to trace back to. Should be provided by a __FILE__ macro variant.
/// @param line The source-code line to trace back to. Should be provided by a __LINE__ macro variant.
std::vector<token> trace_format(
const std::string& func,
const std::string& file,
int line);
/// Returns a formatted sequence of tokens given a severity and message.
/// @param severity_name The severity tag to prefix to the message. Could theoretically also be a context.
/// @param message The actual message to include
/// @param severity_cc The colorcode to assign to the severity.
std::vector<token> log_format(
const std::string& severity_name,
const std::string& message,
const mcolor::ansiColors::Colors& severity_cc = mcolor::ansiColors::Colors::FG_WHITE);
/// Returns a more detailed formatted sequence of tokens.
/// @param severity_name The severity tag to prefix to the message. Could theoretically also be a context.
/// @param message The actual message to include
/// @param func The function name/signature to trace back to. Should be provided by a __FUNCTION__ macro variant.
/// @param file The file name to trace back to. Should be provided by a __FILE__ macro variant.
/// @param line The source-code line to trace back to. Should be provided by a __LINE__ macro variant.
/// @param severity_cc The colorcode to assign to the severity.
std::vector<token> log_detailed_format(
const std::string& severity_name,
const std::string& message,
const std::string& func,
const std::string& file,
int line,
const mcolor::ansiColors::Colors& severity_cc = mcolor::ansiColors::Colors::FG_WHITE);
/// Returns a token sequence pre-formatted for the INFO log level.
/// @param message The message to send out.
std::vector<token> info_format(const std::string& message);
/// Returns a token sequence pre-formatted for the INFO log level.
/// @param message The message to send out.
/// @param func The function name/signature to trace back to. Should be provided by a __FUNCTION__ macro variant.
/// @param file The file name to trace back to. Should be provided by a __FILE__ macro variant.
/// @param line The source-code line to trace back to. Should be provided by a __LINE__ macro variant.
std::vector<token> info_detailed_format(
const std::string &message,
const std::string &func,
const std::string &file,
int line);
/// Returns a token sequence pre-formatted for the WARNING log level.
/// @param message The message to send out.
std::vector<token> warning_format(const std::string& message);
/// Returns a token sequence pre-formatted for the WARNING log level.
/// @param message The message to send out.
/// @param func The function name/signature to trace back to. Should be provided by a __FUNCTION__ macro variant.
/// @param file The file name to trace back to. Should be provided by a __FILE__ macro variant.
/// @param line The source-code line to trace back to. Should be provided by a __LINE__ macro variant.
std::vector<token> warning_detailed_format(
const std::string &message,
const std::string &func,
const std::string &file,
int line);
/// Returns a token sequence pre-formatted for the ERROR log level.
/// @param message The message to send out.
std::vector<token> error_format(const std::string& message);
/// Returns a token sequence pre-formatted for the ERROR log level.
/// @param message The message to send out.
/// @param func The function name/signature to trace back to. Should be provided by a __FUNCTION__ macro variant.
/// @param file The file name to trace back to. Should be provided by a __FILE__ macro variant.
/// @param line The source-code line to trace back to. Should be provided by a __LINE__ macro variant.
std::vector<token> error_detailed_format(
const std::string &message,
const std::string &func,
const std::string &file,
int line);
/// Returns a token sequence pre-formatted for the FATAL log level.
/// @param message The message to send out.
std::vector<token> fatal_format(const std::string& message);
/// Returns a token sequence pre-formatted for the FATAL log level.
/// @param message The message to send out.
/// @param func The function name/signature to trace back to. Should be provided by a __FUNCTION__ macro variant.
/// @param file The file name to trace back to. Should be provided by a __FILE__ macro variant.
/// @param line The source-code line to trace back to. Should be provided by a __LINE__ macro variant.
std::vector<token> fatal_detailed_format(
const std::string &message,
const std::string &func,
const std::string &file,
int line);
/// Returns a token sequence pre-formatted for the VERBOSE log level.
/// @param message The message to send out.
std::vector<token> verbose_format(const std::string& message);
/// Returns a token sequence pre-formatted for the VERBOSE log level.
/// @param message The message to send out.
/// @param func The function name/signature to trace back to. Should be provided by a __FUNCTION__ macro variant.
/// @param file The file name to trace back to. Should be provided by a __FILE__ macro variant.
/// @param line The source-code line to trace back to. Should be provided by a __LINE__ macro variant.
std::vector<token> verbose_detailed_format(
const std::string &message,
const std::string &func,
const std::string &file,
int line);
/// Returns a token sequence pre-formatted for the DEBUG log level.
/// @param message The message to send out.
std::vector<token> debug_format(const std::string& message);
/// Returns a token sequence pre-formatted for the DEBUG log level.
/// @param message The message to send out.
/// @param func The function name/signature to trace back to. Should be provided by a __FUNCTION__ macro variant.
/// @param file The file name to trace back to. Should be provided by a __FILE__ macro variant.
/// @param line The source-code line to trace back to. Should be provided by a __LINE__ macro variant.
std::vector<token> debug_detailed_format(
const std::string &message,
const std::string &func,
const std::string &file,
int line);
#pragma endregion
void SetTracebackOnGlobalLoggers(bool enabled);
}
#define INFO(i) if (jlog::loglevel >= jlog::severity::none) { jlog::log(jlog::info_detailed_format(i, FUNCTION, __FILE__, __LINE__)); }
#define VERBOSE(i) if (jlog::loglevel >= jlog::severity::verbose) { jlog::log(jlog::verbose_detailed_format(i, FUNCTION, __FILE__, __LINE__)); }
#define DEBUG(i) if (jlog::loglevel >= jlog::severity::debug) { jlog::log(jlog::debug_detailed_format(i, FUNCTION, __FILE__, __LINE__)); }
#define WARNING(i) if (jlog::loglevel >= jlog::severity::warning) { jlog::log(jlog::warning_detailed_format(i, FUNCTION, __FILE__, __LINE__)); }
#define ERROR(i) if (jlog::loglevel >= jlog::severity::error) { jlog::log(jlog::error_detailed_format(i, FUNCTION, __FILE__, __LINE__)); }
#define FATAL(i) if (jlog::loglevel >= jlog::severity::fatal) { jlog::log(jlog::fatal_detailed_format(i, FUNCTION, __FILE__, __LINE__)); }
#define LOGLEVEL(i) jlog::loglevel = i;
#define CONSOLELOGGING(i) jlog::console_logging = i
#define LOGTEST(i) if (jlog::loglevel >= jlog::severity::none) { jlog::ltlog(jlog::info_detailed_format(i, FUNCTION, __FILE__, __LINE__)); }

51
include/jlog/logger.hpp Normal file
View File

@@ -0,0 +1,51 @@
#pragma once
#include <mcolor.h>
#include "Colors.hpp"
#include <source_location>
#include <map>
#include <jlog/token.hpp>
#include <Event.h>
namespace jlog
{
using namespace mcolor;
///
class Logger {
public:
explicit Logger(const std::string& context, const Color4& color = Colors::LightGray);
public:
Event<std::vector<token>> OnLogEvent;
public:
void operator () (const std::string& message, const std::source_location& location = std::source_location::current());
virtual void Log(const std::string &message, const std::source_location& location = std::source_location::current());
//virtual void LogTrace(const std::vector<token> tokens);
//virtual void LogTrace(const std::string& context, const std::string &message);
//virtual void LogTrace(const std::string &message, const std::source_location& location = std::source_location::current());
public:
void SetEnabled(bool state);
void Enable();
void Disable();
bool Enabled();
void LogFile(const std::string& f);
std::string LogFile();
// no cc no bullshit
//void SetColorCode(AnsiColor cc = AnsiColor::FG_DEFAULT);
//AnsiColor GetColorCode();
void SetColorCode(Color4 cc = Colors::LightGray);
Color4 GetColorCode();
public:
std::string Context();
void SetTraceback(bool enabled);
/**/
protected:
bool enabled = true;
std::string logfile = "latest.log";
//AnsiColor colorcode = AnsiColor::FG_DEFAULT;
Color4 colorcode = Colors::LightGray;
std::string context;
bool trace = true;
};
}

25
include/jlog/token.hpp Normal file
View File

@@ -0,0 +1,25 @@
#pragma once
#include <functional>
#include <mcolor.h>
#include "Colors.hpp"
namespace jlog {
using namespace mcolor;
/// A single piece of a logging message, with color code, content, and delimiter
/// These are strung together to build full logger messages in a flexible manner.
struct token {
Color4 colorCode = Colors::White;
std::string content = "";
std::string delimiter = "[]";
};
/// These are helper functions designed to be wrapped around for easier custom logger building.
std::string toks2msg(std::vector<token> tokens, std::function<std::string(token)>);
std::string consoleMsgFormatter(token t);
std::string logfileMsgFormatter(token t);
std::string toks2consoleMsg(std::vector<token> tokens);
std::string toks2logfileMsg(std::vector<token> tokens);
}

View File

@@ -4,44 +4,80 @@
// Contact: josh@redacted.cc
// Contributors: william@redacted.cc maxi@redacted.cc
// This work is dedicated to the public domain.
#include <jlog/jlog.hpp>
// Writing custom wrappers for jlog is super easy!
/*void coollog(std::vector<jlog::token> tokens) {
std::vector<jlog::token> wtokens;
auto group = jlog::token{.content = "COOLLOGGER"};
wtokens.push_back(group);
wtokens.insert(wtokens.end(), tokens.begin(), tokens.end());
jlog::log(wtokens);
}*/
// We can either define custom logging macros or redefine jlog's builtin macros.
//#define COOLINFO(i) coollog(jlog::info_format(i));
//#define COOLINFOTRACE(i) coollog(jlog::info_detailed_format(i, FUNCTION, __FILE__, __LINE__));
#include <jlog/io.hpp>
#include <mcolor.h>
int main()
{
LOGLEVEL(jlog::severity::debug); // <- see jlog::severity for full list of log levels
CONSOLELOGGING(true); // <- Set to true or false to enable/disable logging to console. Useful for release builds of a program.
#ifdef _WIN32
jlog::set_default_logfile("NUL");
#else
jlog::set_default_logfile("/dev/null");
#endif
using namespace mcolor;
INFO("This is barely useful information.");
DEBUG("Debugging Information");
VERBOSE("Yadda Yadda Yadda");
WARNING("Slight miscalculation!");
ERROR("Oops, something went wrong.");
FATAL("Unrecoverable Error!!!");
jlog::Logger demo{"demo", Colors::Pinks::DeepPink};
demo.SetTraceback(false);
demo(std::format("{}\n>\t{}\n>\t{}",
"Custom loggers such as this one can be easily created",
"jlog::Logger demo{\"demo\", Colors::Pinks::DeepPink};", "demo.SetTraceback(false);"));
// "Custom loggers such as this one can be easily created."));
//COOLINFO("This is really cool!!!");
//COOLINFOTRACE("THIS IS EVEN COOLER!!!");
LOGTEST("This is a really cool test man :3");
LOGTEST("Go check cmake-build-debug/logtest.log and cmake-build-debug/latest.log");
// Traceback is enabled on global Loggers by default
demo("Traceback is enabled on global Loggers by default");
jlog::info("info message traceback");
jlog::debug("debug message traceback");
jlog::verbose("verbose message traceback");
jlog::warning("warning message traceback");
jlog::error("error message traceback");
jlog::fatal("fatal message traceback");
// We can disable/enable traceback on a logger
demo("We can disable/enable traceback on a logger");
demo("Disable = demo.SetTraceback(false);");
demo.SetTraceback(true);
demo("Enable = demo.SetTraceback(true);");
demo.SetTraceback(false);
// We can set the traceback for all the global loggers.
demo(std::format("{}\n>\t{}", "We can set the traceback for all the global loggers.", "jlog::SetTracebackOnGlobalLoggers(false);"));
jlog::SetTracebackOnGlobalLoggers(false);
jlog::info("info message");
jlog::debug("debug message");
jlog::verbose("verbose message");
jlog::warning("warning message");
jlog::error("error message");
jlog::fatal("fatal message");
// We can enable/disable loggers.
demo(std::format("{}\n>\t{}\n>\t{}", "We can enable/disable loggers.", "jlog::info.Enable();", "jlog::info.Disable();"));
jlog::info.Enable();
jlog::info("Logger enabled");
jlog::info.Disable();
demo("You won't see the 'Logger disabled' message here since we just disabled it. Check main.cpp for proof.");
jlog::info("Logger disabled");
jlog::info.Enable();
// We can also add event hooks to a logger.
demo(std::format("{}\n>\t{}\n>\t\t{}\n>\n>\t\t{}\n>\t{}",
"We can also add event hooks to a logger.",
"demo.OnLogEvent += [](std::vector<jlog::token> t) {",
"jlog::token dbg = {.colorCode = jlog::debug.GetColorCode(), .content = \"This message is only seen when the event hook is added.\"};",
"jlog::log_to_console(jlog::toks2consoleMsg(std::vector<jlog::token>{dbg}));",
"}"
));
demo("Before event hook");
// Create and add event hook.
demo.OnLogEvent += [](std::vector<jlog::token> t) {
jlog::token dbg = {.colorCode = jlog::debug.GetColorCode(), .content = "This message is only seen when the event hook is added."};
jlog::log_to_console(jlog::toks2consoleMsg(std::vector<jlog::token>{dbg}));
};
demo("After event hook");
return 0;
}

63
src/jlog/formatter.cpp Normal file
View File

@@ -0,0 +1,63 @@
#include <string>
#include <format>
#include <vector>
#include <chrono>
#include "mcolor.h"
#include "jlog/formatter.hpp"
#include "jlog/token.hpp"
namespace jlog {
std::string get_timestamp() {
using namespace std::chrono;
auto const timestamp = current_zone()->to_local(system_clock::now());
auto dp = floor<days>(timestamp);
year_month_day ymd{floor<days>(timestamp)};
hh_mm_ss time{floor<milliseconds>(timestamp - dp)};
auto y = ymd.year();
auto m = ymd.month();
auto d = ymd.day();
auto h = time.hours();
auto M = time.minutes();
auto s = time.seconds();
auto ms = time.subseconds();
return std::format("{}-{}-{} {}:{}:{}.{}", y, m, d, h.count(), M.count(), s.count(), ms.count());
}
std::vector<token> trace_format(
const std::string& func,
const std::string& file,
int line)
{
auto trace = token{.content = func};
auto filedata = token{.content = std::format("{}:{}", file, line)};
return {trace, filedata};
}
std::vector<token> log_format(
const std::string& severity_name,
const std::string& message,
const Color4& severity_cc)
{
auto severity = token{.colorCode = severity_cc, .content = severity_name};
auto content = token{.content = message, .delimiter = ""};
return {severity, content};
}
std::vector<token> log_format(
const std::string& severity_name,
const std::string& message,
const std::string& func,
const std::string& file,
int line,
const Color4& severity_cc)
{
std::vector<token> tokens;
auto timestamp = token{.content = jlog::get_timestamp()};
auto tf_tokens = jlog::trace_format(func, file, line);
auto lf_tokens = jlog::log_format(severity_name, message, severity_cc);
tokens.push_back(timestamp);
tokens.insert(tokens.end(), tf_tokens.begin(), tf_tokens.end());
tokens.insert(tokens.end(), lf_tokens.begin(), lf_tokens.end());
return tokens;
}
}

23
src/jlog/io.cpp Normal file
View File

@@ -0,0 +1,23 @@
#include <mcolor.h>
#include <jlog/io.hpp>
#include <fstream>
#include <iostream>
#include <chrono>
namespace jlog
{
void log_to_console(const std::string& message)
{
#ifdef WIN32
mcolor::windowsSaneify();
#endif
std::cout << message;
}
void log_to_file(const std::string& filename, const std::string& message)
{
std::ofstream latest_log(filename, std::ios_base::app);
latest_log << message;
latest_log.close();
}
}

View File

@@ -3,251 +3,28 @@
#include <iostream>
#include <chrono>
/*
#ifdef WIN32
#define NOMINMAX
#include <windows.h>
#endif
*/
namespace jlog
{
static std::string default_logfile = "latest.log";
Logger info {"info", Colors::Primary::Green};
Logger warning {"warning", Colors::Primary::Yellow};
Logger error {"error", Colors::Primary::Red};
Logger fatal {"fatal", Colors::Reds::Crimson};
Logger verbose {"verbose", Colors::Primary::Blue};
Logger debug {"debug", Colors::Purples::Purple};
void set_default_logfile(const std::string& filename)
{
default_logfile = filename;
}
std::string get_timestamp()
{
using namespace std::chrono;
auto const timestamp = current_zone()->to_local(system_clock::now());
auto dp = floor<days>(timestamp);
year_month_day ymd{floor<days>(timestamp)};
hh_mm_ss time{floor<milliseconds>(timestamp - dp)};
auto y = ymd.year();
auto m = ymd.month();
auto d = ymd.day();
auto h = time.hours();
auto M = time.minutes();
auto s = time.seconds();
auto ms = time.subseconds();
return std::format("{}-{}-{} {}:{}:{}.{}", y, m, d, h.count(), M.count(), s.count(), ms.count());
}
void log_to_console(const std::string& message)
{
#ifdef WIN32
mcolor::windowsSaneify();
#endif
std::cout << message;
}
void log_to_file(const std::string& message)
{
std::ofstream latest_log(default_logfile, std::ios_base::app);
latest_log << message;
latest_log.close();
}
void log_to_file(const std::string& filename, const std::string& message)
{
std::ofstream latest_log(filename, std::ios_base::app);
latest_log << message;
latest_log.close();
}
void log_to_stream(std::ostream stream, const std::string& message)
{
stream << message;
}
std::string toks2msg(std::vector<token> tokens, std::function<std::string(token)> formatter)
{
std::string msg;
for (const token& t: tokens)
{
msg += formatter(t);
}
return msg;
}
std::string toks2consoleMsg(std::vector<token> tokens)
{
return toks2msg(tokens, consoleMsgFormatter);
}
std::string toks2logfileMsg(std::vector<token> tokens)
{
return toks2msg(tokens, logfileMsgFormatter);
}
std::string consoleMsgFormatter(token t)
{
if (!t.delimiter.empty())
{
return std::format("{}{}{}{}{} ", mcolor::toEscapeCode(t.colorCode), t.delimiter[0], t.content, t.delimiter[1], mcolor::toEscapeCode(mcolor::ansiColors::Colors::RESET));
}
return std::format("{}{}{} ", mcolor::toEscapeCode(t.colorCode), t.content, mcolor::toEscapeCode(mcolor::ansiColors::Colors::RESET));
}
std::string logfileMsgFormatter(token t)
{
if (!t.delimiter.empty())
{
return std::format("{}{}{} ", t.delimiter[0], t.content, t.delimiter[1]);
}
return t.content + " ";
}
void log(const std::vector<token>& tokens, const std::string& filename)
{
if (console_logging) {
log_to_console(toks2consoleMsg(tokens));
log_to_console("\n");
}
log_to_file(filename, toks2logfileMsg(tokens));
log_to_file(filename, "\n");
}
void log(const std::vector<token>& tokens)
{
log(tokens, default_logfile);
}
// Mainly for debug purposes
void ltlog(const std::vector<token>& tokens)
{
std::vector<token> wtokens;
//auto head = token{.colorCode = ansi_escape_codes::true_color(color_codes::BG_RED.rgb.r, color_codes::BG_RED.rgb.g, color_codes::BG_RED.rgb.b), .content = "GAS"};
//wtokens.push_back(head);
wtokens.insert(wtokens.end(), tokens.begin(), tokens.end());
log(wtokens);
log_to_file("logtest.log", toks2logfileMsg(wtokens) + "\n");
}
std::vector<token> trace_format(
const std::string& func,
const std::string& file,
int line)
{
auto trace = token{.content = func};
auto filedata = token{.content = std::format("{}:{}", file, line)};
return {trace, filedata};
}
std::vector<token> info_format(const std::string& message)
{
return log_format("INFO", message);
}
std::vector<token> warning_format(const std::string& message)
{
return log_format("INFO", message, mcolor::ansiColors::Colors::FG_YELLOW);
}
std::vector<token> error_format(const std::string& message)
{
return log_format("ERROR", message, mcolor::ansiColors::Colors::FG_RED);
}
std::vector<token> fatal_format(const std::string& message)
{
return log_format("FATAL", message, mcolor::ansiColors::Colors::FG_BRIGHT_RED);
}
std::vector<token> verbose_format(const std::string& message)
{
return log_format("VERBOSE", message, mcolor::ansiColors::Colors::FG_CYAN);
}
std::vector<token> debug_format(const std::string& message)
{
return log_format("DEBUG", message, mcolor::ansiColors::Colors::FG_GREEN);
}
std::vector<token> debug_detailed_format(
const std::string& message,
const std::string& func,
const std::string& file,
int line)
{
return log_detailed_format("DEBUG", message, func, file, line, mcolor::ansiColors::Colors::FG_GREEN);
}
std::vector<token> info_detailed_format(
const std::string& message,
const std::string& func,
const std::string& file,
int line)
{
return log_detailed_format("INFO", message, func, file, line);
}
std::vector<token> warning_detailed_format(
const std::string& message,
const std::string& func,
const std::string& file,
int line)
{
return log_detailed_format("WARNING", message, func, file, line, mcolor::ansiColors::Colors::FG_YELLOW);
}
std::vector<token> error_detailed_format(
const std::string& message,
const std::string& func,
const std::string& file,
int line)
{
return log_detailed_format("ERROR", message, func, file, line, mcolor::ansiColors::Colors::FG_RED);
}
std::vector<token> verbose_detailed_format(
const std::string& message,
const std::string& func,
const std::string& file,
int line)
{
return log_detailed_format("VERBOSE", message, func, file, line, mcolor::ansiColors::Colors::FG_CYAN);
}
std::vector<token> fatal_detailed_format(
const std::string& message,
const std::string& func,
const std::string& file,
int line)
{
return log_detailed_format("FATAL", message, func, file, line, mcolor::ansiColors::Colors::FG_BRIGHT_RED);
}
std::vector<token> log_format(
const std::string& severity_name,
const std::string& message,
const mcolor::ansiColors::Colors& severity_cc)
{
auto severity = token{.colorCode = severity_cc, .content = severity_name};
auto content = token{.content = message, .delimiter = ""};
return {severity, content};
}
std::vector<token> log_detailed_format(
const std::string& severity_name,
const std::string& message,
const std::string& func,
const std::string& file,
int line,
const mcolor::ansiColors::Colors& severity_cc)
{
std::vector<token> tokens;
auto timestamp = token{.content = jlog::get_timestamp()};
auto tf_tokens = jlog::trace_format(func, file, line);
auto lf_tokens = jlog::log_format(severity_name, message, severity_cc);
tokens.push_back(timestamp);
tokens.insert(tokens.end(), tf_tokens.begin(), tf_tokens.end());
tokens.insert(tokens.end(), lf_tokens.begin(), lf_tokens.end());
return tokens;
void SetTracebackOnGlobalLoggers(bool enabled) {
info.SetTraceback(enabled);
warning.SetTraceback(enabled);
error.SetTraceback(enabled);
fatal.SetTraceback(enabled);
verbose.SetTraceback(enabled);
debug.SetTraceback(enabled);
}
}

59
src/jlog/logger.cpp Normal file
View File

@@ -0,0 +1,59 @@
#include <jlog/logger.hpp>
#include <jlog/jlog.hpp>
#include <jlog/formatter.hpp>
#include <jlog/token.hpp>
#include "jlog/io.hpp"
namespace jlog
{
Logger::Logger(const std::string& context, const Color4& color) {
this->context = context;
this->colorcode = color;
}
void Logger::Log(const std::string &message, const std::source_location& location) {
if (!enabled)
return;
std::vector<jlog::token> fmt;
if (trace)
fmt = log_format(this->context, message, location.function_name(), location.file_name(), location.line(),this->colorcode);
else
fmt = log_format(this->context, message, this->colorcode);
OnLogEvent(fmt);
jlog::log_to_console(jlog::toks2consoleMsg(fmt) + '\n');
jlog::log_to_file(this->logfile, jlog::toks2logfileMsg(fmt) + '\n');
}
void Logger::SetEnabled(bool state) {
this->enabled = state;
}
bool Logger::Enabled() { return this->enabled; }
void Logger::LogFile(const std::string& f) {
this->logfile = f;
}
std::string Logger::LogFile() { return this->logfile; }
//void Logger::SetColorCode(AnsiColor cc) { this->colorcode = cc; }
//AnsiColor Logger::GetColorCode() { return this->colorcode; }
void Logger::SetColorCode(Color4 cc) { this->colorcode = cc; }
Color4 Logger::GetColorCode() { return this->colorcode; }
std::string Logger::Context() { return this->context; }
void Logger::operator()(const std::string &message, const std::source_location& location) {
Log(message, location);
}
void Logger::SetTraceback(bool enabled) {
trace = enabled;
}
void Logger::Enable() { SetEnabled(true);}
void Logger::Disable() { SetEnabled(false); }
}

52
src/jlog/token.cpp Normal file
View File

@@ -0,0 +1,52 @@
#include <string>
#include <vector>
#include <functional>
#include <format>
#include <mcolor.h>
#include <jlog/token.hpp>
namespace jlog {
std::string toks2msg(std::vector <token> tokens, std::function<std::string(token)> formatter) {
std::string msg;
for (const token &t: tokens) {
msg += formatter(t);
}
return msg;
}
std::string toks2consoleMsg(std::vector <token> tokens) {
return toks2msg(tokens, consoleMsgFormatter);
}
std::string toks2logfileMsg(std::vector <token> tokens) {
return toks2msg(tokens, logfileMsgFormatter);
}
std::string consoleMsgFormatter(token t) {
// Just disable color output on Windows for now
// TODO: Figure out why ANSI RGB isn't working quite right on Windows
#ifdef WIN32
if (!t.delimiter.empty()) {
return std::format("{}{}{} ", t.delimiter[0], t.content, t.delimiter[1]);
}
return t.content + " ";
#else
if (!t.delimiter.empty()) {
return std::format("{}{}{}{}{} ", mcolor::toEscapeCode(t.colorCode), t.delimiter[0], t.content,
t.delimiter[1], mcolor::toEscapeCode(AnsiColor::RESET));
}
return std::format("{}{}{} ", mcolor::toEscapeCode(t.colorCode), t.content,
mcolor::toEscapeCode(AnsiColor::RESET));
#endif
}
std::string logfileMsgFormatter(token t) {
if (!t.delimiter.empty()) {
return std::format("{}{}{} ", t.delimiter[0], t.content, t.delimiter[1]);
}
return t.content + " ";
}
}