yapb-noob-edition/ext/crlib/cr-logger.h

112 lines
2.3 KiB
C
Raw Normal View History

2019-07-27 17:36:24 +03:00
//
// YaPB - Counter-Strike Bot based on PODBot by Markus Klinge.
// Copyright © 2004-2020 YaPB Project <yapb@jeefo.net>.
2019-07-27 17:36:24 +03:00
//
// SPDX-License-Identifier: MIT
2019-07-27 17:36:24 +03:00
//
#pragma once
#include <time.h>
#include <crlib/cr-files.h>
#include <crlib/cr-lambda.h>
CR_NAMESPACE_BEGIN
class SimpleLogger final : public Singleton <SimpleLogger> {
public:
using PrintFunction = Lambda <void (const char *)>;
private:
String filename_;
2020-06-12 18:52:38 +03:00
PrintFunction printFun_;
2019-07-27 17:36:24 +03:00
public:
SimpleLogger () = default;
~SimpleLogger () = default;
2019-07-27 17:36:24 +03:00
public:
class LogFile final {
private:
File handle_;
public:
LogFile (StringRef filename) {
handle_.open (filename, "at");
}
~LogFile () {
handle_.close ();
}
public:
void print (StringRef msg) {
if (!handle_) {
return;
}
handle_.puts (msg.chars ());
}
};
2019-07-27 17:36:24 +03:00
private:
void logToFile (const char *level, const char *msg) {
time_t ticks = time (&ticks);
tm timeinfo {};
#if defined (CR_WINDOWS)
localtime_s (&timeinfo, &ticks);
#else
localtime_r (&ticks, &timeinfo);
#endif
2019-07-27 17:36:24 +03:00
auto timebuf = strings.chars ();
strftime (timebuf, StringBuffer::StaticBufferSize, "%Y-%m-%d %H:%M:%S", &timeinfo);
2019-07-27 17:36:24 +03:00
LogFile lf (filename_);
lf.print (strings.format ("%s (%s): %s\n", timebuf, level, msg));
2019-07-27 17:36:24 +03:00
}
public:
2020-06-12 18:52:38 +03:00
template <typename ...Args> void fatal (const char *fmt, Args &&...args) {
2019-07-27 17:36:24 +03:00
auto msg = strings.format (fmt, cr::forward <Args> (args)...);
logToFile ("FATAL", msg);
2020-06-12 18:52:38 +03:00
if (printFun_) {
printFun_ (msg);
2019-07-27 17:36:24 +03:00
}
plat.abort (msg);
}
2020-06-12 18:52:38 +03:00
template <typename ...Args> void error (const char *fmt, Args &&...args) {
2019-07-27 17:36:24 +03:00
auto msg = strings.format (fmt, cr::forward <Args> (args)...);
logToFile ("ERROR", msg);
2020-06-12 18:52:38 +03:00
if (printFun_) {
printFun_ (msg);
2019-07-27 17:36:24 +03:00
}
}
2020-06-12 18:52:38 +03:00
template <typename ...Args> void message (const char *fmt, Args &&...args) {
2019-07-27 17:36:24 +03:00
auto msg = strings.format (fmt, cr::forward <Args> (args)...);
logToFile ("INFO", msg);
2020-06-12 18:52:38 +03:00
if (printFun_) {
printFun_ (msg);
2019-07-27 17:36:24 +03:00
}
}
public:
2020-06-12 18:52:38 +03:00
void initialize (StringRef filename, PrintFunction printFunction) {
printFun_ = cr::move (printFunction);
filename_ = filename;
2019-07-27 17:36:24 +03:00
}
};
// expose global instance
CR_EXPOSE_GLOBAL_SINGLETON (SimpleLogger, logger);
2019-07-27 17:36:24 +03:00
CR_NAMESPACE_END