Skip to content

Commit

Permalink
feat: add cout&cerr redirector
Browse files Browse the repository at this point in the history
  • Loading branch information
OEOTYAN committed Oct 28, 2023
1 parent d82dfc1 commit 8e46cbd
Show file tree
Hide file tree
Showing 17 changed files with 224 additions and 139 deletions.
2 changes: 0 additions & 2 deletions src/ll/api/Logger.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
using namespace ll::StringUtils;

namespace ll {
std::mutex logger_mutex;

bool checkLogLevel(int level, int outLevel) {
if (level >= outLevel) return true;
Expand All @@ -21,7 +20,6 @@ bool checkLogLevel(int level, int outLevel) {
}

void Logger::OutputStream::print(std::string_view s) const {
std::lock_guard lock(logger_mutex);
try {
using Clock = std::chrono::system_clock;
auto time = fmt::localtime(Clock::to_time_t(Clock::now()));
Expand Down
9 changes: 0 additions & 9 deletions src/ll/api/base/Global.h
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,6 @@
#include "ll/api/base/Macro.h"
#include "mc/_HeaderOutputPredefine.h"

#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif

#ifndef NOMINMAX
#define NOMINMAX
#endif


// windows types
#include "minwindef.h"

Expand Down
6 changes: 2 additions & 4 deletions src/ll/api/command/DynamicCommand.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -303,22 +303,20 @@ std::string DynamicCommand::Result::toDebugString() const {
getRaw<std::string>()
);
case ParameterType::BlockPos:
// TODO use CompoundTag::toSNBT, not toString
return fmt::format(
"name: {:15s}, type: {:15s}, isSet: {:5}, value: {}",
name,
typeName,
isSet,
getRaw<CommandPosition>().serialize().toString()
getRaw<CommandPosition>().serialize().toSnbt()
);
case ParameterType::Vec3:
// TODO use CompoundTag::toSNBT, not toString
return fmt::format(
"name: {:15s}, type: {:15s}, isSet: {:5}, value: {}",
name,
typeName,
isSet,
getRaw<CommandPositionFloat>().serialize().toString()
getRaw<CommandPositionFloat>().serialize().toSnbt()
);
case ParameterType::RawText:
return fmt::format(
Expand Down
3 changes: 0 additions & 3 deletions src/ll/api/utils/PluginOwnData.cpp
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
#include "ll/api/utils/PluginOwnData.h"

#include "minwindef.h"
#include <string_view>

std::unordered_map<HMODULE, std::unordered_map<std::string, void*>> ll_PluginOwnData;
1 change: 0 additions & 1 deletion src/ll/api/utils/PluginOwnData.h
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@

#include "WinHelper.h"
#include "ll/api/base/Global.h"
#include "minwindef.h"
#include <string_view>
#include <unordered_map>

Expand Down
17 changes: 3 additions & 14 deletions src/ll/api/utils/SehTranslator.h
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,6 @@
/*
* @brief This file is a simple header-only SEH-Exception convert helper with minwindef
*/
#ifndef _AMD64_
#define _AMD64_
#endif

#ifdef SEH_TRANS_INFO_STRUCT
#include "minwindef.h"
#define SEH_EXP_INFO_POINTER struct _EXCEPTION_POINTERS*
#else
#define SEH_EXP_INFO_POINTER void*
#endif

#include <exception>

#pragma comment(lib, "ntdll")
Expand Down Expand Up @@ -47,9 +36,9 @@ class seh_exception : std::exception {
public:
const uint _expCode = 0;
char const* _expMsg = nullptr;
const SEH_EXP_INFO_POINTER _expInfo = nullptr;
const void* _expInfo = nullptr;

seh_exception(uint ExpCode, SEH_EXP_INFO_POINTER ExpInfo) : _expCode(ExpCode), _expInfo(ExpInfo) {}
seh_exception(uint ExpCode, void* ExpInfo) : _expCode(ExpCode), _expInfo(ExpInfo) {}

~seh_exception() override {
if (_expMsg) {
Expand All @@ -76,7 +65,7 @@ class seh_exception : std::exception {
return "SEH_UNKNOW_ERROR";
}

[[nodiscard]] const SEH_EXP_INFO_POINTER info() const { return _expInfo; }
[[nodiscard]] const void* info() const { return _expInfo; }

[[nodiscard]] uint code() const { return _expCode; }

Expand Down
3 changes: 1 addition & 2 deletions src/ll/core/Config.h
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
#include <thread>

#include "ll/api/LLAPI.h"
#include "nlohmann/json.hpp"

/////////////////////// LL Configs ///////////////////////

Expand Down Expand Up @@ -57,7 +56,7 @@ struct LLConfig {
bool checkRunningBDS = true;
bool simpleServerLogger = true;

std::map<std::string, std::string> resourcePackEncryptionMap = {
std::unordered_map<std::string, std::string> resourcePackEncryptionMap = {
{"<UUID>", "<KEY>"}
};

Expand Down
3 changes: 1 addition & 2 deletions src/ll/core/LeviLamina.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -344,9 +344,8 @@ void leviLaminaMain() {
// bstats::registerBStats();
}

using namespace ll::memory;

LL_AUTO_STATIC_HOOK(LeviLaminaMainHook, HookPriority::Normal, "main", int, int argc, char* argv[]) {
LL_AUTO_STATIC_HOOK(LeviLaminaMainHook, HookPriority::Highest, "main", int, int argc, char* argv[]) {

SeverStartBeginTime = std::chrono::steady_clock::now();

Expand Down
23 changes: 23 additions & 0 deletions src/ll/core/tweak/ModifyInfomation.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@

#include "mc/deps/core/common/debug/LogDetails.h"

#include "ll/core/tweak/OutputRedirector.h"

ll::Logger serverLogger("Server");

static std::unordered_map<uint, decltype(serverLogger.debug)&> loggerMap = {
Expand Down Expand Up @@ -76,6 +78,27 @@ LL_AUTO_STATIC_HOOK(
}
}

LL_AUTO_STATIC_HOOK(CppOutputRedirectHook, HookPriority::High, "main", int, int argc, char* argv[]) {

ll::Logger coutlogger("std::cout");
ll::Logger cerrlogger("std::cerr");

ll::redirect::ofuncstream coutfs{[&](std::string_view s) {
if (s.ends_with("\n")) { s.remove_suffix(1); }
if (s.empty()) { return; }
coutlogger.warn(s);
}};
ll::redirect::ofuncstream cerrfs{[&](std::string_view s) {
if (s.ends_with("\n")) { s.remove_suffix(1); }
if (s.empty()) { return; }
cerrlogger.error(s);
}};
ll::redirect::StreamRedirector coutsr(std::cout, coutfs.rdbuf());
ll::redirect::StreamRedirector cerrsr(std::cerr, cerrfs.rdbuf());

return origin(argc, argv);
}


// Block BDS from adding LOG metadata

Expand Down
58 changes: 58 additions & 0 deletions src/ll/core/tweak/OutputRedirector.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
#include <functional>
#include <iostream>
#include <utility>

namespace ll::redirect {
struct StreamRedirector {
StreamRedirector(const StreamRedirector&) = delete;
StreamRedirector& operator=(const StreamRedirector&) = delete;

StreamRedirector(std::ostream& stream, std::streambuf* rdbuf) : stream(stream), rdbuf_old(stream.rdbuf()) {
stream.set_rdbuf(rdbuf);
}

~StreamRedirector() { stream.set_rdbuf(rdbuf_old); }

private:
std::ostream& stream;
std::streambuf* rdbuf_old;
};

struct functionbuf : public std::streambuf {

explicit functionbuf(std::function<void(std::string_view)> function) : function(std::move(function)) {
setp(buffer, buffer + sizeof(buffer) - 1);
}

private:
char buffer[1024]{};
std::function<void(std::string_view)> function;

int_type overflow(int_type c) override {
if (!traits_type::eq_int_type(c, traits_type::eof())) {
*this->pptr() = traits_type::to_char_type(c);
pbump(1);
}

return sync() ? traits_type::not_eof(c) : traits_type::eof();
}

int_type sync() override {
if (pbase() != pptr()) {
function(std::string_view(pbase(), pptr()));

setp(pbase(), epptr());
}

return 0;
}
};

struct ofuncstream : private virtual functionbuf, public std::ostream {
explicit ofuncstream(const std::function<void(std::string_view)>& function)
: functionbuf(function),
std::ostream(static_cast<std::streambuf*>(this)) {
setf(std::ios_base::unitbuf);
}
};
} // namespace ll::redirect
3 changes: 3 additions & 0 deletions src/ll/test/ConfigTest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -69,4 +69,7 @@ LL_AUTO_TYPED_INSTANCE_HOOK(

ll::logger.debug("{} for load config", ll::config::loadConfig(helloReflection, "plugins/Test/testconfig.json"));
ll::logger.debug("\n{}", ll::reflection::serialize<nlohmann::ordered_json>(helloReflection).dump(4));

ll::logger.debug("789\xDB\xFE");
ll::logger.debug("789\xDB\xFE");
}
15 changes: 8 additions & 7 deletions src/ll/test/ScheduleTest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,6 @@
#include "mc/world/events/ServerInstanceEventCoordinator.h"

using namespace ll::schedule;
namespace {
ll::Logger logger("Schedule");
}

SystemTimeScheduler s;
GameTickScheduler s2;
Expand All @@ -24,18 +21,22 @@ LL_AUTO_TYPED_INSTANCE_HOOK(
) {

s.add<RepeatTask>(100_tick, [&] {
logger.debug("hi, 100_tick life {}", ll::gamechrono::GameTimeClock::now().time_since_epoch());
std::cout << fmt::format("hi, 100_tick life {}", ll::gamechrono::GameTimeClock::now().time_since_epoch())
<< std::endl;
});

s2.add<DelayTask>(1_tick, [&] {
logger.debug("try GameTime {}", ll::gamechrono::GameTimeClock::now().time_since_epoch());
std::cout << fmt::format("try GameTime {}", ll::gamechrono::GameTimeClock::now().time_since_epoch())
<< std::endl;
s3.add<RepeatTask>(100_tick, [&] {
logger.debug("hi, 100_tick gt {}", ll::gamechrono::GameTimeClock::now().time_since_epoch());
std::cout << fmt::format("hi, 100_tick gt {}", ll::gamechrono::GameTimeClock::now().time_since_epoch())
<< std::endl;
});
});

s2.add<RepeatTask>(100_tick, [&] {
logger.debug("hi, 100_tick game {}", ll::gamechrono::GameTimeClock::now().time_since_epoch());
std::cout << fmt::format("hi, 100_tick game {}", ll::gamechrono::GameTimeClock::now().time_since_epoch())
<< std::endl;
});

return origin(ins);
Expand Down
74 changes: 37 additions & 37 deletions src/ll/test/TestNbt.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -49,56 +49,56 @@ LL_AUTO_TYPED_INSTANCE_HOOK(
auto nbt2 = *CompoundTag::fromSnbt(R"(
{
"byte": 127b,
"bytearray": [B;1b, 2b, 3b, 4b, 5b, -2b, -3b, -6b],
"compound": {
"sdouble": 1.0 /*d*/,
"double": 0.3D,
"float": 0.1f,
"long": 10000l
byte = 127b,
bytearray = [B;1b, 2b, 3b, 4b, 5b, -2b, -3b, -6b],
compound = {
sdouble = 1.0 /*d*/,
double = 0.3D,
float = 0.1f,
long = 10000l
},
"hello": {
"Nzg52/4=" /*BASE64*/: {
"ሴ56": "XG5cdFxyXGJcdTEyMzRcdWZmZmZmZmZm2/4=" /*BASE64*/ // hellow
hello = {
"Nzg52/4=" /*BASE64*/= {
'ሴ56' = "XG5cdFxyXGJcdTEyMzRcdWZmZmZmZmZm2/4=" /*BASE64*/ // hellow
}
},
"intarray": [I;1, 2, 3, 4, 5, -2, -3, -6],
"list": [5b, 1b, 0b, -2b],
"num": 1,
"nums": 3s,
"some": {
"new": {
"compound": {
"byte": 127b,
"bytearray": [B;1b, 2b, 3b, 4b, 5b, -2b, -3b, -6b], // orld /**/ /* 34t */
"compound": {
"sdouble": 1.0 /*d*/,
"double": 0.3D,
"float": 0.1f,
"long": 10000l
},
"intarray": [ /*I;*/1,2,3,4,5,-2,-3,-6],
"list": [
5 /*b*/,
1 /*b*/,
intarray = [I;1, 2, 3, 4, 5, -2, -3, -6],
list = [5b, 1b, 0b, -2b],
num = 1,
nums = 3s, # teabawwb 4atg @zg5y
some = {
new = { ; hi
compound = {
"byte" = 127b
"bytearray" = [B;1b, 2b, 3b, 4b, 5b, -2b, -3b, -6b], // orld /**/ /* 34t */
"compound" = {
"sdouble" = 1.0 /*d*/
"double" = 0.3D
"float" = 0.1f
"long" = 10000l
}
"intarray": [ /*I;*/1,2,3,4,5,-2,-3,-6]
list = [
5 /*b*/
1 /*b*/
0 /*b*/,
-2 /*b*/
],
"num": 1,
"nums": 3s,
"string?": "streee _ _o-ix 我超, utf8 \"\\asfa%\"*)##q)$\\\\\"\\Q34\\\\\"\"'':"
-2 /*b*/,
]
"num": 1
"nums": 3s
"string?": "streee _ _o-ix 我超, utf8 \"\\asfa%\"*)##q)$\\\\\"\\Q34\\\\\"\"'':",
}
}
},
}
"string?": "streee _ _o-ix 我超, utf8 \"\\asfa%\"*)##q)$\\\\\"\\Q34\\\\\"\"'':"
}
)");


ll::logger.debug("\n{}", nbt.toSnbt(SnbtFormat::PrettyConsolePrint));
ll::logger.debug("\n{}", nbt.toSnbt(SnbtFormat::Colored | SnbtFormat::Console | SnbtFormat::Jsonify));

ll::logger.debug("\n{}", nbt2.toSnbt(SnbtFormat::Colored | SnbtFormat::Console | SnbtFormat::Jsonify));
ll::logger.debug("\n{}", nbt2.toSnbt(SnbtFormat::PrettyConsolePrint));

ll::logger.debug(
"\n{}",
Expand Down
Loading

0 comments on commit 8e46cbd

Please sign in to comment.