Skip to content

Commit

Permalink
improve
Browse files Browse the repository at this point in the history
  • Loading branch information
beats-dh committed Aug 22, 2024
1 parent 5418917 commit 70095d7
Show file tree
Hide file tree
Showing 17 changed files with 213 additions and 237 deletions.
1 change: 1 addition & 0 deletions cmake/modules/BaseConfig.cmake
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ endif(OPTIONS_ENABLE_OPENMP)
# cmake -DDEBUG_LOG=ON ..
if(DEBUG_LOG)
add_definitions(-DDEBUG_LOG=ON)
add_definitions(-DSPDLOG_ACTIVE_LEVEL=SPDLOG_LEVEL_TRACE)
log_option_enabled("DEBUG LOG")
else()
log_option_disabled("DEBUG LOG")
Expand Down
3 changes: 2 additions & 1 deletion config.lua.dist
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ coreDirectory = "data"
-- Set log level
-- It can be trace, debug, info, warning, error, critical, off (default: info).
-- NOTE: Will only display logs with level higher or equal the one set.
-- NOTE: Debug and trace logs are only available if compiled in debug mode.
logLevel = "info"

--- Toggles the server's maintenance mode.
Expand Down Expand Up @@ -52,7 +53,7 @@ cleanProtectionZones = false
-- Connection Config
-- NOTE: allowOldProtocol can allow login on 10x protocol. (11.00)
-- NOTE: maxPlayers set to 0 means no limit
-- NOTE: MaxPacketsPerSeconds if you change you will be subject to bugs by WPE, keep the default value of 25,
-- NOTE: MaxPacketsPerSeconds if you change you will be subject to bugs by WPE, keep the default value of 25,
-- It's recommended to use a range like min 50 in this function, otherwise you will be disconnected after equipping two-handed distance weapons.
ip = "127.0.0.1"
allowOldProtocol = false
Expand Down
1 change: 0 additions & 1 deletion src/account/account.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
#include "utils/definitions.hpp"
#include "security/argon.hpp"
#include "utils/tools.hpp"
#include "lib/logging/log_with_spd_log.hpp"

