diff options
author | Thorbjørn Lindeijer <bjorn@lindeijer.nl> | 2025-07-04 12:13:01 +0200 |
---|---|---|
committer | Thorbjørn Lindeijer <bjorn@lindeijer.nl> | 2025-07-04 21:17:55 +0200 |
commit | 1debcc8032f01dd2bb64f2725143121b57320876 (patch) | |
tree | 85cba14f5309a487913c0c430811273343211f8f | |
parent | 3fb53be63095dad2ebcfd52d44f13d20f630e478 (diff) | |
download | mana-1debcc8032f01dd2bb64f2725143121b57320876.tar.gz mana-1debcc8032f01dd2bb64f2725143121b57320876.tar.bz2 mana-1debcc8032f01dd2bb64f2725143121b57320876.tar.xz mana-1debcc8032f01dd2bb64f2725143121b57320876.zip |
Added logging priorities and use SDLs logging facilities
By using SDL logging, we can rely on SDL to filter the log messages by
their priority before they get sent to our custom output function. For
example, we now no longer get entries for created and destroyed Window
instances by default, since these have only "debug" priority whereas the
default priority for the "app" category is "info".
We can also get log messages raised by SDL itself in our log now. Log
levels can be controlled per category through the "SDL_LOGGING"
environment variable.
Many existing log messages have been assigned a category based on their
existing prefix.
86 files changed, 615 insertions, 593 deletions
diff --git a/src/actorsprite.cpp b/src/actorsprite.cpp index 7cb46bd4..f31297e9 100644 --- a/src/actorsprite.cpp +++ b/src/actorsprite.cpp @@ -213,7 +213,7 @@ void ActorSprite::loadTargetCursor(const std::string &filename, auto currentImageSet = resman->getImageSet(filename, width, height); if (!currentImageSet) { - logger->log("Error loading target cursor: %s", filename.c_str()); + Log::info("Error loading target cursor: %s", filename.c_str()); return; } diff --git a/src/being.cpp b/src/being.cpp index 46b67f4b..91fe4bc0 100644 --- a/src/being.cpp +++ b/src/being.cpp @@ -481,15 +481,15 @@ void Being::setShowName(bool doShowName) void Being::setGuildName(const std::string &name) { - logger->log("Got guild name \"%s\" for being %s(%i)", name.c_str(), - mName.c_str(), mId); + Log::info("Got guild name \"%s\" for being %s(%i)", name.c_str(), + mName.c_str(), mId); } void Being::setGuildPos(const std::string &pos) { - logger->log("Got guild position \"%s\" for being %s(%i)", pos.c_str(), - mName.c_str(), mId); + Log::info("Got guild position \"%s\" for being %s(%i)", pos.c_str(), + mName.c_str(), mId); } void Being::addGuild(Guild *guild) diff --git a/src/client.cpp b/src/client.cpp index 03fbc184..7c8763a1 100644 --- a/src/client.cpp +++ b/src/client.cpp @@ -29,6 +29,7 @@ #include "game.h" #include "itemshortcut.h" #include "keyboardconfig.h" +#include "log.h" #include "playerrelations.h" #include "sound.h" @@ -96,7 +97,6 @@ LoginData loginData; Config config; /**< Global settings (config.xml) */ Configuration branding; /**< XML branding information reader */ Configuration paths; /**< XML default paths information reader */ -Logger *logger; /**< Log object */ ChatLogger *chatLogger; /**< Chat log object */ KeyboardConfig keyboard; @@ -176,8 +176,6 @@ Client::Client(const Options &options): assert(!mInstance); mInstance = this; - logger = new Logger; - // Set default values for configuration files branding.setDefaultValues(getBrandingDefaults()); paths.setDefaultValues(getPathsDefaults()); @@ -192,19 +190,18 @@ Client::Client(const Options &options): initHomeDir(); initConfiguration(); + // Configure logger + Log::init(); + Log::setLogFile(mLocalDataDir + "/mana.log"); + Log::setLogToStandardOut(config.logToStandardOut); + Log::info("%s", FULL_VERSION); + chatLogger = new ChatLogger; if (options.chatLogDir.empty()) chatLogger->setLogDir(mLocalDataDir + "/logs/"); else chatLogger->setLogDir(options.chatLogDir); - // Configure logger - logger->setLogFile(mLocalDataDir + "/mana.log"); - logger->setLogToStandardOut(config.logToStandardOut); - - // Log the mana version - logger->log("%s", FULL_VERSION); - initScreenshotDir(); #if SDL_VERSION_ATLEAST(2, 24, 0) @@ -212,10 +209,10 @@ Client::Client(const Options &options): #endif // Initialize SDL - logger->log("Initializing SDL..."); + Log::info("Initializing SDL..."); if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER) < 0) { - logger->error(strprintf("Could not initialize SDL: %s", + Log::critical(strprintf("Could not initialize SDL: %s", SDL_GetError())); } atexit(SDL_Quit); @@ -224,7 +221,7 @@ Client::Client(const Options &options): if (!FS::setWriteDir(mLocalDataDir)) { - logger->error(strprintf("%s couldn't be set as write directory! " + Log::critical(strprintf("%s couldn't be set as write directory! " "Exiting.", mLocalDataDir.c_str())); } @@ -287,7 +284,7 @@ Client::Client(const Options &options): iconFile += ".png"; #endif iconFile = ResourceManager::getPath(iconFile); - logger->log("Loading icon from file: %s", iconFile.c_str()); + Log::info("Loading icon from file: %s", iconFile.c_str()); #ifdef _WIN32 static SDL_SysWMinfo pInfo; SDL_GetWindowWMInfo(mVideo.window(), &pInfo); @@ -329,7 +326,7 @@ Client::Client(const Options &options): { mState = STATE_ERROR; errorMessage = err; - logger->log("Warning: %s", err); + Log::warn("%s", err); } // Initialize keyboard @@ -425,15 +422,13 @@ Client::~Client() SDL_FreeSurface(mIcon); - logger->log("Quitting"); + Log::info("Quitting"); delete userPalette; XML::Writer writer(mConfigDir + "/config.xml"); if (writer.isValid()) serialize(writer, config); - delete logger; - mInstance = nullptr; } @@ -499,7 +494,7 @@ int Client::exec() catch (gcn::Exception e) { const char *err = e.getMessage().c_str(); - logger->log("Warning: guichan input exception: %s", err); + Log::warn("Guichan input exception: %s", err); } } @@ -616,7 +611,7 @@ void Client::update() switch (mState) { case STATE_CHOOSE_SERVER: - logger->log("State: CHOOSE SERVER"); + Log::info("State: CHOOSE SERVER"); // Don't allow an alpha opacity // lower than the default value @@ -627,7 +622,7 @@ void Client::update() break; case STATE_CONNECT_SERVER: - logger->log("State: CONNECT SERVER"); + Log::info("State: CONNECT SERVER"); Net::connectToServer(mCurrentServer); @@ -636,7 +631,7 @@ void Client::update() break; case STATE_LOGIN: - logger->log("State: LOGIN"); + Log::info("State: LOGIN"); // Don't allow an alpha opacity // lower than the default value gui->getTheme()->setMinimumOpacity(0.8f); @@ -655,14 +650,14 @@ void Client::update() break; case STATE_LOGIN_ATTEMPT: - logger->log("State: LOGIN ATTEMPT"); + Log::info("State: LOGIN ATTEMPT"); accountLogin(&loginData); mCurrentDialog = new ConnectionDialog( _("Logging in"), STATE_SWITCH_SERVER); break; case STATE_WORLD_SELECT: - logger->log("State: WORLD SELECT"); + Log::info("State: WORLD SELECT"); { Worlds worlds = Net::getLoginHandler()->getWorlds(); @@ -684,13 +679,13 @@ void Client::update() break; case STATE_WORLD_SELECT_ATTEMPT: - logger->log("State: WORLD SELECT ATTEMPT"); + Log::info("State: WORLD SELECT ATTEMPT"); mCurrentDialog = new ConnectionDialog( _("Entering game world"), STATE_WORLD_SELECT); break; case STATE_UPDATE: - logger->log("State: UPDATE"); + Log::info("State: UPDATE"); if (mOptions.skipUpdate) { @@ -705,7 +700,7 @@ void Client::update() break; case STATE_LOAD_DATA: - logger->log("State: LOAD DATA"); + Log::info("State: LOAD DATA"); // If another data path has been set, // we don't load any other files... @@ -752,7 +747,7 @@ void Client::update() break; case STATE_GET_CHARACTERS: - logger->log("State: GET CHARACTERS"); + Log::info("State: GET CHARACTERS"); Net::getCharHandler()->requestCharacters(); mCurrentDialog = new ConnectionDialog( _("Requesting characters"), @@ -760,7 +755,7 @@ void Client::update() break; case STATE_CHAR_SELECT: - logger->log("State: CHAR SELECT"); + Log::info("State: CHAR SELECT"); // Don't allow an alpha opacity // lower than the default value gui->getTheme()->setMinimumOpacity(0.8f); @@ -785,7 +780,7 @@ void Client::update() break; case STATE_CONNECT_GAME: - logger->log("State: CONNECT GAME"); + Log::info("State: CONNECT GAME"); Net::getGameHandler()->connect(); mCurrentDialog = new ConnectionDialog( @@ -795,7 +790,7 @@ void Client::update() break; case STATE_CHANGE_MAP: - logger->log("State: CHANGE_MAP"); + Log::info("State: CHANGE_MAP"); Net::getGameHandler()->connect(); mCurrentDialog = new ConnectionDialog( @@ -804,7 +799,7 @@ void Client::update() break; case STATE_GAME: - logger->log("Memorizing selected character %s", + Log::info("Memorizing selected character %s", local_player->getName().c_str()); config.lastCharacter = local_player->getName(); @@ -822,52 +817,52 @@ void Client::update() mCurrentDialog = nullptr; - logger->log("State: GAME"); + Log::info("State: GAME"); mGame = new Game; break; case STATE_LOGIN_ERROR: - logger->log("State: LOGIN ERROR"); + Log::info("State: LOGIN ERROR"); showErrorDialog(errorMessage, STATE_LOGIN); break; case STATE_ACCOUNTCHANGE_ERROR: - logger->log("State: ACCOUNT CHANGE ERROR"); + Log::info("State: ACCOUNT CHANGE ERROR"); showErrorDialog(errorMessage, STATE_CHAR_SELECT); break; case STATE_REGISTER_PREP: - logger->log("State: REGISTER_PREP"); + Log::info("State: REGISTER_PREP"); Net::getLoginHandler()->getRegistrationDetails(); mCurrentDialog = new ConnectionDialog( _("Requesting registration details"), STATE_LOGIN); break; case STATE_REGISTER: - logger->log("State: REGISTER"); + Log::info("State: REGISTER"); mCurrentDialog = new RegisterDialog(&loginData); break; case STATE_REGISTER_ATTEMPT: - logger->log("Username is %s", loginData.username.c_str()); + Log::info("Username is %s", loginData.username.c_str()); Net::getLoginHandler()->registerAccount(&loginData); loginData.password.clear(); break; case STATE_CHANGEPASSWORD: - logger->log("State: CHANGE PASSWORD"); + Log::info("State: CHANGE PASSWORD"); mCurrentDialog = new ChangePasswordDialog(&loginData); break; case STATE_CHANGEPASSWORD_ATTEMPT: - logger->log("State: CHANGE PASSWORD ATTEMPT"); + Log::info("State: CHANGE PASSWORD ATTEMPT"); Net::getLoginHandler()->changePassword(loginData.username, loginData.password, loginData.newPassword); break; case STATE_CHANGEPASSWORD_SUCCESS: - logger->log("State: CHANGE PASSWORD SUCCESS"); + Log::info("State: CHANGE PASSWORD SUCCESS"); showOkDialog(_("Password Change"), _("Password changed successfully!"), STATE_CHAR_SELECT); @@ -876,35 +871,35 @@ void Client::update() break; case STATE_CHANGEEMAIL: - logger->log("State: CHANGE EMAIL"); + Log::info("State: CHANGE EMAIL"); mCurrentDialog = new ChangeEmailDialog(&loginData); break; case STATE_CHANGEEMAIL_ATTEMPT: - logger->log("State: CHANGE EMAIL ATTEMPT"); + Log::info("State: CHANGE EMAIL ATTEMPT"); Net::getLoginHandler()->changeEmail(loginData.email); break; case STATE_CHANGEEMAIL_SUCCESS: - logger->log("State: CHANGE EMAIL SUCCESS"); + Log::info("State: CHANGE EMAIL SUCCESS"); showOkDialog(_("Email Change"), _("Email changed successfully!"), STATE_CHAR_SELECT); break; case STATE_UNREGISTER: - logger->log("State: UNREGISTER"); + Log::info("State: UNREGISTER"); mCurrentDialog = new UnRegisterDialog(&loginData); break; case STATE_UNREGISTER_ATTEMPT: - logger->log("State: UNREGISTER ATTEMPT"); + Log::info("State: UNREGISTER ATTEMPT"); Net::getLoginHandler()->unregisterAccount( loginData.username, loginData.password); break; case STATE_UNREGISTER_SUCCESS: - logger->log("State: UNREGISTER SUCCESS"); + Log::info("State: UNREGISTER SUCCESS"); Net::getLoginHandler()->disconnect(); showOkDialog(_("Unregister Successful"), @@ -914,7 +909,7 @@ void Client::update() break; case STATE_SWITCH_SERVER: - logger->log("State: SWITCH SERVER"); + Log::info("State: SWITCH SERVER"); Net::getLoginHandler()->disconnect(); Net::getGameHandler()->disconnect(); @@ -924,7 +919,7 @@ void Client::update() break; case STATE_SWITCH_LOGIN: - logger->log("State: SWITCH LOGIN"); + Log::info("State: SWITCH LOGIN"); Net::getLoginHandler()->disconnect(); @@ -932,7 +927,7 @@ void Client::update() break; case STATE_SWITCH_CHARACTER: - logger->log("State: SWITCH CHARACTER"); + Log::info("State: SWITCH CHARACTER"); // Done with game Net::getGameHandler()->disconnect(); @@ -941,26 +936,26 @@ void Client::update() break; case STATE_LOGOUT_ATTEMPT: - logger->log("State: LOGOUT ATTEMPT"); + Log::info("State: LOGOUT ATTEMPT"); // TODO break; case STATE_WAIT: - logger->log("State: WAIT"); + Log::info("State: WAIT"); break; case STATE_EXIT: - logger->log("State: EXIT"); + Log::info("State: EXIT"); break; case STATE_FORCE_QUIT: - logger->log("State: FORCE QUIT"); + Log::info("State: FORCE QUIT"); mState = STATE_EXIT; break; case STATE_ERROR: - logger->log("State: ERROR"); - logger->log("Error: %s", errorMessage.c_str()); + Log::info("State: ERROR"); + Log::error("%s", errorMessage.c_str()); showErrorDialog(errorMessage, STATE_CHOOSE_SERVER); Net::getGameHandler()->disconnect(); break; @@ -1018,7 +1013,7 @@ void Client::initRootDir() Configuration portable; portable.init(portableName); - logger->log("Portable file: %s", portableName.c_str()); + Log::info("Portable file: %s", portableName.c_str()); if (mOptions.localDataDir.empty()) { @@ -1026,8 +1021,8 @@ void Client::initRootDir() if (!dir.empty()) { mOptions.localDataDir = mRootDir + dir; - logger->log("Portable data dir: %s", - mOptions.localDataDir.c_str()); + Log::info("Portable data dir: %s", + mOptions.localDataDir.c_str()); } } @@ -1037,8 +1032,8 @@ void Client::initRootDir() if (!dir.empty()) { mOptions.configDir = mRootDir + dir; - logger->log("Portable config dir: %s", - mOptions.configDir.c_str()); + Log::info("Portable config dir: %s", + mOptions.configDir.c_str()); } } @@ -1048,8 +1043,8 @@ void Client::initRootDir() if (!dir.empty()) { mOptions.screenshotDir = mRootDir + dir; - logger->log("Portable screenshot dir: %s", - mOptions.screenshotDir.c_str()); + Log::info("Portable screenshot dir: %s", + mOptions.screenshotDir.c_str()); } } } @@ -1081,7 +1076,7 @@ void Client::initHomeDir() if (mkdir_r(mLocalDataDir.c_str())) { - logger->error(strprintf(_("%s doesn't exist and can't be created! " + Log::critical(strprintf(_("%s doesn't exist and can't be created! " "Exiting."), mLocalDataDir.c_str())); } @@ -1104,7 +1099,7 @@ void Client::initHomeDir() if (mkdir_r(mConfigDir.c_str())) { - logger->error(strprintf(_("%s doesn't exist and can't be created! " + Log::critical(strprintf(_("%s doesn't exist and can't be created! " "Exiting."), mConfigDir.c_str())); } } @@ -1123,7 +1118,7 @@ void Client::initConfiguration() if (doc.rootNode() && doc.rootNode().name() == "configuration") deserialize(doc.rootNode(), config); else - logger->log("Couldn't read configuration file: %s", configPath.c_str()); + Log::info("Couldn't read configuration file: %s", configPath.c_str()); } /** @@ -1146,7 +1141,7 @@ bool Client::initUpdatesDir() if (mUpdateHost.empty()) { - logger->log("No update host provided"); + Log::info("No update host provided"); mUpdatesDir.clear(); mState = STATE_LOAD_DATA; return false; @@ -1154,8 +1149,8 @@ bool Client::initUpdatesDir() mUpdatesDir = "updates/" + getDirectoryFromURL(mUpdateHost); - logger->log("Update host: %s", mUpdateHost.c_str()); - logger->log("Updates dir: %s", mUpdatesDir.c_str()); + Log::info("Update host: %s", mUpdateHost.c_str()); + Log::info("Updates dir: %s", mUpdatesDir.c_str()); // Verify that the updates directory exists. Create if necessary. if (!FS::isDirectory(mUpdatesDir)) @@ -1175,16 +1170,16 @@ bool Client::initUpdatesDir() if (!CreateDirectory(newDir.c_str(), 0) && GetLastError() != ERROR_ALREADY_EXISTS) { - logger->log("Error: %s can't be made, but doesn't exist!", - newDir.c_str()); + Log::error("%s can't be made, but doesn't exist!", + newDir.c_str()); errorMessage = strprintf(_("Error creating updates directory!\n(%s)"), newDir.c_str()); mState = STATE_ERROR; } #else - logger->log("Error: %s/%s can't be made, but doesn't exist!", - mLocalDataDir.c_str(), mUpdatesDir.c_str()); + Log::error("%s/%s can't be made, but doesn't exist!", + mLocalDataDir.c_str(), mUpdatesDir.c_str()); errorMessage = strprintf(_("Error creating updates directory!\n(%s/%s)"), mLocalDataDir.c_str(), mUpdatesDir.c_str()); @@ -1230,7 +1225,7 @@ void Client::initScreenshotDir() void Client::accountLogin(LoginData *loginData) { - logger->log("Username is %s", loginData->username.c_str()); + Log::info("Username is %s", loginData->username.c_str()); // Send login infos if (loginData->registerLogin) diff --git a/src/configuration.cpp b/src/configuration.cpp index 10398d6f..e220f4c6 100644 --- a/src/configuration.cpp +++ b/src/configuration.cpp @@ -107,9 +107,9 @@ VariableData *Configuration::getDefault(const std::string &key, return itdef->second; } - logger->log("%s: No value in registry for key %s", - mConfigPath.c_str(), - key.c_str()); + Log::info("%s: No value in registry for key %s", + mConfigPath.c_str(), + key.c_str()); } return nullptr; @@ -214,13 +214,13 @@ void Configuration::init(const std::string &filename, bool useResManager) if (!rootNode) { - logger->log("Couldn't open configuration file: %s", filename.c_str()); + Log::info("Couldn't open configuration file: %s", filename.c_str()); return; } if (rootNode.name() != "configuration") { - logger->log("Warning: No configuration file (%s)", filename.c_str()); + Log::warn("No configuration file (%s)", filename.c_str()); return; } diff --git a/src/effectmanager.cpp b/src/effectmanager.cpp index 32280555..d1b3a037 100644 --- a/src/effectmanager.cpp +++ b/src/effectmanager.cpp @@ -38,13 +38,13 @@ EffectManager::EffectManager() // Handle old naming until the 0.5.x versions are obsolete. if (!root || root.name() != "being-effects") { - logger->log("Error loading being effects file: effects.xml"); + Log::info("Error loading being effects file: effects.xml"); return; } } else { - logger->log("Effects are now loading"); + Log::info("Effects are now loading"); } for (auto node : root.children()) @@ -67,7 +67,7 @@ bool EffectManager::trigger(int id, Being *being, int rotation) auto it = mEffects.find(id); if (it == mEffects.end()) { - logger->log("EffectManager::trigger: effect %d not found", id); + Log::warn("EffectManager::trigger: effect %d not found", id); return false; } @@ -90,7 +90,7 @@ bool EffectManager::trigger(int id, int x, int y, int rotation) auto it = mEffects.find(id); if (it == mEffects.end()) { - logger->log("EffectManager::trigger: effect %d not found", id); + Log::warn("EffectManager::trigger: effect %d not found", id); return false; } diff --git a/src/game.cpp b/src/game.cpp index 34104aa7..b91df9db 100644 --- a/src/game.cpp +++ b/src/game.cpp @@ -288,7 +288,7 @@ static bool saveScreenshot() if (!screenshot) { serverNotice(_("Could not take screenshot!")); - logger->log("Error: could not take screenshot."); + Log::error("Could not take screenshot."); return false; } @@ -301,9 +301,9 @@ static bool saveScreenshot() if (mkdir_r(screenshotDirectory.c_str()) != 0) { - logger->log("Directory %s doesn't exist and can't be created! " - "Setting screenshot directory to home.", - screenshotDirectory.c_str()); + Log::info("Directory %s doesn't exist and can't be created! " + "Setting screenshot directory to home.", + screenshotDirectory.c_str()); screenshotDirectory = FS::getUserDir(); } @@ -331,7 +331,7 @@ static bool saveScreenshot() else { serverNotice(_("Saving screenshot failed!")); - logger->log("Error: could not save screenshot."); + Log::error("Could not save screenshot."); } SDL_FreeSurface(screenshot); @@ -873,7 +873,7 @@ void Game::changeMap(const std::string &mapPath) if (!newMap) { - logger->log("Error while loading %s", fullMap.c_str()); + Log::info("Error while loading %s", fullMap.c_str()); new OkDialog(_("Could Not Load Map"), strprintf(_("Error while loading %s"), fullMap.c_str())); } diff --git a/src/gui/abilitieswindow.cpp b/src/gui/abilitieswindow.cpp index 700fa7ff..d8122bf3 100644 --- a/src/gui/abilitieswindow.cpp +++ b/src/gui/abilitieswindow.cpp @@ -145,13 +145,13 @@ void AbilitiesWindow::draw(gcn::Graphics *graphics) void AbilitiesWindow::rebuild(const std::map<int, Ability> &abilityData) { delete_all(mEntries); - + mEntries.clear(); int vPos = 0; //vertical position of next placed element for (auto &[id, ability] : abilityData) { - logger->log("Updating ability GUI for %d", id); + Log::info("Updating ability GUI for %d", id); AbilityInfo *info = AbilityDB::get(id); if (info) @@ -166,7 +166,7 @@ void AbilitiesWindow::rebuild(const std::map<int, Ability> &abilityData) } else { - logger->log("Warning: No info available of ability %d", id); + Log::warn("No info available of ability %d", id); } } } diff --git a/src/gui/changeemaildialog.cpp b/src/gui/changeemaildialog.cpp index ce83087b..e10a0d18 100644 --- a/src/gui/changeemaildialog.cpp +++ b/src/gui/changeemaildialog.cpp @@ -112,8 +112,8 @@ void ChangeEmailDialog::action(const gcn::ActionEvent &event) const std::string username = mLoginData->username.c_str(); const std::string newFirstEmail = mFirstEmailField->getText(); const std::string newSecondEmail = mSecondEmailField->getText(); - logger->log("ChangeEmailDialog::Email change, Username is %s", - username.c_str()); + Log::info("ChangeEmailDialog::Email change, Username is %s", + username.c_str()); std::stringstream errorMessage; int error = 0; diff --git a/src/gui/changepassworddialog.cpp b/src/gui/changepassworddialog.cpp index 437a8c90..91d7721d 100644 --- a/src/gui/changepassworddialog.cpp +++ b/src/gui/changepassworddialog.cpp @@ -94,8 +94,8 @@ void ChangePasswordDialog::action(const gcn::ActionEvent &event) const std::string oldPassword = mOldPassField->getText(); const std::string newFirstPass = mFirstPassField->getText(); const std::string newSecondPass = mSecondPassField->getText(); - logger->log("ChangePasswordDialog::Password change, Username is %s", - username.c_str()); + Log::info("ChangePasswordDialog::Password change, Username is %s", + username.c_str()); std::stringstream errorMessage; int error = 0; diff --git a/src/gui/charselectdialog.cpp b/src/gui/charselectdialog.cpp index 2485be69..1ed353dd 100644 --- a/src/gui/charselectdialog.cpp +++ b/src/gui/charselectdialog.cpp @@ -271,7 +271,7 @@ void CharSelectDialog::setCharacters(const Net::Characters &characters) if (characterSlot >= (int)mCharacterEntries.size()) { - logger->log("Warning: slot out of range: %d", character->slot); + Log::warn("Slot out of range: %d", character->slot); continue; } diff --git a/src/gui/connectiondialog.cpp b/src/gui/connectiondialog.cpp index 2ff68a15..e6435269 100644 --- a/src/gui/connectiondialog.cpp +++ b/src/gui/connectiondialog.cpp @@ -54,7 +54,7 @@ ConnectionDialog::ConnectionDialog(const std::string &text, void ConnectionDialog::action(const gcn::ActionEvent &) { - logger->log("Cancel pressed"); + Log::info("Cancel pressed"); Client::setState(mCancelState); } diff --git a/src/gui/gui.cpp b/src/gui/gui.cpp index 0c3d78eb..361ad0b8 100644 --- a/src/gui/gui.cpp +++ b/src/gui/gui.cpp @@ -71,7 +71,7 @@ Gui::Gui(Graphics *graphics, const std::string &themePath) setTheme(themeIt != mAvailableThemes.end() ? *themeIt : mAvailableThemes.front()); - logger->log("Initializing GUI..."); + Log::info("Initializing GUI..."); // Set graphics setGraphics(graphics); @@ -106,8 +106,8 @@ Gui::Gui(Graphics *graphics, const std::string &themePath) } catch (gcn::Exception e) { - logger->error(std::string("Unable to load '") + fontFile + - std::string("': ") + e.getMessage()); + Log::critical(std::string("Unable to load '") + fontFile + + "': " + e.getMessage()); } // Set bold font @@ -119,8 +119,8 @@ Gui::Gui(Graphics *graphics, const std::string &themePath) } catch (gcn::Exception e) { - logger->error(std::string("Unable to load '") + fontFile + - std::string("': ") + e.getMessage()); + Log::critical(std::string("Unable to load '") + fontFile + + "': " + e.getMessage()); } // Set mono font @@ -132,8 +132,8 @@ Gui::Gui(Graphics *graphics, const std::string &themePath) } catch (gcn::Exception e) { - logger->error(std::string("Unable to load '") + fontFile + - std::string("': ") + e.getMessage()); + Log::critical(std::string("Unable to load '") + fontFile + + "': " + e.getMessage()); } loadCustomCursors(); @@ -288,8 +288,8 @@ void Gui::loadCustomCursors() SDL_Surface *mouseSurface = loadSurface(cursorPath); if (!mouseSurface) { - logger->log("Warning: Unable to load mouse cursor file (%s): %s", - cursorPath.c_str(), SDL_GetError()); + Log::warn("Unable to load mouse cursor file (%s): %s", + cursorPath.c_str(), SDL_GetError()); return; } @@ -329,7 +329,7 @@ void Gui::loadCustomCursors() 17 * mCustomCursorScale); if (!cursor) { - logger->log("Warning: Unable to create cursor: %s", SDL_GetError()); + Log::warn("Unable to create cursor: %s", SDL_GetError()); } mCustomMouseCursors.push_back(cursor); diff --git a/src/gui/helpwindow.cpp b/src/gui/helpwindow.cpp index e0e21610..c7e87a55 100644 --- a/src/gui/helpwindow.cpp +++ b/src/gui/helpwindow.cpp @@ -98,7 +98,7 @@ void HelpWindow::loadFile(const std::string &file) char *fileContents = (char *) FS::loadFile(fileName, contentsLength); if (!fileContents) { - logger->log("Couldn't load text file: %s", fileName.c_str()); + Log::info("Couldn't load text file: %s", fileName.c_str()); return; } diff --git a/src/gui/popupmenu.cpp b/src/gui/popupmenu.cpp index 4bafc074..16b16af9 100644 --- a/src/gui/popupmenu.cpp +++ b/src/gui/popupmenu.cpp @@ -318,7 +318,7 @@ void PopupMenu::handleLink(const std::string &link) // Unknown actions else if (link != "cancel") { - logger->log("PopupMenu: Warning, unknown action '%s'", link.c_str()); + Log::info("PopupMenu: Warning, unknown action '%s'", link.c_str()); } setVisible(false); diff --git a/src/gui/register.cpp b/src/gui/register.cpp index 62114c10..d7924021 100644 --- a/src/gui/register.cpp +++ b/src/gui/register.cpp @@ -147,7 +147,7 @@ void RegisterDialog::action(const gcn::ActionEvent &event) else if (event.getId() == "register" && canSubmit()) { const std::string user = mUserField->getText(); - logger->log("RegisterDialog::register Username is %s", user.c_str()); + Log::info("RegisterDialog::register Username is %s", user.c_str()); std::string errorMessage; int error = 0; diff --git a/src/gui/serverdialog.cpp b/src/gui/serverdialog.cpp index f5418625..8be33733 100644 --- a/src/gui/serverdialog.cpp +++ b/src/gui/serverdialog.cpp @@ -361,7 +361,7 @@ void ServerDialog::logic() case DownloadStatus::Canceled: case DownloadStatus::Error: mDownloadDone = true; - logger->log("Error retrieving server list: %s", mDownload->getError()); + Log::info("Error retrieving server list: %s", mDownload->getError()); mDownloadText->setCaption(_("Error retrieving server list!")); break; @@ -406,15 +406,14 @@ void ServerDialog::loadServers() if (!rootNode || rootNode.name() != "serverlist") { - logger->log("Error loading server list!"); + Log::info("Error loading server list!"); return; } int version = rootNode.getProperty("version", 0); if (version != 1) { - logger->log("Error: unsupported online server list version: %d", - version); + Log::error("Unsupported online server list version: %d", version); return; } @@ -440,8 +439,8 @@ void ServerDialog::loadServer(XML::Node serverNode) #endif ) { - logger->log("Ignoring server entry with unknown type: %s", - type.c_str()); + Log::info("Ignoring server entry with unknown type: %s", + type.c_str()); return; } diff --git a/src/gui/setup_audio.cpp b/src/gui/setup_audio.cpp index 43b132d8..0031f9bc 100644 --- a/src/gui/setup_audio.cpp +++ b/src/gui/setup_audio.cpp @@ -108,7 +108,7 @@ void Setup_Audio::apply() catch (const char *err) { new OkDialog(_("Sound Engine"), err); - logger->log("Warning: %s", err); + Log::warn("%s", err); } } else diff --git a/src/gui/skilldialog.cpp b/src/gui/skilldialog.cpp index 40421daf..3112446a 100644 --- a/src/gui/skilldialog.cpp +++ b/src/gui/skilldialog.cpp @@ -290,7 +290,7 @@ void SkillDialog::loadSkills() if (!root || root.name() != "skills") { - logger->log("Error loading skills file: %s", SKILLS_FILE); + Log::info("Error loading skills file: %s", SKILLS_FILE); if (Net::getNetworkType() == ServerType::TmwAthena) { diff --git a/src/gui/unregisterdialog.cpp b/src/gui/unregisterdialog.cpp index 94f6ef62..2abbebf7 100644 --- a/src/gui/unregisterdialog.cpp +++ b/src/gui/unregisterdialog.cpp @@ -98,8 +98,8 @@ void UnRegisterDialog::action(const gcn::ActionEvent &event) else if (event.getId() == "unregister") { const std::string &password = mPasswordField->getText(); - logger->log("UnregisterDialog::unregistered, Username is %s", - mLoginData->username.c_str()); + Log::info("UnregisterDialog::unregistered, Username is %s", + mLoginData->username.c_str()); std::stringstream errorMessage; bool error = false; diff --git a/src/gui/updaterwindow.cpp b/src/gui/updaterwindow.cpp index 5cfb45cd..bb9523a9 100644 --- a/src/gui/updaterwindow.cpp +++ b/src/gui/updaterwindow.cpp @@ -60,7 +60,7 @@ std::vector<UpdateFile> loadXMLFile(const std::string &fileName) if (!rootNode || rootNode.name() != "updates") { - logger->log("Error loading update file: %s", fileName.c_str()); + Log::info("Error loading update file: %s", fileName.c_str()); return files; } @@ -110,7 +110,7 @@ std::vector<UpdateFile> loadTxtFile(const std::string &fileName) } else { - logger->log("Error loading update file: %s", fileName.c_str()); + Log::info("Error loading update file: %s", fileName.c_str()); } fileHandler.close(); @@ -258,9 +258,9 @@ void UpdaterWindow::loadUpdates() mUpdateFiles = loadXMLFile(mUpdatesDir + "/" + xmlUpdateFile); if (mUpdateFiles.empty()) { - logger->log("Warning this server does not have a" - " %s file falling back to %s", xmlUpdateFile, - txtUpdateFile); + Log::warn("This server does not have a" + " %s file falling back to %s", xmlUpdateFile, + txtUpdateFile); mUpdateFiles = loadTxtFile(mUpdatesDir + "/" + txtUpdateFile); } } @@ -336,9 +336,9 @@ void UpdaterWindow::downloadCompleted() mUpdateFiles = loadXMLFile(mUpdatesDir + "/" + xmlUpdateFile); if (mUpdateFiles.empty()) { - logger->log("Warning this server does not have a %s" - " file falling back to %s", - xmlUpdateFile, txtUpdateFile); + Log::warn("This server does not have a %s" + " file falling back to %s", + xmlUpdateFile, txtUpdateFile); // If the resources.xml file fails, fall back onto a older version mDialogState = DialogState::DownloadList; @@ -383,7 +383,7 @@ void UpdaterWindow::downloadCompleted() else { fclose(file); - logger->log("%s already here", thisFile.name.c_str()); + Log::info("%s already here", thisFile.name.c_str()); } mUpdateIndex++; } diff --git a/src/gui/widgets/desktop.cpp b/src/gui/widgets/desktop.cpp index e424beec..b21c235a 100644 --- a/src/gui/widgets/desktop.cpp +++ b/src/gui/widgets/desktop.cpp @@ -113,6 +113,6 @@ void Desktop::setBestFittingWallpaper() } else { - logger->log("Couldn't load %s as wallpaper", wallpaperName.c_str()); + Log::info("Couldn't load %s as wallpaper", wallpaperName.c_str()); } } diff --git a/src/gui/widgets/popup.cpp b/src/gui/widgets/popup.cpp index b245b9e6..c4c6f652 100644 --- a/src/gui/widgets/popup.cpp +++ b/src/gui/widgets/popup.cpp @@ -40,7 +40,7 @@ Popup::Popup(const std::string &name, SkinType skinType) , mMaxHeight(graphics->getHeight()) , mSkinType(skinType) { - logger->log("Popup::Popup(\"%s\")", name.c_str()); + Log::debug("Popup::Popup(\"%s\")", name.c_str()); if (!windowContainer) throw GCN_EXCEPTION("Popup::Popup(): no windowContainer set"); @@ -58,7 +58,7 @@ Popup::Popup(const std::string &name, SkinType skinType) Popup::~Popup() { - logger->log("Popup::~Popup(\"%s\")", mPopupName.c_str()); + Log::debug("Popup::~Popup(\"%s\")", mPopupName.c_str()); } void Popup::setWindowContainer(WindowContainer *wc) diff --git a/src/gui/widgets/window.cpp b/src/gui/widgets/window.cpp index e57918b7..b05731bd 100644 --- a/src/gui/widgets/window.cpp +++ b/src/gui/widgets/window.cpp @@ -53,7 +53,7 @@ Window::Window(SkinType skinType, const std::string &caption, bool modal, Window , mMaxWinWidth(graphics->getWidth()) , mMaxWinHeight(graphics->getHeight()) { - logger->log("Window::Window(\"%s\")", caption.c_str()); + Log::debug("Window::Window(\"%s\")", caption.c_str()); if (!windowContainer) throw GCN_EXCEPTION("Window::Window(): no windowContainer set"); @@ -82,7 +82,7 @@ Window::Window(SkinType skinType, const std::string &caption, bool modal, Window Window::~Window() { - logger->log("Window::~Window(\"%s\")", getCaption().c_str()); + Log::debug("Window::~Window(\"%s\")", getCaption().c_str()); saveWindowState(); diff --git a/src/inventory.cpp b/src/inventory.cpp index 51eb24e1..e45e094c 100644 --- a/src/inventory.cpp +++ b/src/inventory.cpp @@ -67,7 +67,7 @@ void Inventory::setItem(int index, int id, int quantity) { if (index < 0 || index >= getSize()) { - logger->log("Warning: invalid inventory index: %d", index); + Log::warn("Invalid inventory index: %d", index); return; } diff --git a/src/joystick.cpp b/src/joystick.cpp index c6e106bf..070e9dcf 100644 --- a/src/joystick.cpp +++ b/src/joystick.cpp @@ -36,9 +36,9 @@ void Joystick::init() SDL_JoystickEventState(SDL_ENABLE); joystickCount = SDL_NumJoysticks(); - logger->log("%i joysticks/gamepads found", joystickCount); + Log::info("%i joysticks/gamepads found", joystickCount); for (int i = 0; i < joystickCount; i++) - logger->log("- %s", SDL_JoystickNameForIndex(i)); + Log::info("- %s", SDL_JoystickNameForIndex(i)); } Joystick::Joystick(int no) @@ -57,14 +57,14 @@ Joystick::Joystick(int no) // TODO Bail out! if (!mJoystick) { - logger->log("Couldn't open joystick: %s", SDL_GetError()); + Log::info("Couldn't open joystick: %s", SDL_GetError()); return; } - logger->log("Axes: %i ", SDL_JoystickNumAxes(mJoystick)); - logger->log("Balls: %i", SDL_JoystickNumBalls(mJoystick)); - logger->log("Hats: %i", SDL_JoystickNumHats(mJoystick)); - logger->log("Buttons: %i", SDL_JoystickNumButtons(mJoystick)); + Log::info("Axes: %i ", SDL_JoystickNumAxes(mJoystick)); + Log::info("Balls: %i", SDL_JoystickNumBalls(mJoystick)); + Log::info("Hats: %i", SDL_JoystickNumHats(mJoystick)); + Log::info("Buttons: %i", SDL_JoystickNumButtons(mJoystick)); } Joystick::~Joystick() diff --git a/src/log.cpp b/src/log.cpp index 24cb6e9d..eeb26b00 100644 --- a/src/log.cpp +++ b/src/log.cpp @@ -1,7 +1,7 @@ /* * The Mana Client * Copyright (C) 2004-2009 The Mana World Development Team - * Copyright (C) 2009-2012 The Mana Developers + * Copyright (C) 2009-2025 The Mana Developers * * This file is part of The Mana Client. * @@ -23,47 +23,36 @@ #include <SDL.h> -#include <sys/time.h> +#include <cstdarg> +#include <fstream> #include <iostream> #include <sstream> -#include <cstdarg> -#include <cstdio> +#include <sys/time.h> -Logger::Logger() = default; -Logger::~Logger() = default; +static std::ofstream logFile; +static bool logToStandardOut = true; -void Logger::setLogFile(const std::string &logFilename) +static const char *getLogPriorityPrefix(SDL_LogPriority priority) { - mLogFile.open(logFilename, std::ios_base::trunc); - - if (!mLogFile.is_open()) - { - std::cout << "Warning: error while opening " << logFilename << - " for writing.\n"; + switch (priority) { + case SDL_LOG_PRIORITY_WARN: + return "Warning: "; + case SDL_LOG_PRIORITY_ERROR: + return "Error: "; + case SDL_LOG_PRIORITY_CRITICAL: + return "Critical Error: "; + default: + return ""; } } -void Logger::log(const char *log_text, ...) -{ - va_list ap; - va_start(ap, log_text); - vlog(log_text, ap); - va_end(ap); -} - -void Logger::vlog(const char *log_text, va_list ap) +static void logOutputFunction(void *userdata, int category, SDL_LogPriority priority, const char *message) { - const size_t bufSize = 1024; - char* buf = new char[bufSize]; - - // Use a temporary buffer to fill in the variables - vsnprintf(buf, bufSize, log_text, ap); - // Get the current system time timeval tv; gettimeofday(&tv, nullptr); - // Print the log entry + // Create timestamp string std::stringstream timeStr; timeStr << "[" << ((((tv.tv_sec / 60) / 60) % 24 < 10) ? "0" : "") @@ -79,24 +68,71 @@ void Logger::vlog(const char *log_text, va_list ap) << (int)((tv.tv_usec / 10000) % 100) << "] "; - if (mLogFile.is_open()) + const char *prefix = getLogPriorityPrefix(priority); + + if (logToStandardOut) + { + std::cout << timeStr.str() << prefix << message << std::endl; + } + + if (logFile.is_open()) { - mLogFile << timeStr.str() << buf << std::endl; + logFile << timeStr.str() << prefix << message << std::endl; } +} + +void Log::init() +{ + SDL_LogSetOutputFunction(logOutputFunction, nullptr); +} - if (mLogToStandardOut) +void Log::setLogFile(const std::string &logFilename) +{ + logFile.open(logFilename, std::ios_base::trunc); + + if (!logFile.is_open()) { - std::cout << timeStr.str() << buf << std::endl; + std::cout << "Warning: error while opening " << logFilename + << " for writing.\n"; } +} - // Delete temporary buffer - delete[] buf; +void Log::setLogToStandardOut(bool value) +{ + logToStandardOut = value; } -void Logger::error(const std::string &error_text) +#define DEFINE_LOG_FUNCTION(name, priority) \ + void Log::name(const char *fmt, ...) \ + { \ + va_list ap; \ + va_start(ap, fmt); \ + SDL_LogMessageV(SDL_LOG_CATEGORY_APPLICATION, priority, fmt, ap); \ + va_end(ap); \ + } + +DEFINE_LOG_FUNCTION(verbose, SDL_LOG_PRIORITY_VERBOSE) +DEFINE_LOG_FUNCTION(debug, SDL_LOG_PRIORITY_DEBUG) +DEFINE_LOG_FUNCTION(info, SDL_LOG_PRIORITY_INFO) +DEFINE_LOG_FUNCTION(warn, SDL_LOG_PRIORITY_WARN) +DEFINE_LOG_FUNCTION(error, SDL_LOG_PRIORITY_ERROR) + +#undef DEFINE_LOG_FUNCTION + +void Log::vinfo(const char *fmt, va_list ap) +{ + SDL_LogMessageV(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO, fmt, ap); +} + +void Log::critical(const std::string &message) { - log("Error: %s", error_text.c_str()); - std::cerr << "Error: " << error_text << std::endl; - SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", error_text.c_str(), nullptr); + SDL_LogCritical(SDL_LOG_CATEGORY_APPLICATION, "%s", message.c_str()); + + if (!logToStandardOut) + { + std::cerr << getLogPriorityPrefix(SDL_LOG_PRIORITY_CRITICAL) << message << std::endl; + } + + SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", message.c_str(), nullptr); exit(1); } @@ -1,7 +1,7 @@ /* * The Mana Client * Copyright (C) 2004-2009 The Mana World Development Team - * Copyright (C) 2009-2012 The Mana Developers + * Copyright (C) 2009-2025 The Mana Developers * * This file is part of The Mana Client. * @@ -21,52 +21,51 @@ #pragma once -#include <fstream> +#include <string> +#include <cstdarg> + +#ifdef __GNUC__ +# define LOG_PRINTF_ATTR __attribute__((__format__(__printf__, 1, 2))) +#else +# define LOG_PRINTF_ATTR +#endif /** - * The Log Class : Useful to write debug or info messages + * The Log namespace: Useful to write debug or info messages to the log file + * and/or console. The messages will be timestamped. */ -class Logger +namespace Log { - public: - Logger(); + /** + * Initializes the log system. + */ + void init(); - /** - * Destructor, closes log file. - */ - ~Logger(); + /** + * Sets the file to log to and opens it. + */ + void setLogFile(const std::string &logFilename); - /** - * Sets the file to log to and opens it - */ - void setLogFile(const std::string &logFilename); + /** + * Sets whether the log should be written to standard output. + */ + void setLogToStandardOut(bool value); - /** - * Sets whether the log should be written to standard output. - */ - void setLogToStandardOut(bool value) { mLogToStandardOut = value; } - - /** - * Enters a message in the log. The message will be timestamped. - */ - void log(const char *log_text, ...) -#ifdef __GNUC__ - __attribute__((__format__(__printf__, 2, 3))) -#endif - ; + void verbose(const char *log_text, ...) LOG_PRINTF_ATTR; + void debug(const char *log_text, ...) LOG_PRINTF_ATTR; + void info(const char *log_text, ...) LOG_PRINTF_ATTR; + void warn(const char *log_text, ...) LOG_PRINTF_ATTR; + void error(const char *log_text, ...) LOG_PRINTF_ATTR; - void vlog(const char *log_text, va_list ap); + void vinfo(const char *log_text, va_list ap); - /** - * Log an error and quit. The error will be printed to standard error - * and showm in a simple message box. - */ - __attribute__((noreturn)) - void error(const std::string &error_text); + /** + * Log an error and quit. The error will be printed to standard error + * and shown in a simple message box. + */ + __attribute__((noreturn)) + void critical(const std::string &error_text); - private: - std::ofstream mLogFile; - bool mLogToStandardOut = true; -}; +} // namespace Log -extern Logger *logger; +#undef LOG_PRINTF_ATTR diff --git a/src/map.cpp b/src/map.cpp index 908d6178..8dbc7c28 100644 --- a/src/map.cpp +++ b/src/map.cpp @@ -983,7 +983,7 @@ void Map::addAnimation(int gid, TileAnimation animation) auto const [_, inserted] = mTileAnimations.try_emplace(gid, std::move(animation)); if (!inserted) { - logger->error(strprintf("Duplicate tile animation for gid %d", gid)); + Log::warn("Duplicate tile animation for gid %d", gid); } } diff --git a/src/net/download.cpp b/src/net/download.cpp index 7aab3b2f..571af7a4 100644 --- a/src/net/download.cpp +++ b/src/net/download.cpp @@ -108,13 +108,13 @@ bool Download::start() { assert(!mThread); // Download already started - logger->log("Starting download: %s", mUrl.c_str()); + Log::info("Starting download: %s", mUrl.c_str()); mThread = SDL_CreateThread(downloadThread, "Download", this); if (!mThread) { - logger->log("%s", DOWNLOAD_ERROR_MESSAGE_THREAD); + Log::info("%s", DOWNLOAD_ERROR_MESSAGE_THREAD); strncpy(mError, DOWNLOAD_ERROR_MESSAGE_THREAD, CURL_ERROR_SIZE - 1); mState.lock()->status = DownloadStatus::Error; return false; @@ -125,7 +125,7 @@ bool Download::start() void Download::cancel() { - logger->log("Canceling download: %s", mUrl.c_str()); + Log::info("Canceling download: %s", mUrl.c_str()); mCancel = true; } @@ -186,7 +186,7 @@ int Download::downloadThread(void *ptr) if (!curl) break; - logger->log("Downloading: %s", d->mUrl.c_str()); + Log::info("Downloading: %s", d->mUrl.c_str()); curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, d->mHeaders); @@ -236,8 +236,8 @@ int Download::downloadThread(void *ptr) if (res != CURLE_OK) { - logger->log("curl error %d: %s host: %s", - res, d->mError, d->mUrl.c_str()); + Log::info("curl error %d: %s host: %s", + res, d->mError, d->mUrl.c_str()); if (file) { @@ -262,9 +262,9 @@ int Download::downloadThread(void *ptr) // Remove the corrupted file ::remove(outFilename.c_str()); - logger->log("Checksum for file %s failed: (%lx/%lx)", - d->mFileName.c_str(), - adler, *d->mAdler); + Log::info("Checksum for file %s failed: (%lx/%lx)", + d->mFileName.c_str(), + adler, *d->mAdler); continue; // Bail out here to avoid the renaming } diff --git a/src/net/manaserv/charhandler.cpp b/src/net/manaserv/charhandler.cpp index 98591669..cc0ea17e 100644 --- a/src/net/manaserv/charhandler.cpp +++ b/src/net/manaserv/charhandler.cpp @@ -264,10 +264,10 @@ void CharHandler::handleCharacterSelectResponse(MessageIn &msg) chatServer.hostname.assign(msg.readString()); chatServer.port = msg.readInt16(); - logger->log("Game server: %s:%d", gameServer.hostname.c_str(), - gameServer.port); - logger->log("Chat server: %s:%d", chatServer.hostname.c_str(), - chatServer.port); + Log::info("Game server: %s:%d", gameServer.hostname.c_str(), + gameServer.port); + Log::info("Chat server: %s:%d", chatServer.hostname.c_str(), + chatServer.port); // Prevent the selected local player from being deleted local_player = mSelectedCharacter->dummy; diff --git a/src/net/manaserv/chathandler.cpp b/src/net/manaserv/chathandler.cpp index dca556c2..436da820 100644 --- a/src/net/manaserv/chathandler.cpp +++ b/src/net/manaserv/chathandler.cpp @@ -158,8 +158,8 @@ void ChatHandler::handleGameChatMessage(MessageIn &msg) if (!being) { - logger->log("Warning: Received GPMSG_SAY for unknown being with id %i." - " (Message is: %s)", id, chatMsg.c_str()); + Log::warn("Received GPMSG_SAY for unknown being with id %i." + " (Message is: %s)", id, chatMsg.c_str()); return; } @@ -262,7 +262,7 @@ void ChatHandler::handleChatMessage(MessageIn &msg) else { // Can't find channel - logger->log("Couldn't find chat channel id: %hi", channelId); + Log::info("Couldn't find chat channel id: %hi", channelId); } } diff --git a/src/net/manaserv/connection.cpp b/src/net/manaserv/connection.cpp index 1b6f757a..2eb5b4bf 100644 --- a/src/net/manaserv/connection.cpp +++ b/src/net/manaserv/connection.cpp @@ -44,13 +44,13 @@ Connection::~Connection() bool Connection::connect(const std::string &address, enet_uint16 port) { - logger->log("Net::Connection::connect(%s, %i)", address.c_str(), port); + Log::info("Net::Connection::connect(%s, %i)", address.c_str(), port); if (mConnection) disconnect(); if (address.empty()) { - logger->log("Net::Connection::connect() got empty address!"); + Log::info("Net::Connection::connect() got empty address!"); mState = NET_ERROR; return false; } @@ -65,7 +65,7 @@ bool Connection::connect(const std::string &address, enet_uint16 port) if (!mConnection) { - logger->log("Unable to initiate connection to the server."); + Log::info("Unable to initiate connection to the server."); mState = NET_ERROR; return false; } @@ -96,7 +96,7 @@ void Connection::send(const ManaServ::MessageOut &msg) { if (!isConnected()) { - logger->log("Warning: cannot send message to not connected server!"); + Log::warn("Cannot send message to not connected server!"); return; } diff --git a/src/net/manaserv/effecthandler.cpp b/src/net/manaserv/effecthandler.cpp index 22d1f9cf..afd7cd5c 100644 --- a/src/net/manaserv/effecthandler.cpp +++ b/src/net/manaserv/effecthandler.cpp @@ -82,7 +82,7 @@ void EffectHandler::handleCreateEffectBeing(MessageIn &msg) if (b) effectManager->trigger(eid, b); else - logger->log("Warning: CreateEffect called for unknown being #%d", bid); + Log::warn("CreateEffect called for unknown being #%d", bid); } void EffectHandler::handleCreateTextParticle(MessageIn &msg) @@ -120,7 +120,7 @@ void EffectHandler::handleShake(MessageIn &msg) viewport->shakeScreen(intensityX, intensityY, decay, duration); break; default: - logger->log("Warning: Received GPMSG_SHAKE message with unexpected length of %d bytes", msg.getUnreadLength()); + Log::warn("Received GPMSG_SHAKE message with unexpected length of %d bytes", msg.getUnreadLength()); } } diff --git a/src/net/manaserv/guildhandler.cpp b/src/net/manaserv/guildhandler.cpp index 9fdbafc2..bae38c37 100644 --- a/src/net/manaserv/guildhandler.cpp +++ b/src/net/manaserv/guildhandler.cpp @@ -73,7 +73,7 @@ void GuildHandler::handleMessage(MessageIn &msg) { case CPMSG_GUILD_CREATE_RESPONSE: { - logger->log("Received CPMSG_GUILD_CREATE_RESPONSE"); + Log::info("Received CPMSG_GUILD_CREATE_RESPONSE"); if (msg.readInt8() == ERRMSG_OK) { // TODO - Acknowledge guild was created @@ -88,7 +88,7 @@ void GuildHandler::handleMessage(MessageIn &msg) case CPMSG_GUILD_INVITE_RESPONSE: { - logger->log("Received CPMSG_GUILD_INVITE_RESPONSE"); + Log::info("Received CPMSG_GUILD_INVITE_RESPONSE"); const unsigned char response = msg.readInt8(); if (response == ERRMSG_OK) { @@ -111,7 +111,7 @@ void GuildHandler::handleMessage(MessageIn &msg) case CPMSG_GUILD_ACCEPT_RESPONSE: { - logger->log("Received CPMSG_GUILD_ACCEPT_RESPONSE"); + Log::info("Received CPMSG_GUILD_ACCEPT_RESPONSE"); if (msg.readInt8() == ERRMSG_OK) { // TODO - Acknowledge accepted into guild @@ -121,7 +121,7 @@ void GuildHandler::handleMessage(MessageIn &msg) case CPMSG_GUILD_GET_MEMBERS_RESPONSE: { - logger->log("Received CPMSG_GUILD_GET_MEMBERS_RESPONSE"); + Log::info("Received CPMSG_GUILD_GET_MEMBERS_RESPONSE"); if (msg.readInt8() == ERRMSG_OK) { std::string name; @@ -152,7 +152,7 @@ void GuildHandler::handleMessage(MessageIn &msg) case CPMSG_GUILD_UPDATE_LIST: { - logger->log("Received CPMSG_GUILD_UPDATE_LIST"); + Log::info("Received CPMSG_GUILD_UPDATE_LIST"); short guildId = msg.readInt16(); std::string name = msg.readString(); char eventId = msg.readInt8(); @@ -189,14 +189,14 @@ void GuildHandler::handleMessage(MessageIn &msg) break; default: - logger->log("Invalid guild event"); + Log::info("Invalid guild event"); } } } break; case CPMSG_GUILD_INVITED: { - logger->log("Received CPMSG_GUILD_INVITED"); + Log::info("Received CPMSG_GUILD_INVITED"); std::string inviterName = msg.readString(); std::string guildName = msg.readString(); int guildId = msg.readInt16(); @@ -207,7 +207,7 @@ void GuildHandler::handleMessage(MessageIn &msg) case CPMSG_GUILD_PROMOTE_MEMBER_RESPONSE: { - logger->log("Received CPMSG_GUILD_PROMOTE_MEMBER_RESPONSE"); + Log::info("Received CPMSG_GUILD_PROMOTE_MEMBER_RESPONSE"); if (msg.readInt8() == ERRMSG_OK) { @@ -223,14 +223,14 @@ void GuildHandler::handleMessage(MessageIn &msg) case CPMSG_GUILD_REJOIN: { - logger->log("Received CPMSG_GUILD_REJOIN"); + Log::info("Received CPMSG_GUILD_REJOIN"); joinedGuild(msg); } break; case CPMSG_GUILD_QUIT_RESPONSE: { - logger->log("Received CPMSG_GUILD_QUIT_RESPONSE"); + Log::info("Received CPMSG_GUILD_QUIT_RESPONSE"); if (msg.readInt8() == ERRMSG_OK) { @@ -247,7 +247,7 @@ void GuildHandler::handleMessage(MessageIn &msg) } break; case CPMSG_GUILD_KICK_NOTIFICATION: { - logger->log("Received CPMSG_GUILD_KICK_NOTIFICATION"); + Log::info("Received CPMSG_GUILD_KICK_NOTIFICATION"); const int guildId = msg.readInt16(); std::string player = msg.readString(); diff --git a/src/net/manaserv/inventoryhandler.cpp b/src/net/manaserv/inventoryhandler.cpp index 58a495af..fa31b32a 100644 --- a/src/net/manaserv/inventoryhandler.cpp +++ b/src/net/manaserv/inventoryhandler.cpp @@ -88,9 +88,8 @@ void EquipBackend::equip(int inventorySlot, int equipmentSlot) auto slotIt = mSlots.find(equipmentSlot); if (slotIt == mSlots.end()) { - logger->log("ManaServ::EquipBackend: Equipment slot %i" - " is not existing.", - equipmentSlot); + Log::info("ManaServ::EquipBackend: Equipment slot %i" + " is not existing.", equipmentSlot); return; } @@ -115,8 +114,8 @@ void EquipBackend::unequip(int inventorySlot) } } - logger->log("ManaServ::EquipBackend: No equipped item found at inventory " - "slot %i!", inventorySlot); + Log::info("ManaServ::EquipBackend: No equipped item found at inventory " + "slot %i!", inventorySlot); } void EquipBackend::event(Event::Channel, const Event &event) @@ -134,8 +133,8 @@ void EquipBackend::readEquipFile() if (!rootNode || rootNode.name() != "equip-slots") { - logger->log("ManaServ::EquipBackend: Error while reading " - EQUIP_FILE "!"); + Log::info("ManaServ::EquipBackend: Error while reading " + EQUIP_FILE "!"); return; } diff --git a/src/net/manaserv/loginhandler.cpp b/src/net/manaserv/loginhandler.cpp index 1c398990..9828af29 100644 --- a/src/net/manaserv/loginhandler.cpp +++ b/src/net/manaserv/loginhandler.cpp @@ -342,7 +342,7 @@ void LoginHandler::readServerInfo(MessageIn &msg) if (!updateHost.empty()) mLoginData->updateHost = updateHost; else - logger->log("Warning: server does not have an update host set!"); + Log::warn("Server does not have an update host set!"); // Read the client data folder for dynamic data loading. // This is only used by the Qt client. diff --git a/src/net/manaserv/network.cpp b/src/net/manaserv/network.cpp index d69d3397..cb9f76a0 100644 --- a/src/net/manaserv/network.cpp +++ b/src/net/manaserv/network.cpp @@ -48,14 +48,14 @@ void initialize() { if (enet_initialize()) { - logger->error("Failed to initialize ENet."); + Log::critical("Failed to initialize ENet."); } client = enet_host_create(nullptr, 3, 0, 0, 0); if (!client) { - logger->error("Failed to create the local host."); + Log::critical("Failed to create the local host."); } } @@ -66,7 +66,7 @@ void finalize() if (connections) { - logger->error("Tried to shutdown the network subsystem while there " + Log::critical("Tried to shutdown the network subsystem while there " "are network connections left!"); } @@ -78,7 +78,7 @@ Connection *getConnection() { if (!client) { - logger->error("Tried to instantiate a network object before " + Log::critical("Tried to instantiate a network object before " "initializing the network subsystem!"); } @@ -117,14 +117,14 @@ namespace if (iter != mMessageHandlers.end()) { - //logger->log("Received packet %x (%i B)", - // msg.getId(), msg.getLength()); + //Log::info("Received packet %x (%i B)", + // msg.getId(), msg.getLength()); iter->second->handleMessage(msg); } else { - logger->log("Unhandled packet %x (%i B)", - msg.getId(), msg.getLength()); + Log::info("Unhandled packet %x (%i B)", + msg.getId(), msg.getLength()); } // Clean up the packet now that we're done using it. @@ -142,7 +142,7 @@ void flush() switch (event.type) { case ENET_EVENT_TYPE_CONNECT: - logger->log("Connected to port %d.", event.peer->address.port); + Log::info("Connected to port %d.", event.peer->address.port); // Store any relevant server information here. event.peer->data = nullptr; break; @@ -152,7 +152,7 @@ void flush() break; case ENET_EVENT_TYPE_DISCONNECT: - logger->log("Disconnected."); + Log::info("Disconnected."); // Reset the server information. event.peer->data = nullptr; break; diff --git a/src/net/manaserv/partyhandler.cpp b/src/net/manaserv/partyhandler.cpp index e2a021cd..23ea7aa5 100644 --- a/src/net/manaserv/partyhandler.cpp +++ b/src/net/manaserv/partyhandler.cpp @@ -103,7 +103,7 @@ void PartyHandler::handleMessage(MessageIn &msg) "inviter has left the game.")); break; default: - logger->log("Unknown CPMSG_PARTY_INVITE_ANSWER_RESPONSE."); + Log::info("Unknown CPMSG_PARTY_INVITE_ANSWER_RESPONSE."); break; } } break; @@ -161,7 +161,7 @@ void PartyHandler::handleMessage(MessageIn &msg) name.c_str())); break; default: - logger->log("Unknown CPMSG_PARTY_REJECTED."); + Log::info("Unknown CPMSG_PARTY_REJECTED."); break; } } break; diff --git a/src/net/manaserv/playerhandler.cpp b/src/net/manaserv/playerhandler.cpp index 8ee9ed80..edae6be6 100644 --- a/src/net/manaserv/playerhandler.cpp +++ b/src/net/manaserv/playerhandler.cpp @@ -96,7 +96,7 @@ void PlayerHandler::handleMessage(MessageIn &msg) netToken = msg.readString(32); std::string address = msg.readString(); int port = msg.readInt16(); - logger->log("Changing server to %s:%d", address.c_str(), port); + Log::info("Changing server to %s:%d", address.c_str(), port); gameServer.hostname = address; gameServer.port = port; @@ -147,14 +147,14 @@ void PlayerHandler::handleMessage(MessageIn &msg) } break; case ATTRIBMOD_INVALID_ATTRIBUTE: { - logger->log("Warning: Server denied increase of attribute %d (unknown attribute) ", attrNum); + Log::warn("Server denied increase of attribute %d (unknown attribute) ", attrNum); } break; case ATTRIBMOD_NO_POINTS_LEFT: { // when the server says "you got no points" it // has to be correct. The server is always right! // undo attribute change and set points to 0 - logger->log("Warning: Server denied increase of attribute %d (no points left) ", attrNum); + Log::warn("Server denied increase of attribute %d (no points left) ", attrNum); int attrValue = PlayerInfo::getStatBase(attrNum) - 1; PlayerInfo::setAttribute(CHAR_POINTS, 0); PlayerInfo::setStatBase(attrNum, attrValue); @@ -162,7 +162,7 @@ void PlayerHandler::handleMessage(MessageIn &msg) case ATTRIBMOD_DENIED: { // undo attribute change - logger->log("Warning: Server denied increase of attribute %d (reason unknown) ", attrNum); + Log::warn("Server denied increase of attribute %d (reason unknown) ", attrNum); int points = PlayerInfo::getAttribute(CHAR_POINTS) - 1; PlayerInfo::setAttribute(CHAR_POINTS, points); @@ -184,14 +184,14 @@ void PlayerHandler::handleMessage(MessageIn &msg) } break; case ATTRIBMOD_INVALID_ATTRIBUTE: { - logger->log("Warning: Server denied reduction of attribute %d (unknown attribute) ", attrNum); + Log::warn("Server denied reduction of attribute %d (unknown attribute) ", attrNum); } break; case ATTRIBMOD_NO_POINTS_LEFT: { // when the server says "you got no points" it // has to be correct. The server is always right! // undo attribute change and set points to 0 - logger->log("Warning: Server denied reduction of attribute %d (no points left) ", attrNum); + Log::warn("Server denied reduction of attribute %d (no points left) ", attrNum); int attrValue = PlayerInfo::getStatBase(attrNum) + 1; // TODO are these right? PlayerInfo::setAttribute(CHAR_POINTS, 0); @@ -201,7 +201,7 @@ void PlayerHandler::handleMessage(MessageIn &msg) case ATTRIBMOD_DENIED: { // undo attribute change - logger->log("Warning: Server denied reduction of attribute %d (reason unknown) ", attrNum); + Log::warn("Server denied reduction of attribute %d (reason unknown) ", attrNum); int charaPoints = PlayerInfo::getAttribute(CHAR_POINTS) - 1; PlayerInfo::setAttribute(CHAR_POINTS, charaPoints); @@ -245,7 +245,7 @@ void PlayerHandler::handleMessage(MessageIn &msg) BY_SERVER); break; default: - logger->log("0x013b: Unhandled message %i", type); + Log::info("0x013b: Unhandled message %i", type); break; } } @@ -263,7 +263,7 @@ void PlayerHandler::handleMapChangeMessage(MessageIn &msg) Game *game = Game::instance(); const bool sameMap = (game->getCurrentMapName() == mapName); - logger->log("Changing map to %s (%d, %d)", mapName.c_str(), x, y); + Log::info("Changing map to %s (%d, %d)", mapName.c_str(), x, y); // Switch the actual map, deleting the previous one game->changeMap(mapName); @@ -285,8 +285,8 @@ void PlayerHandler::handleMapChangeMessage(MessageIn &msg) local_player->setPosition(x, y); local_player->setDestination(x, y); - logger->log("Adjust scrolling by %d,%d", (int) scrollOffsetX, - (int) scrollOffsetY); + Log::info("Adjust scrolling by %d,%d", (int) scrollOffsetX, + (int) scrollOffsetY); viewport->scrollBy(scrollOffsetX, scrollOffsetY); } @@ -295,7 +295,7 @@ void PlayerHandler::attack(int id) auto ability = AbilityDB::find("Strike"); if (!ability) { - logger->log("PlayerHandler::attack: 'Strike' ability not found."); + Log::info("PlayerHandler::attack: 'Strike' ability not found."); return; } @@ -304,7 +304,7 @@ void PlayerHandler::attack(int id) abilityHandler->useOn(ability->id, id); break; case AbilityInfo::TARGET_POINT: - logger->log("PlayerHandler::attack: Unsupported target mode 'point' for 'Strike' ability."); + Log::info("PlayerHandler::attack: Unsupported target mode 'point' for 'Strike' ability."); break; case AbilityInfo::TARGET_DIRECTION: abilityHandler->useInDirection(ability->id, local_player->getDirection()); @@ -420,8 +420,8 @@ Vector PlayerHandler::getPixelsPerSecondMoveSpeed(const Vector &speed, Map *map) if (!map) { - logger->log("Manaserv::PlayerHandler: Speed wasn't given back" - " because Map not initialized."); + Log::info("Manaserv::PlayerHandler: Speed wasn't given back" + " because Map not initialized."); return speedInPixels; } diff --git a/src/net/net.cpp b/src/net/net.cpp index 1d157b3d..443a739c 100644 --- a/src/net/net.cpp +++ b/src/net/net.cpp @@ -138,7 +138,7 @@ void connectToServer(ServerInfo &server) else if (server.port == 9601) server.type = ServerType::ManaServ; else - logger->error(_("Unknown Server Type! Exiting.")); + Log::critical(_("Unknown Server Type! Exiting.")); } if (networkType == server.type && getGeneralHandler() != nullptr) @@ -160,7 +160,7 @@ void connectToServer(ServerInfo &server) generalHandler = new TmwAthena::GeneralHandler; break; default: - logger->error(_("Server protocol unsupported")); + Log::critical(_("Server protocol unsupported")); break; } @@ -203,4 +203,3 @@ ServerType getNetworkType() } } // namespace Net - diff --git a/src/net/tmwa/abilityhandler.cpp b/src/net/tmwa/abilityhandler.cpp index ab891b40..fea492ef 100644 --- a/src/net/tmwa/abilityhandler.cpp +++ b/src/net/tmwa/abilityhandler.cpp @@ -129,7 +129,7 @@ void AbilityHandler::handleMessage(MessageIn &msg) auto type = msg.readInt8(); if (btype == BSKILL_EMOTE) { - logger->log("Action: %d", btype); + Log::info("Action: %d", btype); } std::string msg; diff --git a/src/net/tmwa/beinghandler.cpp b/src/net/tmwa/beinghandler.cpp index c7debd5e..690b0d87 100644 --- a/src/net/tmwa/beinghandler.cpp +++ b/src/net/tmwa/beinghandler.cpp @@ -531,8 +531,8 @@ void BeingHandler::handleMessage(MessageIn &msg) dstBeing->setSprite(SPRITE_MISC2, id); break; default: - logger->log("SMSG_BEING_CHANGE_LOOKS2: unsupported type: " - "%d, id: %d", static_cast<int>(type), id); + Log::info("SMSG_BEING_CHANGE_LOOKS2: unsupported type: " + "%d, id: %d", static_cast<int>(type), id); break; } } diff --git a/src/net/tmwa/charserverhandler.cpp b/src/net/tmwa/charserverhandler.cpp index 0ecbb135..fcd47b74 100644 --- a/src/net/tmwa/charserverhandler.cpp +++ b/src/net/tmwa/charserverhandler.cpp @@ -89,8 +89,8 @@ void CharServerHandler::handleMessage(MessageIn &msg) auto *character = new Net::Character; readPlayerData(msg, character); mCharacters.push_back(character); - logger->log("CharServer: Player: %s (%d)", - character->dummy->getName().c_str(), character->slot); + Log::info("CharServer: Player: %s (%d)", + character->dummy->getName().c_str(), character->slot); } Client::setState(STATE_CHAR_SELECT); diff --git a/src/net/tmwa/gamehandler.cpp b/src/net/tmwa/gamehandler.cpp index 0a3bb9d9..a88e377e 100644 --- a/src/net/tmwa/gamehandler.cpp +++ b/src/net/tmwa/gamehandler.cpp @@ -68,8 +68,8 @@ void GameHandler::handleMessage(MessageIn &msg) msg.readInt32(); // server tick msg.readCoordinates(x, y, direction); msg.skip(2); // unknown - logger->log("Protocol: Player start position: (%d, %d), Direction: %d", - x, y, direction); + Log::info("Protocol: Player start position: (%d, %d), Direction: %d", + x, y, direction); // Switch now or we'll have problems Client::setState(STATE_GAME); // Stores the position until the map is loaded. diff --git a/src/net/tmwa/generalhandler.cpp b/src/net/tmwa/generalhandler.cpp index d6eb3b34..1f52c3db 100644 --- a/src/net/tmwa/generalhandler.cpp +++ b/src/net/tmwa/generalhandler.cpp @@ -117,7 +117,7 @@ void GeneralHandler::handleMessage(MessageIn &msg) { case SMSG_CONNECTION_PROBLEM: code = msg.readInt8(); - logger->log("Connection problem: %i", code); + Log::info("Connection problem: %i", code); switch (code) { diff --git a/src/net/tmwa/inventoryhandler.cpp b/src/net/tmwa/inventoryhandler.cpp index 0d8e3005..73d967a6 100644 --- a/src/net/tmwa/inventoryhandler.cpp +++ b/src/net/tmwa/inventoryhandler.cpp @@ -157,10 +157,10 @@ void InventoryHandler::handleMessage(MessageIn &msg) if (debugInventory) { - logger->log("Index: %d, ID: %d, Type: %d, Identified: %d, " - "Qty: %d, Cards: %d, %d, %d, %d", - index, itemId, itemType, identified, amount, - cards[0], cards[1], cards[2], cards[3]); + Log::info("Index: %d, ID: %d, Type: %d, Identified: %d, " + "Qty: %d, Cards: %d, %d, %d, %d", + index, itemId, itemType, identified, amount, + cards[0], cards[1], cards[2], cards[3]); } if (msg.getId() == SMSG_PLAYER_INVENTORY) @@ -191,10 +191,10 @@ void InventoryHandler::handleMessage(MessageIn &msg) if (debugInventory) { - logger->log("Index: %d, ID: %d, Type: %d, Identified: %d, " - "Qty: %d, Cards: %d, %d, %d, %d", - index, itemId, itemType, identified, amount, - cards[0], cards[1], cards[2], cards[3]); + Log::info("Index: %d, ID: %d, Type: %d, Identified: %d, " + "Qty: %d, Cards: %d, %d, %d, %d", + index, itemId, itemType, identified, amount, + cards[0], cards[1], cards[2], cards[3]); } mInventoryItems.push_back( @@ -419,8 +419,8 @@ void InventoryHandler::handleMessage(MessageIn &msg) } else { - logger->log("Couldn't set attacke range due to the lack" - "of an initialized map."); + Log::info("Couldn't set attacke range due to the lack" + "of an initialized map."); local_player->setAttackRange(-1); } } @@ -434,7 +434,7 @@ void InventoryHandler::handleMessage(MessageIn &msg) index -= INVENTORY_OFFSET; - logger->log("Arrows equipped: %i", index); + Log::info("Arrows equipped: %i", index); mEquips.setEquipment(EQUIP_PROJECTILE_SLOT, index); break; } diff --git a/src/net/tmwa/inventoryhandler.h b/src/net/tmwa/inventoryhandler.h index f5ef4492..cde1235b 100644 --- a/src/net/tmwa/inventoryhandler.h +++ b/src/net/tmwa/inventoryhandler.h @@ -108,9 +108,9 @@ class EquipBackend final : public Equipment::Backend if (!newItem && inventoryIndex >= 0) { - logger->log("EquipBackend: Warning, trying to equip " - "non-existing item from inventory index %i at " - "equipment slot %i.", inventoryIndex, index); + Log::info("EquipBackend: Warning, trying to equip " + "non-existing item from inventory index %i at " + "equipment slot %i.", inventoryIndex, index); return; } diff --git a/src/net/tmwa/loginhandler.cpp b/src/net/tmwa/loginhandler.cpp index a7162ee6..b6e3d518 100644 --- a/src/net/tmwa/loginhandler.cpp +++ b/src/net/tmwa/loginhandler.cpp @@ -108,7 +108,7 @@ void LoginHandler::handleMessage(MessageIn &msg) mUpdateHost = msg.readString(len); loginData.updateHost = mUpdateHost; - logger->log("Received update host \"%s\" from login server.", + Log::info("Received update host \"%s\" from login server.", mUpdateHost.c_str()); break; } @@ -138,10 +138,10 @@ void LoginHandler::handleMessage(MessageIn &msg) msg.readInt16(); // maintenance msg.readInt16(); // is_new - logger->log("Network: Server: %s (%s:%d)", - world->name.c_str(), - ipToString(world->address), - world->port); + Log::info("Network: Server: %s (%s:%d)", + world->name.c_str(), + ipToString(world->address), + world->port); mWorlds.push_back(world); } @@ -150,7 +150,7 @@ void LoginHandler::handleMessage(MessageIn &msg) case SMSG_LOGIN_ERROR: code = msg.readInt8(); - logger->log("Login::error code: %i", code); + Log::info("Login::error code: %i", code); switch (code) { @@ -212,9 +212,9 @@ void LoginHandler::handleMessage(MessageIn &msg) mServerVersion = 0; if (mServerVersion > 0) - logger->log("TMW server version: x%06x", mServerVersion); + Log::info("TMW server version: x%06x", mServerVersion); else - logger->log("Server without version"); + Log::info("Server without version"); mRegistrationEnabled = (options & FLAG_REGISTRATION); diff --git a/src/net/tmwa/messageout.cpp b/src/net/tmwa/messageout.cpp index a886fb4d..7758e306 100644 --- a/src/net/tmwa/messageout.cpp +++ b/src/net/tmwa/messageout.cpp @@ -23,6 +23,8 @@ #include "net/tmwa/network.h" +#include "log.h" + #include <SDL_endian.h> #include <cstring> @@ -32,7 +34,7 @@ namespace TmwAthena { MessageOut::MessageOut(uint16_t id) { #ifdef DEBUG - logger->log("Sending %s (0x%x)", Network::mInstance->messageName(id), id); + Log::info("Sending %s (0x%x)", Network::mInstance->messageName(id), id); #endif writeInt16(id); } diff --git a/src/net/tmwa/network.cpp b/src/net/tmwa/network.cpp index b448dc4f..9e010f7c 100644 --- a/src/net/tmwa/network.cpp +++ b/src/net/tmwa/network.cpp @@ -279,7 +279,7 @@ bool Network::connect(const ServerInfo &server) { if (mState != IDLE && mState != NET_ERROR) { - logger->log("Tried to connect an already connected socket!"); + Log::info("Tried to connect an already connected socket!"); assert(false); return false; } @@ -290,8 +290,8 @@ bool Network::connect(const ServerInfo &server) return false; } - logger->log("Network::Connecting to %s:%i", server.hostname.c_str(), - server.port); + Log::info("Network::Connecting to %s:%i", server.hostname.c_str(), + server.port); mServer.hostname = server.hostname; mServer.port = server.port; @@ -376,8 +376,7 @@ void Network::dispatchMessages() auto packetInfoIt = mPacketInfo.find(msgId); if (packetInfoIt == mPacketInfo.end()) { - auto error = strprintf("Unknown packet 0x%x received.", msgId); - logger->error(error); + Log::critical(strprintf("Unknown packet 0x%x received.", msgId)); break; } @@ -395,9 +394,8 @@ void Network::dispatchMessages() if (len < 4) { - auto error = strprintf("Variable length packet 0x%x has invalid length %d.", - msgId, len); - logger->error(error); + Log::critical(strprintf("Variable length packet 0x%x has invalid length %d.", + msgId, len)); break; } } @@ -413,14 +411,14 @@ void Network::dispatchMessages() if (iter != mMessageHandlers.end()) { #ifdef DEBUG - logger->log("Handling %s (0x%x) of length %d", packetInfo->name, msgId, len); + Log::info("Handling %s (0x%x) of length %d", packetInfo->name, msgId, len); #endif iter->second->handleMessage(message); } else { - logger->log("Unhandled %s (0x%x) of length %d", packetInfo->name, msgId, len); + Log::info("Unhandled %s (0x%x) of length %d", packetInfo->name, msgId, len); } skip(len); @@ -474,7 +472,7 @@ bool Network::realConnect() std::string errorMessage = strprintf(_("Unable to resolve host \"%s\""), mServer.hostname.c_str()); setError(errorMessage); - logger->log("SDLNet_ResolveHost: %s", errorMessage.c_str()); + Log::info("SDLNet_ResolveHost: %s", errorMessage.c_str()); return false; } @@ -483,13 +481,13 @@ bool Network::realConnect() mSocket = SDLNet_TCP_Open(&ipAddress); if (!mSocket) { - logger->log("Error in SDLNet_TCP_Open(): %s", SDLNet_GetError()); + Log::info("Error in SDLNet_TCP_Open(): %s", SDLNet_GetError()); setError(SDLNet_GetError()); return false; } - logger->log("Network::Started session with %s:%i", - ipToString(ipAddress.host), ipAddress.port); + Log::info("Network::Started session with %s:%i", + ipToString(ipAddress.host), ipAddress.port); mState = CONNECTED; @@ -522,7 +520,7 @@ void Network::receive() switch (numReady) { case -1: - logger->log("Error: SDLNet_CheckSockets"); + Log::error("SDLNet_CheckSockets"); // FALLTHROUGH case 0: break; @@ -537,7 +535,7 @@ void Network::receive() { // We got disconnected mState = IDLE; - logger->log("Disconnected."); + Log::info("Disconnected."); } else if (ret < 0) { @@ -578,7 +576,7 @@ void Network::receive() if (SDLNet_TCP_DelSocket(set, mSocket) == -1) { - logger->log("Error in SDLNet_DelSocket(): %s", SDLNet_GetError()); + Log::info("Error in SDLNet_DelSocket(): %s", SDLNet_GetError()); } SDLNet_FreeSocketSet(set); @@ -586,7 +584,7 @@ void Network::receive() void Network::setError(const std::string &error) { - logger->log("Network error: %s", error.c_str()); + Log::info("Network error: %s", error.c_str()); mError = error; mState = NET_ERROR; } diff --git a/src/net/tmwa/partyhandler.cpp b/src/net/tmwa/partyhandler.cpp index 2b256cd5..78dfd7a0 100644 --- a/src/net/tmwa/partyhandler.cpp +++ b/src/net/tmwa/partyhandler.cpp @@ -184,7 +184,7 @@ void PartyHandler::handleMessage(MessageIn &msg) partyTab->chatLog(_("Experience sharing not possible."), BY_SERVER); break; default: - logger->log("Unknown party exp option: %d", exp); + Log::info("Unknown party exp option: %d", exp); } switch (item) @@ -208,7 +208,7 @@ void PartyHandler::handleMessage(MessageIn &msg) partyTab->chatLog(_("Item sharing not possible."), BY_SERVER); break; default: - logger->log("Unknown party item option: %d", exp); + Log::info("Unknown party item option: %d", exp); } break; } diff --git a/src/net/tmwa/playerhandler.cpp b/src/net/tmwa/playerhandler.cpp index a5de7619..b16a2a82 100644 --- a/src/net/tmwa/playerhandler.cpp +++ b/src/net/tmwa/playerhandler.cpp @@ -186,7 +186,7 @@ void PlayerHandler::handleMessage(MessageIn &msg) int x = msg.readInt16(); int y = msg.readInt16(); - logger->log("Warping to %s (%d, %d)", mapPath.c_str(), x, y); + Log::info("Warping to %s (%d, %d)", mapPath.c_str(), x, y); /* * We must clear the local player's target *before* the call @@ -224,8 +224,8 @@ void PlayerHandler::handleMessage(MessageIn &msg) // Stop movement local_player->setDestination(pos.x, pos.y); - logger->log("Adjust scrolling by %d:%d", (int) scrollOffsetX, - (int) scrollOffsetY); + Log::info("Adjust scrolling by %d:%d", (int) scrollOffsetX, + (int) scrollOffsetY); viewport->scrollBy(scrollOffsetX, scrollOffsetY); } @@ -506,7 +506,7 @@ void PlayerHandler::handleMessage(MessageIn &msg) serverNotice(_("Equip arrows first.")); break; default: - logger->log("0x013b: Unhandled message %i", type); + Log::info("0x013b: Unhandled message %i", type); break; } } @@ -699,8 +699,8 @@ Vector PlayerHandler::getPixelsPerSecondMoveSpeed(const Vector &speed, Map *map) if (!map || speed.x == 0 || speed.y == 0) { - logger->log("TmwAthena::PlayerHandler: Speed set to default: " - "Map not yet initialized or invalid speed."); + Log::info("TmwAthena::PlayerHandler: Speed set to default: " + "Map not yet initialized or invalid speed."); return getDefaultMoveSpeed(); } diff --git a/src/openglgraphics.cpp b/src/openglgraphics.cpp index 180b16ec..667c91e8 100644 --- a/src/openglgraphics.cpp +++ b/src/openglgraphics.cpp @@ -91,8 +91,8 @@ OpenGLGraphics::OpenGLGraphics(SDL_Window *window, SDL_GLContext glContext) glGetIntegerv(GL_MAX_TEXTURE_SIZE, &texSize); } Image::mTextureSize = texSize; - logger->log("OpenGL texture size: %d pixels%s", Image::mTextureSize, - rectTex ? " (rectangle textures)" : ""); + Log::info("OpenGL texture size: %d pixels%s", Image::mTextureSize, + rectTex ? " (rectangle textures)" : ""); glMatrixMode(GL_TEXTURE); glLoadIdentity(); diff --git a/src/particle.cpp b/src/particle.cpp index cb79c86f..5051672b 100644 --- a/src/particle.cpp +++ b/src/particle.cpp @@ -74,7 +74,7 @@ void Particle::setupEngine() Particle::fastPhysics = config.particleFastPhysics; Particle::emitterSkip = config.particleEmitterSkip + 1; Particle::enabled = config.particleEffects; - logger->log("Particle engine set up"); + Log::info("Particle engine set up"); } bool Particle::draw(Graphics *, int, int) const @@ -261,7 +261,7 @@ Particle *Particle::addEffect(const std::string &particleEffectFile, if (!rootNode || rootNode.name() != "effect") { - logger->log("Error loading particle: %s", particleEffectFile.c_str()); + Log::info("Error loading particle: %s", particleEffectFile.c_str()); return nullptr; } diff --git a/src/particleemitter.cpp b/src/particleemitter.cpp index 4954d317..e898b2fb 100644 --- a/src/particleemitter.cpp +++ b/src/particleemitter.cpp @@ -179,9 +179,8 @@ ParticleEmitter::ParticleEmitter(XML::Node emitterNode, Particle *target, } else { - logger->log("Particle Engine: Warning, unknown emitter property \"%s\"", - name.c_str() - ); + Log::info("Particle Engine: Warning, unknown emitter property \"%s\"", + name.c_str()); } } else if (propertyNode.name() == "emitter") diff --git a/src/playerinfo.cpp b/src/playerinfo.cpp index a05ffaaa..a96471a5 100644 --- a/src/playerinfo.cpp +++ b/src/playerinfo.cpp @@ -287,8 +287,8 @@ void clearAbilityStatus(int id) void setAbilityStatus(int id, int current, int max, int recharge) { - logger->log("AbilityUpdate Skill #%d -- (%d/%d) -> %d", id, current, max, - recharge); + Log::info("AbilityUpdate Skill #%d -- (%d/%d) -> %d", id, current, max, + recharge); mAbilities[id].currentMana = current; mAbilities[id].neededMana = max; mAbilities[id].recharge = recharge; diff --git a/src/resources/abilitydb.cpp b/src/resources/abilitydb.cpp index 311ee9eb..cb596ea8 100644 --- a/src/resources/abilitydb.cpp +++ b/src/resources/abilitydb.cpp @@ -41,7 +41,7 @@ static AbilityInfo::TargetMode targetModeFromString(const std::string& str) if (str == "direction") return AbilityInfo::TARGET_DIRECTION; - logger->log("AbilityDB: Warning, unknown target mode \"%s\"", str.c_str() ); + Log::info("AbilityDB: Warning, unknown target mode \"%s\"", str.c_str() ); return AbilityInfo::TARGET_BEING; } @@ -68,7 +68,7 @@ void AbilityDB::readAbilityNode(XML::Node node, const std::string &filename) info->rechargeCurrent = 0; if (mAbilityInfos.find(id) != mAbilityInfos.end()) - logger->log("AbilityDB: Duplicate ability ID %d in %s, ignoring", id, filename.c_str()); + Log::info("AbilityDB: Duplicate ability ID %d in %s, ignoring", id, filename.c_str()); else mAbilityInfos[id] = info; } diff --git a/src/resources/animation.cpp b/src/resources/animation.cpp index 91c22236..c529400f 100644 --- a/src/resources/animation.cpp +++ b/src/resources/animation.cpp @@ -84,7 +84,7 @@ Animation Animation::fromXML(XML::Node node, const std::string &dyePalettes) if (index < 0) { - logger->log("No valid value for 'index'"); + Log::info("No valid value for 'index'"); continue; } @@ -92,7 +92,7 @@ Animation Animation::fromXML(XML::Node node, const std::string &dyePalettes) if (!img) { - logger->log("No image at index %d", index); + Log::info("No image at index %d", index); continue; } @@ -105,7 +105,7 @@ Animation Animation::fromXML(XML::Node node, const std::string &dyePalettes) if (start < 0 || end < 0) { - logger->log("No valid value for 'start' or 'end'"); + Log::info("No valid value for 'start' or 'end'"); continue; } @@ -115,7 +115,7 @@ Animation Animation::fromXML(XML::Node node, const std::string &dyePalettes) if (!img) { - logger->log("No image at index %d", start); + Log::info("No image at index %d", start); continue; } diff --git a/src/resources/attributes.cpp b/src/resources/attributes.cpp index 7ec6b516..5b1018ee 100644 --- a/src/resources/attributes.cpp +++ b/src/resources/attributes.cpp @@ -240,22 +240,22 @@ namespace Attributes { int id = node.getProperty("id", 0); if (!id) { - logger->log("Attributes: Invalid or missing stat ID in " - DEFAULT_ATTRIBUTESDB_FILE "!"); + Log::info("Attributes: Invalid or missing stat ID in " + DEFAULT_ATTRIBUTESDB_FILE "!"); return; } if (attributes.find(id) != attributes.end()) { - logger->log("Attributes: Redefinition of stat ID %d", id); + Log::info("Attributes: Redefinition of stat ID %d", id); } std::string name = node.getProperty("name", ""); if (name.empty()) { - logger->log("Attributes: Invalid or missing stat name in " - DEFAULT_ATTRIBUTESDB_FILE "!"); + Log::info("Attributes: Invalid or missing stat name in " + DEFAULT_ATTRIBUTESDB_FILE "!"); return; } @@ -280,10 +280,10 @@ namespace Attributes { { if (name.empty()) { - logger->log("Attribute modifier in attribute %u:%s: " - "Empty name definition " - "on empty tag definition, skipping.", - a.id, a.name.c_str()); + Log::info("Attribute modifier in attribute %u:%s: " + "Empty name definition " + "on empty tag definition, skipping.", + a.id, a.name.c_str()); --count; continue; } @@ -296,10 +296,10 @@ namespace Attributes { { if (name.empty()) { - logger->log("Attribute modifier in attribute %u:%s: " - "Empty name definition " - "on empty effect definition, skipping.", - a.id, a.name.c_str()); + Log::info("Attribute modifier in attribute %u:%s: " + "Empty name definition " + "on empty effect definition, skipping.", + a.id, a.name.c_str()); --count; continue; } @@ -308,7 +308,7 @@ namespace Attributes { } tags.insert(std::make_pair(tag, effect)); } - logger->log("Found %d tags for attribute %d.", count, id); + Log::info("Found %d tags for attribute %d.", count, id); } /** @@ -321,8 +321,8 @@ namespace Attributes { DEFAULT_MIN_PTS); attributeMaximum = node.getProperty("maximum", DEFAULT_MAX_PTS); - logger->log("Loaded points: start: %i, min: %i, max: %i.", - creationPoints, attributeMinimum, attributeMaximum); + Log::info("Loaded points: start: %i, min: %i, max: %i.", + creationPoints, attributeMinimum, attributeMaximum); } /** @@ -330,8 +330,8 @@ namespace Attributes { */ void checkStatus() { - logger->log("Found %d tags for %d attributes.", int(tags.size()), - int(attributes.size())); + Log::info("Found %d tags for %d attributes.", int(tags.size()), + int(attributes.size())); if (attributes.size() == 0) { @@ -346,9 +346,9 @@ namespace Attributes { if (averageValue > attributeMaximum || averageValue < attributeMinimum || creationPoints < 1) { - logger->log("Attributes: Character's point values make " - "the character's creation impossible. " - "Switch back to defaults."); + Log::info("Attributes: Character's point values make " + "the character's creation impossible. " + "Switch back to defaults."); creationPoints = DEFAULT_POINTS; attributeMinimum = DEFAULT_MIN_PTS; attributeMaximum = DEFAULT_MAX_PTS; diff --git a/src/resources/beinginfo.cpp b/src/resources/beinginfo.cpp index 20c24d4f..f2edf1d8 100644 --- a/src/resources/beinginfo.cpp +++ b/src/resources/beinginfo.cpp @@ -73,8 +73,8 @@ void BeingInfo::setTargetCursorSize(const std::string &size) const auto cursorSize = targetCursorSizeFromString(size); if (!cursorSize) { - logger->log("Unknown targetCursor value \"%s\" for %s", - size.c_str(), name.c_str()); + Log::info("Unknown targetCursor value \"%s\" for %s", + size.c_str(), name.c_str()); } targetCursorSize = cursorSize.value_or(ActorSprite::TC_MEDIUM); } @@ -84,8 +84,8 @@ void BeingInfo::setHoverCursor(const std::string &cursorName) const auto cursor = cursorFromString(cursorName); if (!cursor) { - logger->log("Unknown hoverCursor value \"%s\" for %s", - cursorName.c_str(), name.c_str()); + Log::info("Unknown hoverCursor value \"%s\" for %s", + cursorName.c_str(), name.c_str()); } hoverCursor = cursor.value_or(Cursor::Pointer); } diff --git a/src/resources/chardb.cpp b/src/resources/chardb.cpp index 9001b6c2..97f86d3a 100644 --- a/src/resources/chardb.cpp +++ b/src/resources/chardb.cpp @@ -54,7 +54,7 @@ void CharDB::load() if (!root || root.name() != "chars") { - logger->log("CharDB: Failed to parse charcreation.xml."); + Log::info("CharDB: Failed to parse charcreation.xml."); return; } @@ -86,7 +86,7 @@ void CharDB::load() void CharDB::unload() { - logger->log("Unloading chars database..."); + Log::info("Unloading chars database..."); mLoaded = false; } diff --git a/src/resources/dye.cpp b/src/resources/dye.cpp index 0ecc9fd6..136c9334 100644 --- a/src/resources/dye.cpp +++ b/src/resources/dye.cpp @@ -63,8 +63,8 @@ DyePalette::DyePalette(const std::string &description) } else { - logger->log("Error, invalid embedded palette: %s", - description.c_str()); + Log::info("Error, invalid embedded palette: %s", + description.c_str()); return; } @@ -82,7 +82,7 @@ DyePalette::DyePalette(const std::string &description) ++pos; } - logger->log("Error, invalid embedded palette: %s", description.c_str()); + Log::info("Error, invalid embedded palette: %s", description.c_str()); } void DyePalette::getColor(int intensity, int color[3]) const @@ -195,7 +195,7 @@ Dye::Dye(const std::string &description) if (next_pos <= pos + 3 || description[pos + 1] != ':') { - logger->log("Error, invalid dye: %s", description.c_str()); + Log::info("Error, invalid dye: %s", description.c_str()); return; } @@ -211,7 +211,7 @@ Dye::Dye(const std::string &description) case 'C': i = 5; break; case 'W': i = 6; break; default: - logger->log("Error, invalid dye: %s", description.c_str()); + Log::info("Error, invalid dye: %s", description.c_str()); return; } mDyePalettes[i] = new DyePalette(description.substr(pos + 2, @@ -289,7 +289,7 @@ void Dye::instantiate(std::string &target, const std::string &palettes) } else { - logger->log("Error, invalid dye placeholder: %s", target.c_str()); + Log::info("Error, invalid dye placeholder: %s", target.c_str()); return; } s << target[next_pos]; diff --git a/src/resources/emotedb.cpp b/src/resources/emotedb.cpp index d29483d1..c0f5f777 100644 --- a/src/resources/emotedb.cpp +++ b/src/resources/emotedb.cpp @@ -51,7 +51,7 @@ void EmoteDB::readEmoteNode(XML::Node node, const std::string &filename) const int id = node.getProperty("id", -1); if (id == -1) { - logger->log("Emote Database: Emote with missing ID in %s!", filename.c_str()); + Log::info("Emote Database: Emote with missing ID in %s!", filename.c_str()); return; } @@ -63,8 +63,8 @@ void EmoteDB::readEmoteNode(XML::Node node, const std::string &filename) if (emote.effectId == -1) { - logger->log("Emote Database: Warning: Emote %s has no attached effect in %s!", - emote.name.c_str(), filename.c_str()); + Log::info("Emote Database: Warning: Emote %s has no attached effect in %s!", + emote.name.c_str(), filename.c_str()); return; } @@ -74,8 +74,8 @@ void EmoteDB::readEmoteNode(XML::Node node, const std::string &filename) if (imageName.empty() || width <= 0 || height <= 0) { - logger->log("Emote Database: Warning: Emote %s has bad imageset values in %s", - emote.name.c_str(), filename.c_str()); + Log::info("Emote Database: Warning: Emote %s has bad imageset values in %s", + emote.name.c_str(), filename.c_str()); return; } @@ -85,8 +85,8 @@ void EmoteDB::readEmoteNode(XML::Node node, const std::string &filename) if (!emote.is || emote.is->size() == 0) { - logger->log("Emote Database: Error loading imageset for emote %s in %s", - emote.name.c_str(), filename.c_str()); + Log::info("Emote Database: Error loading imageset for emote %s in %s", + emote.name.c_str(), filename.c_str()); return; } @@ -119,7 +119,7 @@ const Emote &EmoteDB::get(int id) if (i == mEmotes.end()) { - logger->log("EmoteDB: Warning, unknown emote ID %d requested", id); + Log::info("EmoteDB: Warning, unknown emote ID %d requested", id); return mUnknown; } diff --git a/src/resources/hairdb.cpp b/src/resources/hairdb.cpp index 6b88a4df..312188d6 100644 --- a/src/resources/hairdb.cpp +++ b/src/resources/hairdb.cpp @@ -40,7 +40,7 @@ void HairDB::readHairColorNode(XML::Node node, const std::string &filename) int id = node.getProperty("id", 0); if (mHairColors.find(id) != mHairColors.end()) - logger->log("HairDb: Redefinition of color Id %d in %s", id, filename.c_str()); + Log::info("HairDb: Redefinition of color Id %d in %s", id, filename.c_str()); mHairColors[id] = node.getProperty("value", COLOR_WHITE); } @@ -55,7 +55,7 @@ void HairDB::unload() if (!mLoaded) return; - logger->log("Unloading hair style and color database..."); + Log::info("Unloading hair style and color database..."); mHairColors.clear(); mHairStyles.clear(); @@ -71,7 +71,7 @@ void HairDB::addHairStyle(int id) id = -id; if (mHairStyles.find(id) != mHairStyles.end()) - logger->log("Warning: Redefinition of hairstyle id %i:", id); + Log::warn("Redefinition of hairstyle id %i:", id); mHairStyles.insert(id); } @@ -81,13 +81,13 @@ const std::string &HairDB::getHairColor(int id) const if (!mLoaded) { // no idea if this can happen, but that check existed before - logger->log("WARNING: HairDB::getHairColor() called before settings were loaded!"); + Log::warn("HairDB::getHairColor() called before settings were loaded!"); } auto it = mHairColors.find(id); if (it != mHairColors.end()) return it->second; - logger->log("HairDb: Error, unknown color Id# %d", id); + Log::info("HairDb: Error, unknown color Id# %d", id); return mHairColors.at(0); } diff --git a/src/resources/image.cpp b/src/resources/image.cpp index b36aea01..11d5c275 100644 --- a/src/resources/image.cpp +++ b/src/resources/image.cpp @@ -54,8 +54,7 @@ Image::Image(SDL_Texture *texture, int width, int height): if (!texture) { - logger->log( - "Image::Image(SDL_Texture*, ...): Couldn't load invalid Surface!"); + Log::info("Image::Image(SDL_Texture*, ...): Couldn't load invalid Surface!"); } } @@ -72,8 +71,7 @@ Image::Image(GLuint glimage, int width, int height, int texWidth, int texHeight) if (glimage == 0) { - logger->log( - "Image::Image(GLuint, ...): Couldn't load invalid Surface!"); + Log::info("Image::Image(GLuint, ...): Couldn't load invalid Surface!"); } } #endif @@ -101,7 +99,7 @@ Resource *Image::load(SDL_RWops *rw) if (!tmpImage) { - logger->log("Error, image load failed: %s", IMG_GetError()); + Log::info("Error, image load failed: %s", IMG_GetError()); return nullptr; } @@ -117,20 +115,20 @@ Resource *Image::load(SDL_RWops *rw, const Dye &dye) if (!surf) { - logger->log("Error, image load failed: %s", IMG_GetError()); + Log::info("Error, image load failed: %s", IMG_GetError()); return nullptr; } if (surf->format->format != SDL_PIXELFORMAT_RGBA32) { - logger->log("Warning: image format is %s, not SDL_PIXELFORMAT_RGBA32. Converting...", - SDL_GetPixelFormatName(surf->format->format)); + Log::warn("Image format is %s, not SDL_PIXELFORMAT_RGBA32. Converting...", + SDL_GetPixelFormatName(surf->format->format)); SDL_Surface *convertedSurf = SDL_ConvertSurfaceFormat(surf, SDL_PIXELFORMAT_RGBA32, 0); SDL_FreeSurface(surf); if (!convertedSurf) { - logger->log("Error, image convert failed: %s", SDL_GetError()); + Log::info("Error, image convert failed: %s", SDL_GetError()); return nullptr; } surf = convertedSurf; @@ -219,8 +217,8 @@ Image *Image::_GLload(SDL_Surface *image) if (realWidth < width || realHeight < height) { - logger->log("Warning: image too large, cropping to %dx%d texture!", - realWidth, realHeight); + Log::warn("Image too large, cropping to %dx%d texture!", + realWidth, realHeight); } // Determine 32-bit masks based on byte order @@ -253,7 +251,7 @@ Image *Image::_GLload(SDL_Surface *image) if (!image) { - logger->log("Error, image convert failed: out of memory"); + Log::info("Error, image convert failed: out of memory"); return nullptr; } @@ -308,7 +306,7 @@ Image *Image::_GLload(SDL_Surface *image) errmsg = "GL_OUT_OF_MEMORY"; break; } - logger->log("Error: Image GL import failed: %s", errmsg); + Log::error("Image GL import failed: %s", errmsg); return nullptr; } diff --git a/src/resources/imageset.cpp b/src/resources/imageset.cpp index 34cf1fd8..1f194b4f 100644 --- a/src/resources/imageset.cpp +++ b/src/resources/imageset.cpp @@ -50,7 +50,7 @@ Image *ImageSet::get(size_t i) const { if (i >= mImages.size()) { - logger->log("Warning: No sprite %d in this image set", (int) i); + Log::warn("No sprite %d in this image set", (int) i); return nullptr; } diff --git a/src/resources/imagewriter.cpp b/src/resources/imagewriter.cpp index ddf1fbee..cf4c6803 100644 --- a/src/resources/imagewriter.cpp +++ b/src/resources/imagewriter.cpp @@ -42,7 +42,7 @@ bool ImageWriter::writePNG(SDL_Surface *surface, const std::string &filename) png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr); if (!png_ptr) { - logger->log("Had trouble creating png_structp"); + Log::info("Had trouble creating png_structp"); return false; } @@ -50,21 +50,21 @@ bool ImageWriter::writePNG(SDL_Surface *surface, const std::string &filename) if (!info_ptr) { png_destroy_write_struct(&png_ptr, (png_infopp)nullptr); - logger->log("Could not create png_info"); + Log::info("Could not create png_info"); return false; } if (setjmp(png_jmpbuf(png_ptr))) { png_destroy_write_struct(&png_ptr, (png_infopp)nullptr); - logger->log("problem writing to %s", filename.c_str()); + Log::info("problem writing to %s", filename.c_str()); return false; } FILE *fp = fopen(filename.c_str(), "wb"); if (!fp) { - logger->log("could not open file %s for writing", filename.c_str()); + Log::info("could not open file %s for writing", filename.c_str()); return false; } @@ -83,7 +83,7 @@ bool ImageWriter::writePNG(SDL_Surface *surface, const std::string &filename) row_pointers = new png_bytep[surface->h]; if (!row_pointers) { - logger->log("Had trouble converting surface to row pointers"); + Log::info("Had trouble converting surface to row pointers"); fclose(fp); return false; } diff --git a/src/resources/itemdb.cpp b/src/resources/itemdb.cpp index 05f6ad0b..1d217fc2 100644 --- a/src/resources/itemdb.cpp +++ b/src/resources/itemdb.cpp @@ -148,7 +148,7 @@ const ItemInfo &ItemDB::get(int id) const auto i = mItemInfos.find(id); if (i == mItemInfos.end()) { - logger->log("ItemDB: Warning, unknown item ID# %d", id); + Log::info("ItemDB: Warning, unknown item ID# %d", id); return *mUnknown; } @@ -164,8 +164,8 @@ const ItemInfo &ItemDB::get(const std::string &name) const { if (!name.empty()) { - logger->log("ItemDB: Warning, unknown item name \"%s\"", - name.c_str()); + Log::info("ItemDB: Warning, unknown item name \"%s\"", + name.c_str()); } return *mUnknown; } @@ -202,8 +202,8 @@ void ItemDB::loadSoundRef(ItemInfo &itemInfo, XML::Node node) } else { - logger->log("ItemDB: Ignoring unknown sound event '%s'", - event.c_str()); + Log::info("ItemDB: Ignoring unknown sound event '%s'", + event.c_str()); } } @@ -237,15 +237,15 @@ void ItemDB::loadReplacement(ItemInfo &info, XML::Node replaceNode) if (sprite == SPRITE_UNKNOWN) { - logger->log("ItemDB: Invalid sprite name '%s' in replace tag", - spriteString.data()); + Log::info("ItemDB: Invalid sprite name '%s' in replace tag", + spriteString.data()); return; } if (direction == DIRECTION_UNKNOWN) { - logger->log("ItemDB: Invalid direction name '%s' in replace tag", - directionString.data()); + Log::info("ItemDB: Invalid direction name '%s' in replace tag", + directionString.data()); return; } @@ -266,7 +266,7 @@ void ItemDB::loadReplacement(ItemInfo &info, XML::Node replaceNode) void ItemDB::unload() { - logger->log("Unloading item database..."); + Log::info("Unloading item database..."); delete mUnknown; mUnknown = nullptr; @@ -283,12 +283,12 @@ void ItemDB::loadCommonRef(ItemInfo &itemInfo, XML::Node node, const std::string if (!itemInfo.id) { - logger->log("ItemDB: Invalid or missing item Id in %s!", filename.c_str()); + Log::info("ItemDB: Invalid or missing item Id in %s!", filename.c_str()); return; } else if (mItemInfos.find(itemInfo.id) != mItemInfos.end()) { - logger->log("ItemDB: Redefinition of item Id %d in %s", itemInfo.id, filename.c_str()); + Log::info("ItemDB: Redefinition of item Id %d in %s", itemInfo.id, filename.c_str()); } itemInfo.mView = node.getProperty("view", 0); @@ -346,8 +346,8 @@ void ItemDB::addItem(ItemInfo *itemInfo) if (itr == mNamedItemInfos.end()) mNamedItemInfos[temp] = itemInfo; else - logger->log("ItemDB: Duplicate name (%s) for item id %d found.", - temp.c_str(), itemInfo->id); + Log::info("ItemDB: Duplicate name (%s) for item id %d found.", + temp.c_str(), itemInfo->id); } } @@ -359,7 +359,7 @@ static void checkParameter(int id, const T param, const T errorValue) std::stringstream errMsg; errMsg << "ItemDB: Missing " << param << " attribute for item id " << id << "!"; - logger->log("%s", errMsg.str().c_str()); + Log::info("%s", errMsg.str().c_str()); } } @@ -368,7 +368,7 @@ void ItemDB::checkItemInfo(ItemInfo &itemInfo) int id = itemInfo.id; if (!itemInfo.attackAction.empty()) if (itemInfo.attackRange == 0) - logger->log("ItemDB: Missing attack range from weapon %i!", id); + Log::info("ItemDB: Missing attack range from weapon %i!", id); if (id >= 0) { @@ -504,7 +504,7 @@ void ManaServItemDB::readItemNode(XML::Node node, const std::string &filename) std::string trigger = itemChild.getProperty("trigger", std::string()); if (trigger.empty()) { - logger->log("Found empty trigger effect label in %s, skipping.", filename.c_str()); + Log::info("Found empty trigger effect label in %s, skipping.", filename.c_str()); continue; } @@ -514,8 +514,8 @@ void ManaServItemDB::readItemNode(XML::Node node, const std::string &filename) auto triggerLabel = triggerTable.find(trigger); if (triggerLabel == triggerTable.end()) { - logger->log("Warning: unknown trigger %s in item %d!", - trigger.c_str(), itemInfo->id); + Log::warn("Unknown trigger %s in item %d!", + trigger.c_str(), itemInfo->id); continue; } @@ -528,7 +528,7 @@ void ManaServItemDB::readItemNode(XML::Node node, const std::string &filename) int duration = effectChild.getProperty("duration", 0); if (attribute.empty() || !value) { - logger->log("Warning: incomplete modifier definition in %s, skipping.", filename.c_str()); + Log::warn("Incomplete modifier definition in %s, skipping.", filename.c_str()); continue; } auto it = extraStats.cbegin(); @@ -537,7 +537,7 @@ void ManaServItemDB::readItemNode(XML::Node node, const std::string &filename) ++it; if (it == extraStats.end()) { - logger->log("Warning: unknown modifier tag %s in %s, skipping.", attribute.c_str(), filename.c_str()); + Log::warn("Unknown modifier tag %s in %s, skipping.", attribute.c_str(), filename.c_str()); continue; } effect.push_back( diff --git a/src/resources/mapreader.cpp b/src/resources/mapreader.cpp index b952cdcc..3ca5763c 100644 --- a/src/resources/mapreader.cpp +++ b/src/resources/mapreader.cpp @@ -77,7 +77,7 @@ static std::string resolveRelativePath(std::string base, std::string relative) Map *MapReader::readMap(const std::string &filename) { - logger->log("Attempting to read map %s", filename.c_str()); + Log::info("Attempting to read map %s", filename.c_str()); Map *map = nullptr; XML::Document doc(filename); @@ -89,7 +89,7 @@ Map *MapReader::readMap(const std::string &filename) { if (node.name() != "map") { - logger->log("Error: Not a map file (%s)!", filename.c_str()); + Log::error("Not a map file (%s)!", filename.c_str()); } else { @@ -98,7 +98,7 @@ Map *MapReader::readMap(const std::string &filename) } else { - logger->log("Error while parsing map file (%s)!", filename.c_str()); + Log::info("Error while parsing map file (%s)!", filename.c_str()); } if (map) @@ -119,9 +119,9 @@ Map *MapReader::readMap(XML::Node node, const std::string &path) if (tilew < 0 || tileh < 0) { - logger->log("MapReader: Warning: " - "Unitialized tile width or height value for map: %s", - path.c_str()); + Log::info("MapReader: Warning: " + "Unitialized tile width or height value for map: %s", + path.c_str()); return nullptr; } @@ -174,15 +174,15 @@ Map *MapReader::readMap(XML::Node node, const std::string &path) const int objW = objectNode.getProperty("width", 0); const int objH = objectNode.getProperty("height", 0); - logger->log("- Loading object name: %s type: %s at %d:%d", - objName.c_str(), objType.c_str(), - objX, objY); + Log::info("- Loading object name: %s type: %s at %d:%d", + objName.c_str(), objType.c_str(), + objX, objY); if (objType == "PARTICLE_EFFECT") { if (objName.empty()) { - logger->log(" Warning: No particle file given"); + Log::info(" Warning: No particle file given"); continue; } @@ -203,7 +203,7 @@ Map *MapReader::readMap(XML::Node node, const std::string &path) } else { - logger->log(" Warning: Unknown object type"); + Log::info(" Warning: Unknown object type"); } } } @@ -293,7 +293,7 @@ static void readLayer(XML::Node node, Map *map) map->addLayer(layer); } - logger->log("- Loading layer \"%s\"", name.c_str()); + Log::info("- Loading layer \"%s\"", name.c_str()); int x = 0; int y = 0; @@ -333,8 +333,8 @@ static void readLayer(XML::Node node, Map *map) if (!compression.empty() && compression != "gzip" && compression != "zlib") { - logger->log("Warning: only gzip or zlib layer " - "compression supported!"); + Log::warn("Only gzip or zlib layer " + "compression supported!"); return; } @@ -383,7 +383,7 @@ static void readLayer(XML::Node node, Map *map) if (!inflated) { - logger->log("Error: Could not decompress layer!"); + Log::error("Could not decompress layer!"); return; } } @@ -415,7 +415,7 @@ static void readLayer(XML::Node node, Map *map) const auto data = childNode.textContent(); if (data.empty()) { - logger->log("Error: CSV layer data is empty!"); + Log::error("CSV layer data is empty!"); continue; } @@ -432,7 +432,7 @@ static void readLayer(XML::Node node, Map *map) if (errno == ERANGE) { - logger->log("Error: Range error in tile layer data!"); + Log::error("Range error in tile layer data!"); break; } @@ -452,7 +452,7 @@ static void readLayer(XML::Node node, Map *map) pos = strchr(end, ','); if (!pos) { - logger->log("Error: CSV layer data too short!"); + Log::error("CSV layer data too short!"); break; } ++pos; @@ -536,8 +536,7 @@ static Tileset *readTileset(XML::Node node, const std::string &path, } else { - logger->log("Warning: Failed to load tileset (%s)", - source.c_str()); + Log::warn("Failed to load tileset (%s)", source.c_str()); } } } diff --git a/src/resources/monsterdb.cpp b/src/resources/monsterdb.cpp index 4963f93f..7f092a0e 100644 --- a/src/resources/monsterdb.cpp +++ b/src/resources/monsterdb.cpp @@ -111,11 +111,11 @@ void MonsterDB::readMonsterNode(XML::Node node, const std::string &filename) } else { - logger->log("MonsterDB: Warning, sound effect %s for " - "unknown event %s of monster %s in %s", - soundFile.c_str(), event.c_str(), - currentInfo->name.c_str(), - filename.c_str()); + Log::info("MonsterDB: Warning, sound effect %s for " + "unknown event %s of monster %s in %s", + soundFile.c_str(), event.c_str(), + currentInfo->name.c_str(), + filename.c_str()); } } else if (spriteNode.name() == "attack") @@ -168,7 +168,7 @@ BeingInfo *MonsterDB::get(int id) if (i == mMonsterInfos.end()) { - logger->log("MonsterDB: Warning, unknown monster ID %d requested", id); + Log::info("MonsterDB: Warning, unknown monster ID %d requested", id); return BeingInfo::Unknown; } diff --git a/src/resources/music.cpp b/src/resources/music.cpp index 069af588..b73d89ce 100644 --- a/src/resources/music.cpp +++ b/src/resources/music.cpp @@ -40,7 +40,7 @@ Music *Music::load(SDL_RWops *rw) return new Music(music); } - logger->log("Error, failed to load music: %s", Mix_GetError()); + Log::info("Error, failed to load music: %s", Mix_GetError()); return nullptr; } diff --git a/src/resources/npcdb.cpp b/src/resources/npcdb.cpp index 6b1c3150..44292525 100644 --- a/src/resources/npcdb.cpp +++ b/src/resources/npcdb.cpp @@ -46,7 +46,7 @@ void NPCDB::readNPCNode(XML::Node node, const std::string &filename) int id = node.getProperty("id", 0); if (id == 0) { - logger->log("NPC Database: NPC with missing ID in %s", filename.c_str()); + Log::info("NPC Database: NPC with missing ID in %s", filename.c_str()); return; } @@ -94,7 +94,7 @@ BeingInfo *NPCDB::get(int id) if (i == mNPCInfos.end()) { - logger->log("NPCDB: Warning, unknown NPC ID %d requested", id); + Log::info("NPCDB: Warning, unknown NPC ID %d requested", id); return BeingInfo::Unknown; } diff --git a/src/resources/questdb.cpp b/src/resources/questdb.cpp index b2b8402e..a3dda637 100644 --- a/src/resources/questdb.cpp +++ b/src/resources/questdb.cpp @@ -57,7 +57,7 @@ void readQuestVarNode(XML::Node node, const std::string &filename) if (effect.map.empty() || effect.npcId == 0 || effect.statusEffectId == 0 || effect.values.empty()) { - logger->log("Warning: effect node for var %d is missing required attributes", varId); + Log::warn("effect node for var %d is missing required attributes", varId); } } else if (child.name() == "quest") @@ -70,8 +70,8 @@ void readQuestVarNode(XML::Node node, const std::string &filename) if (state.incomplete.empty() && state.complete.empty()) { - logger->log("Warning: quest node for var %d ('%s') has neither 'complete' nor 'incomplete' values", - varId, state.name.c_str()); + Log::warn("quest node for var %d ('%s') has neither 'complete' nor 'incomplete' values", + varId, state.name.c_str()); continue; } @@ -93,8 +93,8 @@ void readQuestVarNode(XML::Node node, const std::string &filename) rowType = QuestRowType::NPC; else { - logger->log("Warning: unknown quest row type '%s' for var %d ('%s')", - tag.data(), varId, state.name.c_str()); + Log::warn("unknown quest row type '%s' for var %d ('%s')", + tag.data(), varId, state.name.c_str()); continue; } diff --git a/src/resources/resource.cpp b/src/resources/resource.cpp index cdff8060..17864cf5 100644 --- a/src/resources/resource.cpp +++ b/src/resources/resource.cpp @@ -31,7 +31,7 @@ void Resource::decRef(OrphanPolicy orphanPolicy) { // Reference may not already have reached zero if (mRefCount == 0) { - logger->log("Warning: mRefCount already zero for %s", mIdPath.c_str()); + Log::warn("mRefCount already zero for %s", mIdPath.c_str()); assert(false); } diff --git a/src/resources/resourcemanager.cpp b/src/resources/resourcemanager.cpp index e62407e3..2857c0df 100644 --- a/src/resources/resourcemanager.cpp +++ b/src/resources/resourcemanager.cpp @@ -45,7 +45,7 @@ ResourceManager *ResourceManager::instance = nullptr; ResourceManager::ResourceManager() { - logger->log("Initializing resource manager..."); + Log::info("Initializing resource manager..."); } ResourceManager::~ResourceManager() @@ -86,11 +86,11 @@ void ResourceManager::cleanUp(Resource *res) { if (res->mRefCount > 0) { - logger->log("ResourceManager::~ResourceManager() cleaning up %d " - "reference%s to %s", - res->mRefCount, - (res->mRefCount == 1) ? "" : "s", - res->mIdPath.c_str()); + Log::info("ResourceManager::~ResourceManager() cleaning up %d " + "reference%s to %s", + res->mRefCount, + (res->mRefCount == 1) ? "" : "s", + res->mIdPath.c_str()); } delete res; @@ -118,7 +118,7 @@ void ResourceManager::cleanOrphans() } else { - logger->log("ResourceManager::release(%s)", res->mIdPath.c_str()); + Log::info("ResourceManager::release(%s)", res->mIdPath.c_str()); iter = mOrphanedResources.erase(iter); delete res; // delete only after removal from list, to avoid issues in recursion } @@ -129,12 +129,12 @@ void ResourceManager::cleanOrphans() bool ResourceManager::addToSearchPath(const std::string &path, bool append) { - logger->log("Adding to PhysicsFS: %s", path.c_str()); if (!FS::addToSearchPath(path, append)) { - logger->log("Error: %s", FS::getLastError()); + Log::error("Couldn't add search path: %s (%s)", path.c_str(), FS::getLastError()); return false; } + Log::info("Added search path: %s", path.c_str()); return true; } diff --git a/src/resources/settingsmanager.cpp b/src/resources/settingsmanager.cpp index 3630f64f..eabd63ae 100644 --- a/src/resources/settingsmanager.cpp +++ b/src/resources/settingsmanager.cpp @@ -109,7 +109,7 @@ namespace SettingsManager */ static bool loadFile(const std::string &filename) { - logger->log("Loading game settings from %s", filename.c_str()); + Log::info("Loading game settings from %s", filename.c_str()); XML::Document doc(filename); XML::Node node = doc.rootNode(); @@ -120,7 +120,7 @@ namespace SettingsManager // FIXME: check root node's name when bjorn decides it's time if (!node /*|| node.name() != "settings" */) { - logger->log("Settings Manager: %s is not a valid settings file!", filename.c_str()); + Log::info("Settings Manager: %s is not a valid settings file!", filename.c_str()); return false; } @@ -158,7 +158,7 @@ namespace SettingsManager // check if we're not entering a loop if (mIncludedFiles.find(includeFile) != mIncludedFiles.end()) { - logger->log("Warning: Circular include loop detecting while including %s from %s", includeFile.c_str(), filename.c_str()); + Log::warn("Circular include loop detecting while including %s from %s", includeFile.c_str(), filename.c_str()); } else { @@ -167,7 +167,7 @@ namespace SettingsManager } else { - logger->log("Warning: <include> element without 'file' or 'name' attribute in %s", filename.c_str()); + Log::warn("<include> element without 'file' or 'name' attribute in %s", filename.c_str()); } } else if (childNode.name() == "option") @@ -179,7 +179,7 @@ namespace SettingsManager if (!name.empty()) paths.setValue(name, value); else - logger->log("Warning: option without a name found in %s", filename.c_str()); + Log::warn("option without a name found in %s", filename.c_str()); } else if (childNode.name() == "attribute") { diff --git a/src/resources/soundeffect.cpp b/src/resources/soundeffect.cpp index 19d7a820..1b0492d7 100644 --- a/src/resources/soundeffect.cpp +++ b/src/resources/soundeffect.cpp @@ -36,7 +36,7 @@ SoundEffect *SoundEffect::load(SDL_RWops *rw) return new SoundEffect(soundEffect); } - logger->log("Error, failed to load sound effect: %s", Mix_GetError()); + Log::info("Error, failed to load sound effect: %s", Mix_GetError()); return nullptr; } diff --git a/src/resources/spritedef.cpp b/src/resources/spritedef.cpp index 85e5e566..0e7f12dd 100644 --- a/src/resources/spritedef.cpp +++ b/src/resources/spritedef.cpp @@ -44,7 +44,7 @@ Action *SpriteDef::getAction(const std::string &action) const if (i == mActions.end()) { - logger->log("Warning: no action \"%s\" defined!", action.c_str()); + Log::warn("No action \"%s\" defined!", action.c_str()); return nullptr; } @@ -66,7 +66,7 @@ SpriteDef *SpriteDef::load(const std::string &animationFile, int variant) if (!rootNode || rootNode.name() != "sprite") { - logger->log("Error, failed to parse %s", animationFile.c_str()); + Log::info("Error, failed to parse %s", animationFile.c_str()); std::string errorFile = paths.getStringValue("sprites") + paths.getStringValue("spriteErrorFile"); @@ -157,7 +157,7 @@ void SpriteDef::loadImageSet(XML::Node node, const std::string &palettes) auto imageSet = resman->getImageSet(imageSrc, width, height); if (!imageSet) { - logger->error(strprintf("Couldn't load imageset (%s)!", + Log::critical(strprintf("Couldn't load imageset (%s)!", imageSrc.c_str())); } @@ -174,16 +174,16 @@ void SpriteDef::loadAction(XML::Node node, int variant_offset) auto si = mImageSets.find(imageSetName); if (si == mImageSets.end()) { - logger->log("Warning: imageset \"%s\" not defined in %s", - imageSetName.c_str(), getIdPath().c_str()); + Log::warn("imageset \"%s\" not defined in %s", + imageSetName.c_str(), getIdPath().c_str()); return; } ImageSet *imageSet = si->second; if (actionName == SpriteAction::INVALID) { - logger->log("Warning: Unknown action \"%s\" defined in %s", - actionName.c_str(), getIdPath().c_str()); + Log::warn("Unknown action \"%s\" defined in %s", + actionName.c_str(), getIdPath().c_str()); return; } auto *action = new Action; @@ -215,8 +215,8 @@ void SpriteDef::loadAnimation(XML::Node animationNode, if (directionType == DIRECTION_INVALID) { - logger->log("Warning: Unknown direction \"%s\" used in %s", - directionName.c_str(), getIdPath().c_str()); + Log::warn("Unknown direction \"%s\" used in %s", + directionName.c_str(), getIdPath().c_str()); return; } @@ -239,7 +239,7 @@ void SpriteDef::loadAnimation(XML::Node animationNode, if (index < 0) { - logger->log("No valid value for 'index'"); + Log::info("No valid value for 'index'"); continue; } @@ -247,7 +247,7 @@ void SpriteDef::loadAnimation(XML::Node animationNode, if (!img) { - logger->log("No image at index %d", index + variant_offset); + Log::info("No image at index %d", index + variant_offset); continue; } @@ -260,7 +260,7 @@ void SpriteDef::loadAnimation(XML::Node animationNode, if (start < 0 || end < 0) { - logger->log("No valid value for 'start' or 'end'"); + Log::info("No valid value for 'start' or 'end'"); continue; } @@ -270,7 +270,7 @@ void SpriteDef::loadAnimation(XML::Node animationNode, if (!img) { - logger->log("No image at index %d", start + variant_offset); + Log::info("No image at index %d", start + variant_offset); break; } @@ -295,8 +295,8 @@ void SpriteDef::includeSprite(XML::Node includeNode) if (processedFiles.find(filename) != processedFiles.end()) { - logger->log("Error, Tried to include %s which already is included.", - filename.c_str()); + Log::info("Error, Tried to include %s which already is included.", + filename.c_str()); return; } processedFiles.insert(filename); @@ -306,7 +306,7 @@ void SpriteDef::includeSprite(XML::Node includeNode) if (!rootNode || rootNode.name() != "sprite") { - logger->log("Error, no sprite root node in %s", filename.c_str()); + Log::info("Error, no sprite root node in %s", filename.c_str()); return; } diff --git a/src/resources/theme.cpp b/src/resources/theme.cpp index 8e4a07be..f11a5036 100644 --- a/src/resources/theme.cpp +++ b/src/resources/theme.cpp @@ -75,7 +75,7 @@ ThemeInfo::ThemeInfo(const std::string &path) if (rootNode.attribute("name", name) && !name.empty()) this->doc = std::move(doc); else - logger->log("Error: Theme '%s' has no name!", path.c_str()); + Log::error("Theme '%s' has no name!", path.c_str()); } std::string ThemeInfo::getFullPath() const @@ -235,8 +235,8 @@ Theme::Theme(const ThemeInfo &themeInfo) if (mPalettes.empty()) { - logger->log("Error, theme did not define any palettes: %s", - themeInfo.getPath().c_str()); + Log::info("Error, theme did not define any palettes: %s", + themeInfo.getPath().c_str()); // Avoid crashing mPalettes.emplace_back(THEME_COLORS_END); @@ -479,7 +479,7 @@ static bool check(bool value, const char *msg, ...) { va_list ap; va_start(ap, msg); - logger->vlog(msg, ap); + Log::vinfo(msg, ap); va_end(ap); } return !value; @@ -487,9 +487,9 @@ static bool check(bool value, const char *msg, ...) bool Theme::readTheme(const ThemeInfo &themeInfo) { - logger->log("Loading %s theme from '%s'...", - themeInfo.getName().c_str(), - themeInfo.getPath().c_str()); + Log::info("Loading %s theme from '%s'...", + themeInfo.getName().c_str(), + themeInfo.getPath().c_str()); XML::Node rootNode = themeInfo.getDocument().rootNode(); @@ -507,10 +507,10 @@ bool Theme::readTheme(const ThemeInfo &themeInfo) else if (childNode.name() == "icon") readIconNode(childNode); else - logger->log("Theme: Unknown node '%s'!", childNode.name().data()); + Log::info("Theme: Unknown node '%s'!", childNode.name().data()); } - logger->log("Finished loading theme."); + Log::info("Finished loading theme."); for (auto &[_, skin] : mSkins) skin.updateAlpha(mAlpha); @@ -705,7 +705,7 @@ inline void fromString(const char *str, gcn::Color &value) if (strlen(str) < 7 || str[0] != '#') { error: - logger->log("Error, invalid theme color palette: %s", str); + Log::info("Error, invalid theme color palette: %s", str); value = gcn::Color(0, 0, 0); return; } @@ -873,7 +873,7 @@ void Theme::readPaletteNode(XML::Node node) { int paletteId; if (node.attribute("id", paletteId) && static_cast<size_t>(paletteId) != mPalettes.size()) - logger->log("Theme: Non-consecutive palette 'id' attribute with value %d!", paletteId); + Log::info("Theme: Non-consecutive palette 'id' attribute with value %d!", paletteId); Palette &palette = mPalettes.emplace_back(THEME_COLORS_END); @@ -882,7 +882,7 @@ void Theme::readPaletteNode(XML::Node node) if (childNode.name() == "color") readColorNode(childNode, palette); else - logger->log("Theme: Unknown node '%s'!", childNode.name().data()); + Log::info("Theme: Unknown node '%s'!", childNode.name().data()); } } diff --git a/src/sdlgraphics.cpp b/src/sdlgraphics.cpp index 5856d2da..7d75e7f2 100644 --- a/src/sdlgraphics.cpp +++ b/src/sdlgraphics.cpp @@ -72,7 +72,7 @@ std::unique_ptr<Graphics> SDLGraphics::create(SDL_Window *window, const VideoSet SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, rendererFlags); if (!renderer) { - logger->error(strprintf("Failed to create renderer: %s", + Log::critical(strprintf("Failed to create renderer: %s", SDL_GetError())); return {}; } @@ -91,25 +91,25 @@ SDLGraphics::SDLGraphics(SDL_Window *window, SDL_Renderer *renderer) SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_BLEND); if (const char *driver = SDL_GetCurrentVideoDriver()) - logger->log("Using video driver: %s", driver); + Log::info("Using video driver: %s", driver); else - logger->log("Using video driver: not initialized"); + Log::info("Using video driver: not initialized"); SDL_RendererInfo info; if (SDL_GetRendererInfo(renderer, &info) == 0) { - logger->log("Using renderer: %s", info.name); - - logger->log("The renderer is a software fallback: %s", - (info.flags & SDL_RENDERER_SOFTWARE) ? "yes" : "no"); - logger->log("The renderer is hardware accelerated: %s", - (info.flags & SDL_RENDERER_ACCELERATED) ? "yes" : "no"); - logger->log("Vsync: %s", - (info.flags & SDL_RENDERER_PRESENTVSYNC) ? "on" : "off"); - logger->log("Renderer supports rendering to texture: %s", - (info.flags & SDL_RENDERER_TARGETTEXTURE) ? "yes" : "no"); - logger->log("Max texture size: %dx%d", - info.max_texture_width, info.max_texture_height); + Log::info("Using renderer: %s", info.name); + + Log::info("The renderer is a software fallback: %s", + (info.flags & SDL_RENDERER_SOFTWARE) ? "yes" : "no"); + Log::info("The renderer is hardware accelerated: %s", + (info.flags & SDL_RENDERER_ACCELERATED) ? "yes" : "no"); + Log::info("Vsync: %s", + (info.flags & SDL_RENDERER_PRESENTVSYNC) ? "on" : "off"); + Log::info("Renderer supports rendering to texture: %s", + (info.flags & SDL_RENDERER_TARGETTEXTURE) ? "yes" : "no"); + Log::info("Max texture size: %dx%d", + info.max_texture_width, info.max_texture_height); } } diff --git a/src/sound.cpp b/src/sound.cpp index c97951a3..20d3810a 100644 --- a/src/sound.cpp +++ b/src/sound.cpp @@ -64,11 +64,11 @@ void Sound::init() if (mInstalled) return; - logger->log("Sound::init() Initializing sound..."); + Log::info("Sound::init() Initializing sound..."); if (SDL_InitSubSystem(SDL_INIT_AUDIO) == -1) { - logger->log("Sound::init() Failed to initialize audio subsystem"); + Log::info("Sound::init() Failed to initialize audio subsystem"); return; } @@ -78,8 +78,8 @@ void Sound::init() MIX_DEFAULT_CHANNELS, audioBuffer); if (res < 0) { - logger->log("Sound::init Could not initialize audio: %s", - Mix_GetError()); + Log::info("Sound::init Could not initialize audio: %s", + Mix_GetError()); return; } @@ -122,18 +122,18 @@ void Sound::info() case AUDIO_S16MSB: format = "S16MSB"; break; } - logger->log("Sound::info() SDL_mixer: %i.%i.%i (compiled)", + Log::info("Sound::info() SDL_mixer: %i.%i.%i (compiled)", compiledVersion.major, compiledVersion.minor, compiledVersion.patch); - logger->log("Sound::info() SDL_mixer: %i.%i.%i (linked)", + Log::info("Sound::info() SDL_mixer: %i.%i.%i (linked)", linkedVersion->major, linkedVersion->minor, linkedVersion->patch); - logger->log("Sound::info() Driver: %s", driver); - logger->log("Sound::info() Format: %s", format); - logger->log("Sound::info() Rate: %i", rate); - logger->log("Sound::info() Channels: %i", channels); + Log::info("Sound::info() Driver: %s", driver); + Log::info("Sound::info() Format: %s", format); + Log::info("Sound::info() Rate: %i", rate); + Log::info("Sound::info() Channels: %i", channels); } void Sound::setMusicVolume(int volume) @@ -173,7 +173,7 @@ void Sound::stopMusic() if (!mInstalled) return; - logger->log("Sound::stopMusic()"); + Log::info("Sound::stopMusic()"); haltMusic(); } @@ -201,7 +201,7 @@ void Sound::fadeOutMusic(int ms) if (!mInstalled) return; - logger->log("Sound::fadeOutMusic() Fading-out (%i ms)", ms); + Log::info("Sound::fadeOutMusic() Fading-out (%i ms)", ms); if (mMusic) { @@ -260,7 +260,7 @@ void Sound::playSfx(const std::string &path, int x, int y) if (ResourceRef<SoundEffect> sound = resman->getSoundEffect(tmpPath)) { - logger->log("Sound::playSfx() Playing: %s", path.c_str()); + Log::info("Sound::playSfx() Playing: %s", path.c_str()); int vol = 120; if (local_player && (x > 0 || y > 0)) @@ -299,7 +299,7 @@ void Sound::close() return; haltMusic(); - logger->log("Sound::close() Shutting down sound..."); + Log::info("Sound::close() Shutting down sound..."); Mix_CloseAudio(); mInstalled = false; diff --git a/src/units.cpp b/src/units.cpp index ee8fa6ea..1ec81cb0 100644 --- a/src/units.cpp +++ b/src/units.cpp @@ -123,8 +123,8 @@ void Units::readUnitNode(XML::Node node, const std::string &filename) } else { - logger->log("Error bad unit count: %d for %s in %s", - ul.count, ul.symbol.c_str(), bu.symbol.c_str()); + Log::info("Error bad unit count: %d for %s in %s", + ul.count, ul.symbol.c_str(), bu.symbol.c_str()); } } } @@ -139,7 +139,7 @@ void Units::readUnitNode(XML::Node node, const std::string &filename) else if (type == "currency") units[UNIT_CURRENCY] = ud; else - logger->log("Error unknown unit type: %s in %s", type.c_str(), filename.c_str()); + Log::info("Error unknown unit type: %s in %s", type.c_str(), filename.c_str()); } diff --git a/src/utils/mutex.h b/src/utils/mutex.h index a0c72e95..b6c4e88d 100644 --- a/src/utils/mutex.h +++ b/src/utils/mutex.h @@ -75,13 +75,13 @@ inline Mutex::~Mutex() inline void Mutex::lock() { if (SDL_mutexP(mMutex) == -1) - logger->log("Mutex locking failed: %s", SDL_GetError()); + Log::info("Mutex locking failed: %s", SDL_GetError()); } inline void Mutex::unlock() { if (SDL_mutexV(mMutex) == -1) - logger->log("Mutex unlocking failed: %s", SDL_GetError()); + Log::info("Mutex unlocking failed: %s", SDL_GetError()); } diff --git a/src/utils/xml.cpp b/src/utils/xml.cpp index c408c9c2..34bcc52b 100644 --- a/src/utils/xml.cpp +++ b/src/utils/xml.cpp @@ -43,13 +43,13 @@ namespace XML auto *context = static_cast<XMLContext*>(ctx); if (context) - logger->log("Error in XML file '%s' on line %d", - context->file.c_str(), error->line); + Log::info("Error in XML file '%s' on line %d", + context->file.c_str(), error->line); else - logger->log("Error in unknown XML file on line %d", - error->line); + Log::info("Error in unknown XML file on line %d", + error->line); - logger->log("%s", error->message); + Log::info("%s", error->message); // No need to keep errors around xmlCtxtResetLastError(error->ctxt); @@ -76,11 +76,11 @@ namespace XML SDL_free(data); if (!mDoc) - logger->log("Error parsing XML file %s", filename.c_str()); + Log::info("Error parsing XML file %s", filename.c_str()); } else { - logger->log("Error loading %s: %s", filename.c_str(), SDL_GetError()); + Log::info("Error loading %s: %s", filename.c_str(), SDL_GetError()); } xmlSetStructuredErrorFunc(nullptr, xmlLogger); @@ -109,7 +109,7 @@ namespace XML mWriter = xmlNewTextWriterFilename(fileName.c_str(), 0); if (!mWriter) { - logger->log("Error creating XML writer for file %s", fileName.c_str()); + Log::info("Error creating XML writer for file %s", fileName.c_str()); return; } diff --git a/src/utils/zlib.cpp b/src/utils/zlib.cpp index f78b235e..08281bcc 100644 --- a/src/utils/zlib.cpp +++ b/src/utils/zlib.cpp @@ -107,19 +107,19 @@ int inflateMemory(unsigned char *in, unsigned int inLength, { if (ret == Z_MEM_ERROR) { - logger->log("Error: Out of memory while decompressing data!"); + Log::error("Out of memory while decompressing data!"); } else if (ret == Z_VERSION_ERROR) { - logger->log("Error: Incompatible zlib version!"); + Log::error("Incompatible zlib version!"); } else if (ret == Z_DATA_ERROR) { - logger->log("Error: Incorrect zlib compressed data!"); + Log::error("Incorrect zlib compressed data!"); } else { - logger->log("Error: Unknown error while decompressing data!"); + Log::error("Unknown error while decompressing data!"); } free(out); diff --git a/src/video.cpp b/src/video.cpp index 71eff1f9..c71a9097 100644 --- a/src/video.cpp +++ b/src/video.cpp @@ -65,7 +65,7 @@ Graphics *Video::initialize(const VideoSettings &settings) if (!initDisplayModes()) { - logger->log("Failed to initialize display modes: %s", SDL_GetError()); + Log::info("Failed to initialize display modes: %s", SDL_GetError()); } SDL_DisplayMode displayMode; @@ -81,7 +81,7 @@ Graphics *Video::initialize(const VideoSettings &settings) if (SDL_GetClosestDisplayMode(mSettings.display, &requestedMode, &displayMode) == nullptr) { - logger->log("SDL_GetClosestDisplayMode failed: %s, falling back to borderless mode", SDL_GetError()); + Log::info("SDL_GetClosestDisplayMode failed: %s, falling back to borderless mode", SDL_GetError()); mSettings.windowMode = WindowMode::WindowedFullscreen; } } @@ -114,10 +114,10 @@ Graphics *Video::initialize(const VideoSettings &settings) if (mSettings.openGL) windowFlags |= SDL_WINDOW_OPENGL; - logger->log("Setting video mode %dx%d %s", - mSettings.width, - mSettings.height, - videoMode); + Log::info("Setting video mode %dx%d %s", + mSettings.width, + mSettings.height, + videoMode); mWindow = SDL_CreateWindow("Mana", SDL_WINDOWPOS_UNDEFINED, @@ -128,8 +128,7 @@ Graphics *Video::initialize(const VideoSettings &settings) if (!mWindow) { - logger->error(strprintf("Failed to create window: %s", - SDL_GetError())); + Log::critical(strprintf("Failed to create window: %s", SDL_GetError())); return nullptr; } @@ -139,7 +138,7 @@ Graphics *Video::initialize(const VideoSettings &settings) { if (SDL_SetWindowDisplayMode(mWindow, &displayMode) != 0) { - logger->log("SDL_SetWindowDisplayMode failed: %s", SDL_GetError()); + Log::info("SDL_SetWindowDisplayMode failed: %s", SDL_GetError()); } } @@ -152,7 +151,7 @@ Graphics *Video::initialize(const VideoSettings &settings) mGraphics = OpenGLGraphics::create(mWindow, mSettings); if (!mGraphics) { - logger->log("Failed to create OpenGL context, falling back to SDL renderer: %s", + Log::info("Failed to create OpenGL context, falling back to SDL renderer: %s", SDL_GetError()); mSettings.openGL = false; } @@ -178,7 +177,7 @@ bool Video::apply(const VideoSettings &settings) SDL_DisplayMode displayMode; if (SDL_GetWindowDisplayMode(mWindow, &displayMode) != 0) { - logger->error(strprintf("SDL_GetCurrentDisplayMode failed: %s", SDL_GetError())); + Log::critical(strprintf("SDL_GetCurrentDisplayMode failed: %s", SDL_GetError())); return false; } @@ -196,7 +195,7 @@ bool Video::apply(const VideoSettings &settings) if (SDL_SetWindowDisplayMode(mWindow, &displayMode) != 0) { - logger->error(strprintf("SDL_SetWindowDisplayMode failed: %s", SDL_GetError())); + Log::critical(strprintf("SDL_SetWindowDisplayMode failed: %s", SDL_GetError())); return false; } } @@ -217,7 +216,7 @@ bool Video::apply(const VideoSettings &settings) if (SDL_SetWindowFullscreen(mWindow, windowFlags) != 0) { - logger->error(strprintf("SDL_SetWindowFullscreen failed: %s", SDL_GetError())); + Log::critical(strprintf("SDL_SetWindowFullscreen failed: %s", SDL_GetError())); return false; } |