#include "enums/account_type.hpp"
#include "enums/account_coins.hpp"
Expand Down
2 changes: 1 addition & 1 deletion src/canary_server.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,7 @@ void CanaryServer::logInfos() {
logger.info("{} - Version {}", ProtocolStatus::SERVER_NAME, SERVER_RELEASE_VERSION);
#endif

logger.debug("Compiled with {}, on {} {}, for platform {}\n", getCompiler(), __DATE__, __TIME__, getPlatform());
logger.debug("Compiled with {}, on {} {}, for platform {}", getCompiler(), __DATE__, __TIME__, getPlatform());

#if defined(LUAJIT_VERSION)
logger.debug("Linked with {} for Lua support", LUAJIT_VERSION);
Expand Down
2 changes: 0 additions & 2 deletions src/config/configmanager.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,7 @@ bool ConfigManager::load() {
return false;
}

#ifndef DEBUG_LOG
g_logger().setLevel(loadStringConfig(L, LOGLEVEL, "logLevel", "info"));
#endif

// Parse config
// Info that must be loaded one time (unless we reset the modules involved)
Expand Down
2 changes: 1 addition & 1 deletion src/database/database.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
#pragma once

#include "declarations.hpp"
#include "lib/logging/log_with_spd_log.hpp"
#include "lib/logging/logger.hpp"

#ifndef USE_PRECOMPILED_HEADERS
#include <mysql/mysql.h>
Expand Down
1 change: 0 additions & 1 deletion src/game/scheduling/task.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@

#include "task.hpp"

#include "lib/logging/log_with_spd_log.hpp"
#include "lib/metrics/metrics.hpp"

std::atomic_uint_fast64_t Task::LAST_EVENT_ID = 0;
Expand Down
2 changes: 1 addition & 1 deletion src/lib/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
target_sources(${PROJECT_NAME}_lib PRIVATE
di/soft_singleton.cpp
logging/log_with_spd_log.cpp
logging/logger.cpp
thread/thread_pool.cpp
)

Expand Down
4 changes: 2 additions & 2 deletions src/lib/di/container.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

#include "account/account_repository_db.hpp"
#include "lib/di/injector.hpp"
#include "lib/logging/log_with_spd_log.hpp"
#include "lib/logging/logger.hpp"
#include "kv/kv_sql.hpp"

namespace di = boost::di;
Expand All @@ -21,7 +21,7 @@ class DI final {
const inline static auto defaultContainer = di::make_injector(
di::bind<AccountRepository>().to<AccountRepositoryDB>().in(di::singleton),
di::bind<KVStore>().to<KVSQL>().in(di::singleton),
di::bind<Logger>().to<LogWithSpdLog>().in(di::singleton)
di::bind<Logger>().to<Logger>().in(di::singleton)
);

public:
Expand Down
2 changes: 1 addition & 1 deletion src/lib/di/soft_singleton.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
#pragma once

#include <iostream>
#include "lib/logging/log_with_spd_log.hpp"
#include "lib/logging/logger.hpp"

class SoftSingleton {
public:
Expand Down
93 changes: 0 additions & 93 deletions src/lib/logging/log_with_spd_log.cpp
Original file line number Diff line number Diff line change
@@ -1,93 +0,0 @@
/**
* Canary - A free and open-source MMORPG server emulator
* Copyright (©) 2019-2024 OpenTibiaBR <[email protected]>
* Repository: https://github.com/opentibiabr/canary
* License: https://github.com/opentibiabr/canary/blob/main/LICENSE
* Contributors: https://github.com/opentibiabr/canary/graphs/contributors
* Website: https://docs.opentibiabr.com/
*/

#include <spdlog/spdlog.h>
#include <spdlog/sinks/basic_file_sink.h>
#include <spdlog/sinks/stdout_color_sinks.h>

#include "pch.hpp"
#include "lib/di/container.hpp"

LogWithSpdLog::LogWithSpdLog() {
setLevel("info");

#ifdef DEBUG_LOG
spdlog::set_pattern("[%Y-%m-%d %H:%M:%S.%e] [thread %t] [%^%l%$] %v ");
#else
spdlog::set_pattern("[%Y-%m-%d %H:%M:%S.%e] [%^%l%$] %v ");
#endif

const std::tm local_tm = get_local_time();

std::ostringstream oss;
oss << std::put_time(&local_tm, "%Y-%m-%d_%H-%M-%S");
std::string filename = "log/server_log_" + oss.str() + ".txt";

try {
auto console_sink = std::make_shared<spdlog::sinks::stdout_color_sink_mt>();
auto file_sink = std::make_shared<spdlog::sinks::basic_file_sink_mt>(filename, true);

const auto combined_logger = std::make_shared<spdlog::logger>(
"",
spdlog::sinks_init_list { console_sink, file_sink }
);

combined_logger->set_level(spdlog::get_level());
combined_logger->flush_on(spdlog::level::info);

set_default_logger(combined_logger);

spdlog::info("Logger initialized and configured for console and file output.");
} catch (const spdlog::spdlog_ex &ex) {
std::cerr << "Log initialization failed: " << ex.what() << std::endl;
}
}

Logger &LogWithSpdLog::getInstance() {
return inject<Logger>();
}

void LogWithSpdLog::setLevel(const std::string &name) {
debug("Setting log level to: {}.", name);
const auto level = spdlog::level::from_str(name);
spdlog::set_level(level);
}

std::string LogWithSpdLog::getLevel() const {
const auto level = spdlog::level::to_string_view(spdlog::get_level());
return std::string { level.begin(), level.end() };
}

void LogWithSpdLog::log(const std::string &lvl, const fmt::basic_string_view<char> msg) const {
spdlog::log(spdlog::level::from_str(lvl), msg);
}

bool LogWithSpdLog::shouldLog(const std::string &lvl) const {
const auto currentLevel = spdlog::get_level();
const auto messageLevel = spdlog::level::from_str(lvl);
return messageLevel >= currentLevel;
}

void LogWithSpdLog::logProfile(const std::string &name, double duration_ms) const {
std::string filename = "log/profile_log-" + name + ".txt";

const auto it = profile_loggers_.find(filename);
if (it == profile_loggers_.end()) {
try {
auto file_sink = std::make_shared<spdlog::sinks::basic_file_sink_mt>(filename, true);
auto profile_logger = std::make_shared<spdlog::logger>("profile_logger_" + name, file_sink);
profile_loggers_[filename] = profile_logger;
profile_logger->info("Function {} executed in {} ms", name, duration_ms);
} catch (const spdlog::spdlog_ex &ex) {
std::cerr << "Profile log initialization failed: " << ex.what() << std::endl;
}
} else {
it->second->info("Function {} executed in {} ms", name, duration_ms);
}
}
36 changes: 0 additions & 36 deletions src/lib/logging/log_with_spd_log.hpp
Original file line number Diff line number Diff line change
@@ -1,36 +0,0 @@
/**
* Canary - A free and open-source MMORPG server emulator
* Copyright (©) 2019-2024 OpenTibiaBR <[email protected]>
* Repository: https://github.com/opentibiabr/canary
* License: https://github.com/opentibiabr/canary/blob/main/LICENSE
* Contributors: https://github.com/opentibiabr/canary/graphs/contributors
* Website: https://docs.opentibiabr.com/
*/
#pragma once

#include "lib/logging/logger.hpp"

namespace spdlog {
class logger; // Forward declaration
}

class LogWithSpdLog final : public Logger {
public:
LogWithSpdLog();
~LogWithSpdLog() override = default;

static Logger &getInstance();

void setLevel(const std::string &name) override;
std::string getLevel() const override;
bool shouldLog(const std::string &lvl) const override;
void logProfile(const std::string &name, double duration_ms) const override;
void setupLogger() const;

void log(const std::string &lvl, fmt::basic_string_view<char> msg) const override;

private:
mutable std::unordered_map<std::string, std::shared_ptr<spdlog::logger>> profile_loggers_;
};

constexpr auto g_logger = LogWithSpdLog::getInstance;
147 changes: 147 additions & 0 deletions src/lib/logging/logger.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
/**
* Canary - A free and open-source MMORPG server emulator
* Copyright (©) 2019-2024 OpenTibiaBR <[email protected]>
* Repository: https://github.com/opentibiabr/canary
* License: https://github.com/opentibiabr/canary/blob/main/LICENSE
* Contributors: https://github.com/opentibiabr/canary/graphs/contributors
* Website: https://docs.opentibiabr.com/
*/

#include <spdlog/spdlog.h>

Check warning on line 10 in src/lib/logging/logger.cpp

View workflow job for this annotation

GitHub Actions / Qodana for C/C++

restrict-system-libc-headers

system include spdlog/spdlog.h not allowed
#include <spdlog/sinks/basic_file_sink.h>

Check warning on line 11 in src/lib/logging/logger.cpp

View workflow job for this annotation

GitHub Actions / Qodana for C/C++

restrict-system-libc-headers

system include spdlog/sinks/basic_file_sink.h not allowed
#include <spdlog/sinks/stdout_color_sinks.h>

Check warning on line 12 in src/lib/logging/logger.cpp

View workflow job for this annotation

GitHub Actions / Qodana for C/C++

restrict-system-libc-headers

system include spdlog/sinks/stdout_color_sinks.h not allowed

#include "pch.hpp"
#include "lib/di/container.hpp"

Logger::Logger() {
spdlog::set_pattern("[%Y-%d-%m %H:%M:%S.%e] [%^%l%$] %v ");

#ifdef DEBUG_LOG
spdlog::set_level(spdlog::level::trace);
spdlog::set_pattern("[%Y-%d-%m %H:%M:%S.%e] [thread %t] [%^%l%$] %v ");
#endif

const std::tm local_tm = get_local_time();

std::ostringstream oss;
oss << std::put_time(&local_tm, "%Y-%m-%d_%H-%M-%S");
std::string filename = "log/server_log_" + oss.str() + ".txt";

try {
// Limpar logs antigos
cleanOldLogs("log", 2);

auto console_sink = std::make_shared<spdlog::sinks::stdout_color_sink_mt>();
auto file_sink = std::make_shared<spdlog::sinks::basic_file_sink_mt>(filename, true);

const auto combined_logger = std::make_shared<spdlog::logger>(
"",
spdlog::sinks_init_list { console_sink, file_sink }
);

combined_logger->set_level(spdlog::get_level());

combined_logger->set_pattern("[%Y-%d-%m %H:%M:%S.%e] [%^%l%$] %v ");

#ifdef DEBUG_LOG
combined_logger->set_pattern("[%Y-%d-%m %H:%M:%S.%e] [thread %t] [%^%l%$] %v ");
#endif

combined_logger->flush_on(spdlog::level::info);

set_default_logger(combined_logger);

info("Logger initialized and configured for console and file output.");
} catch (const spdlog::spdlog_ex &ex) {
std::cerr << "Log initialization failed: " << ex.what() << std::endl;

Check warning on line 57 in src/lib/logging/logger.cpp

View workflow job for this annotation

GitHub Actions / Qodana for C/C++

avoid-endl

do not use 'std::endl' with streams; use '\n' instead
}
}

Logger &Logger::getInstance() {
return inject<Logger>();
}

void Logger::setLevel(const std::string &name) const {
debug("Setting log level to: {}.", name);
const auto level = spdlog::level::from_str(name);
spdlog::set_level(level);
}

std::string Logger::getLevel() const {

Check warning on line 71 in src/lib/logging/logger.cpp

View workflow job for this annotation

GitHub Actions / Qodana for C/C++

convert-member-functions-to-static

method 'getLevel' can be made static
const auto level = spdlog::level::to_string_view(spdlog::get_level());
return std::string { level.begin(), level.end() };
}

void Logger::logProfile(const std::string& name, double duration_ms) const {
std::string mutable_name = name;

std::ranges::replace(mutable_name, ':', '_');
std::ranges::replace(mutable_name, '\\', '_');
std::ranges::replace(mutable_name, '/', '_');

std::string filename = "log/profile_log-" + mutable_name + ".txt";

const auto it = profile_loggers_.find(filename);
if (it == profile_loggers_.end()) {
try {
auto file_sink = std::make_shared<spdlog::sinks::basic_file_sink_mt>(filename, true);
const auto profile_logger = std::make_shared<spdlog::logger>(mutable_name, file_sink);
profile_loggers_[filename] = profile_logger;
profile_logger->info("Function {} executed in {} ms", name, duration_ms);
} catch (const spdlog::spdlog_ex& ex) {
error("Profile log initialization failed: {}", ex.what());
}
} else {
it->second->info("Function {} executed in {} ms", mutable_name, duration_ms);
}
}


// Função para limpar logs antigos
void Logger::cleanOldLogs(const std::string &logDirectory, int days) const {
namespace fs = std::filesystem;

const auto days_duration = std::chrono::hours(days * 24);

for (const auto &entry : fs::directory_iterator(logDirectory)) {

Check warning on line 107 in src/lib/logging/logger.cpp

View workflow job for this annotation

GitHub Actions / Qodana for C/C++

unroll-loops

kernel performance could be improved by unrolling this loop with a '#pragma unroll' directive
if (entry.is_regular_file()) {
auto ftime = fs::last_write_time(entry);

if (decltype(ftime)::clock::now() - ftime > days_duration) {

Check warning on line 111 in src/lib/logging/logger.cpp

View workflow job for this annotation

GitHub Actions / Qodana for C/C++

misra-cpp2008-4-10-2

MISRA 4-10-2: Literal zero (0) shall not be used as the null-pointer-constant
try {
fs::remove(entry.path());

Check warning on line 113 in src/lib/logging/logger.cpp

View workflow job for this annotation

GitHub Actions / Qodana for C/C++

misra-cpp2008-0-1-7

MISRA 0-1-7: The value returned by a function having non-void return type that is not an overloaded operator shall always be used
debug("Deleted old log file: {}", entry.path().string());
} catch (const std::exception &e) {
debug("Failed to delete old log file: {}", entry.path().string());
}
}
}
}
}

void Logger::info(const std::string &msg) const {

Check warning on line 123 in src/lib/logging/logger.cpp

View workflow job for this annotation

GitHub Actions / Qodana for C/C++

convert-member-functions-to-static

method 'info' can be made static
SPDLOG_INFO(msg);
}

void Logger::warn(const std::string &msg) const {

Check warning on line 127 in src/lib/logging/logger.cpp

View workflow job for this annotation

GitHub Actions / Qodana for C/C++

convert-member-functions-to-static

method 'warn' can be made static
SPDLOG_WARN(msg);
}

void Logger::error(const std::string &msg) const {

Check warning on line 131 in src/lib/logging/logger.cpp

View workflow job for this annotation

GitHub Actions / Qodana for C/C++

convert-member-functions-to-static

method 'error' can be made static
SPDLOG_WARN(msg);
}

void Logger::critical(const std::string &msg) const {

Check warning on line 135 in src/lib/logging/logger.cpp

View workflow job for this annotation

GitHub Actions / Qodana for C/C++

convert-member-functions-to-static

method 'critical' can be made static
SPDLOG_WARN(msg);
}

#if defined(DEBUG_LOG)
void Logger::debug(const std::string &msg) const {

Check warning on line 140 in src/lib/logging/logger.cpp

View workflow job for this annotation

GitHub Actions / Qodana for C/C++

convert-member-functions-to-static

method 'debug' can be made static
SPDLOG_DEBUG(msg);
}

void Logger::trace(const std::string &msg) const {

Check warning on line 144 in src/lib/logging/logger.cpp

View workflow job for this annotation

GitHub Actions / Qodana for C/C++

convert-member-functions-to-static

method 'trace' can be made static
SPDLOG_TRACE(msg);
}
#endif
Loading

0 comments on commit 70095d7

Please sign in to comment.