diff options
author | Guillaume Melquiond <guillaume.melquiond@gmail.com> | 2007-01-05 20:12:51 +0000 |
---|---|---|
committer | Guillaume Melquiond <guillaume.melquiond@gmail.com> | 2007-01-05 20:12:51 +0000 |
commit | 593e65eef0d43f2ff61dc1b4f3160c0a16b5f015 (patch) | |
tree | 8e0a1ca0c73778f0e4d71f4da4d5c47f272915b9 | |
parent | f96ca90ba90da3175be96ff7ed34efb78ea5dfed (diff) | |
download | manaserv-593e65eef0d43f2ff61dc1b4f3160c0a16b5f015.tar.gz manaserv-593e65eef0d43f2ff61dc1b4f3160c0a16b5f015.tar.bz2 manaserv-593e65eef0d43f2ff61dc1b4f3160c0a16b5f015.tar.xz manaserv-593e65eef0d43f2ff61dc1b4f3160c0a16b5f015.zip |
Simplified handling of verbosity levels. Optimized code by generating only needed messages.
-rw-r--r-- | ChangeLog | 15 | ||||
-rw-r--r-- | src/Makefile.am | 6 | ||||
-rw-r--r-- | src/account-server/accounthandler.cpp | 88 | ||||
-rw-r--r-- | src/account-server/dalstorage.cpp | 26 | ||||
-rw-r--r-- | src/account-server/main-account.cpp | 32 | ||||
-rw-r--r-- | src/account-server/serverhandler.cpp | 14 | ||||
-rw-r--r-- | src/chat-server/chathandler.cpp | 24 | ||||
-rw-r--r-- | src/configuration.cpp | 4 | ||||
-rw-r--r-- | src/controller.cpp | 4 | ||||
-rw-r--r-- | src/game-server/accountconnection.cpp | 4 | ||||
-rw-r--r-- | src/game-server/being.cpp | 2 | ||||
-rw-r--r-- | src/game-server/gamehandler.cpp | 6 | ||||
-rw-r--r-- | src/game-server/itemmanager.cpp | 51 | ||||
-rw-r--r-- | src/game-server/main-game.cpp | 26 | ||||
-rw-r--r-- | src/game-server/mapmanager.cpp | 14 | ||||
-rw-r--r-- | src/game-server/mapreader.cpp | 10 | ||||
-rw-r--r-- | src/net/connection.cpp | 11 | ||||
-rw-r--r-- | src/net/connectionhandler.cpp | 17 | ||||
-rw-r--r-- | src/net/netcomputer.cpp | 5 | ||||
-rw-r--r-- | src/resourcemanager.cpp | 10 | ||||
-rw-r--r-- | src/skill.cpp | 8 | ||||
-rw-r--r-- | src/utils/logger.cpp | 277 | ||||
-rw-r--r-- | src/utils/logger.h | 249 | ||||
-rw-r--r-- | src/utils/stringfilter.cpp | 3 | ||||
-rw-r--r-- | src/utils/zlib.cpp | 8 |
25 files changed, 270 insertions, 644 deletions
@@ -25,6 +25,21 @@ Inventory on Player connection. * src/game-server/gamehandler.cpp, src/game-server/player.hpp, src/game-server/player.cpp: Generalized player state. + * src/utils/logger.h, src/utils/logger.cpp: Simplified handling of + verbosity levels: fatal, error, warn, info, debug are now the levels. + Optimized code by generating only needed messages. + * src/chat-server/chathandler.cpp, src/net/connection.cpp, + src/net/netcomputer.cpp, src/net/connectionhandler.cpp, src/skill.cpp, + src/configuration.cpp, src/account-server/main-account.cpp, + src/account-server/serverhandler.cpp, src/utils/stringfilter.cpp, + src/account-server/dalstorage.cpp, src/utils/zlib.cpp, + src/account-server/accounthandler.cpp, src/resourcemanager.cpp, + src/controller.cpp, src/game-server/mapreader.cpp, + src/game-server/gamehandler.cpp, src/game-server/mapmanager.cpp, + src/game-server/accountconnection.cpp, src/game-server/being.cpp, + src/game-server/itemmanager.cpp, src/game-server/main-game.cpp: + Updated accordingly. Removed some unworthy debug messages. + * src/Makefile.am: Removed useless dependencies. 2007-01-04 Guillaume Melquiond <guillaume.melquiond@gmail.com> diff --git a/src/Makefile.am b/src/Makefile.am index 61901420..8b60e54e 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -50,11 +50,8 @@ tmwserv_account_SOURCES = \ net/messageout.cpp \ net/netcomputer.hpp \ net/netcomputer.cpp \ - utils/base64.h \ - utils/base64.cpp \ utils/countedptr.h \ utils/functors.h \ - utils/singleton.h \ utils/logger.h \ utils/logger.cpp \ utils/stringfilter.h \ @@ -117,9 +114,6 @@ tmwserv_game_SOURCES = \ net/netcomputer.cpp \ utils/base64.h \ utils/base64.cpp \ - utils/countedptr.h \ - utils/functors.h \ - utils/singleton.h \ utils/logger.h \ utils/logger.cpp \ utils/stringfilter.h \ diff --git a/src/account-server/accounthandler.cpp b/src/account-server/accounthandler.cpp index 004e1b8b..dae646f7 100644 --- a/src/account-server/accounthandler.cpp +++ b/src/account-server/accounthandler.cpp @@ -39,7 +39,7 @@ bool AccountHandler::startListen(enet_uint16 port) { - LOG_INFO("Account handler started:", 0); + LOG_INFO("Account handler started:"); return ConnectionHandler::startListen(port); } @@ -102,7 +102,6 @@ AccountHandler::processMessage(NetComputer *comp, MessageIn &message) if (computer.getAccount().get() == NULL) { result.writeByte(ERRMSG_NO_LOGIN); - LOG_INFO("Not logged in. Can't change your Account's Email.", 1); break; } @@ -110,25 +109,19 @@ AccountHandler::processMessage(NetComputer *comp, MessageIn &message) if (!stringFilter->isEmailValid(email)) { result.writeByte(ERRMSG_INVALID_ARGUMENT); - LOG_INFO(email << ": Invalid format, cannot change Email for " << - computer.getAccount()->getName(), 1); } else if (stringFilter->findDoubleQuotes(email)) { result.writeByte(ERRMSG_INVALID_ARGUMENT); - LOG_INFO(email << ": has got double quotes in it.", 1); } else if (store.doesEmailAddressExist(email)) { result.writeByte(EMAILCHG_EXISTS_EMAIL); - LOG_INFO(email << ": New Email already exists.", 1); } else { computer.getAccount()->setEmail(email); result.writeByte(ERRMSG_OK); - LOG_INFO(computer.getAccount()->getName() << ": Email changed to: " << - email, 1); } } break; @@ -138,7 +131,6 @@ AccountHandler::processMessage(NetComputer *comp, MessageIn &message) result.writeShort(APMSG_EMAIL_GET_RESPONSE); if (computer.getAccount().get() == NULL) { result.writeByte(ERRMSG_NO_LOGIN); - LOG_INFO("Not logged in. Can't get your Account's current Email.", 1); break; } else @@ -164,7 +156,6 @@ AccountHandler::processMessage(NetComputer *comp, MessageIn &message) if (computer.getAccount().get() == NULL) { result.writeByte(ERRMSG_NO_LOGIN); - LOG_INFO("Not logged in. Can't select a Character.", 1); break; // not logged in } @@ -175,7 +166,6 @@ AccountHandler::processMessage(NetComputer *comp, MessageIn &message) if (charNum >= chars.size()) { // invalid char selection result.writeByte(ERRMSG_INVALID_ARGUMENT); - LOG_INFO("Character Selection: Selection out of ID range.", 1); break; } @@ -184,7 +174,7 @@ AccountHandler::processMessage(NetComputer *comp, MessageIn &message) if (!serverHandler->getGameServerFromMap(chars[charNum]->getMap(), address, port)) { result.writeByte(ERRMSG_FAILURE); - LOG_ERROR("Character Selection: No game server for the map.", 0); + LOG_ERROR("Character Selection: No game server for the map."); break; } @@ -193,8 +183,7 @@ AccountHandler::processMessage(NetComputer *comp, MessageIn &message) PlayerPtr selectedChar = computer.getCharacter(); result.writeByte(ERRMSG_OK); - LOG_INFO(selectedChar->getName() - << " is trying to enter the servers.", 1); + LOG_DEBUG(selectedChar->getName() << " is trying to enter the servers."); std::string magic_token(32, ' '); for (int i = 0; i < 32; ++i) { @@ -221,7 +210,6 @@ AccountHandler::processMessage(NetComputer *comp, MessageIn &message) if (computer.getAccount().get() == NULL) { result.writeByte(ERRMSG_NO_LOGIN); - LOG_INFO("Not logged in. Can't delete a Character.", 1); break; // not logged in } @@ -232,7 +220,6 @@ AccountHandler::processMessage(NetComputer *comp, MessageIn &message) if (charNum >= chars.size()) { // invalid char selection result.writeByte(ERRMSG_INVALID_ARGUMENT); - LOG_INFO("Character Deletion : Selection out of ID range.", 1); break; } @@ -250,14 +237,14 @@ AccountHandler::processMessage(NetComputer *comp, MessageIn &message) std::string deletedCharacter = chars[charNum].get()->getName(); computer.getAccount()->delCharacter(deletedCharacter); store.flush(computer.getAccount()); - LOG_INFO(deletedCharacter << ": Character deleted...", 1); + LOG_INFO(deletedCharacter << ": Character deleted..."); result.writeByte(ERRMSG_OK); } break; default: - LOG_WARN("Invalid message type", 0); + LOG_WARN("Invalid message type"); result.writeShort(XXMSG_INVALID); break; } @@ -274,30 +261,21 @@ AccountHandler::handleLoginMessage(AccountClient &computer, MessageIn &msg) std::string username = msg.readString(); std::string password = msg.readString(); - LOG_INFO(username << " is trying to login.", 1); - MessageOut reply(APMSG_LOGIN_RESPONSE); if (clientVersion < config.getValue("clientVersion", 0)) { - LOG_INFO("Client has an insufficient version number to login.", 1); reply.writeByte(LOGIN_INVALID_VERSION); } if (stringFilter->findDoubleQuotes(username)) { - LOG_INFO(username << ": has got double quotes in it.", 1); reply.writeByte(ERRMSG_INVALID_ARGUMENT); } if (computer.getAccount().get() != NULL) { - LOG_INFO("Already logged in as " << computer.getAccount()->getName() - << ".", 1); - LOG_INFO("Please logout first.", 1); reply.writeByte(ERRMSG_FAILURE); } if (getClientNumber() >= MAX_CLIENTS ) { - LOG_INFO("Client couldn't login. Already has " << MAX_CLIENTS - << " logged in.", 1); reply.writeByte(LOGIN_SERVER_FULL); } else @@ -308,14 +286,10 @@ AccountHandler::handleLoginMessage(AccountClient &computer, MessageIn &msg) if (!acc.get() || acc->getPassword() != password) { - LOG_INFO(username << ": Account does not exist or the password is " - "invalid.", 1); reply.writeByte(ERRMSG_INVALID_ARGUMENT); } else { - LOG_INFO("Login OK by " << username, 1); - // Associate account with connection computer.setAccount(acc); @@ -325,9 +299,6 @@ AccountHandler::handleLoginMessage(AccountClient &computer, MessageIn &msg) // Return information about available characters Players &chars = computer.getAccount()->getCharacters(); - LOG_INFO(username << "'s account has " << chars.size() - << " character(s).", 1); - // Send characters list for (unsigned int i = 0; i < chars.size(); i++) { @@ -357,12 +328,10 @@ AccountHandler::handleLogoutMessage(AccountClient &computer, MessageIn &msg) if (computer.getAccount().get() == NULL) { - LOG_INFO("Can't logout. Not even logged in.", 1); reply.writeByte(ERRMSG_NO_LOGIN); } else { - LOG_INFO(computer.getAccount()->getName() << " logged out.", 1); computer.unsetAccount(); reply.writeByte(ERRMSG_OK); } @@ -378,46 +347,37 @@ AccountHandler::handleRegisterMessage(AccountClient &computer, MessageIn &msg) std::string password = msg.readString(); std::string email = msg.readString(); - LOG_INFO(username << " is trying to register.", 1); - MessageOut reply(APMSG_REGISTER_RESPONSE); if (clientVersion < config.getValue("clientVersion", 0)) { - LOG_INFO("Client has an unsufficient version number to login.", 1); reply.writeByte(REGISTER_INVALID_VERSION); } else if (stringFilter->findDoubleQuotes(username)) { - LOG_INFO(username << ": has got double quotes in it.", 1); reply.writeByte(ERRMSG_INVALID_ARGUMENT); } else if (stringFilter->findDoubleQuotes(email)) { - LOG_INFO(email << ": has got double quotes in it.", 1); reply.writeByte(ERRMSG_INVALID_ARGUMENT); } else if ((username.length() < MIN_LOGIN_LENGTH) || (username.length() > MAX_LOGIN_LENGTH)) { - LOG_INFO(username << ": Username too short or too long.", 1); reply.writeByte(ERRMSG_INVALID_ARGUMENT); } else if ((password.length() < MIN_PASSWORD_LENGTH) || (password.length() > MAX_PASSWORD_LENGTH)) { - LOG_INFO(email << ": Password too short or too long.", 1); reply.writeByte(ERRMSG_INVALID_ARGUMENT); } else if (!stringFilter->isEmailValid(email)) { - LOG_INFO(email << ": Email Invalid, only a@b.c format is accepted.", 1); reply.writeByte(ERRMSG_INVALID_ARGUMENT); } // Checking if the Name is slang's free. else if (!stringFilter->filterContent(username)) { - LOG_INFO(username << ": has got bad words in it.", 1); reply.writeByte(ERRMSG_INVALID_ARGUMENT); } else @@ -428,21 +388,17 @@ AccountHandler::handleRegisterMessage(AccountClient &computer, MessageIn &msg) // Check whether the account already exists. if (accPtr.get()) { - LOG_INFO(username << ": Username already exists.", 1); reply.writeByte(REGISTER_EXISTS_USERNAME); } // Find out whether the email is already in use. else if (store.doesEmailAddressExist(email)) { - LOG_INFO(email << ": Email already exists.", 1); reply.writeByte(REGISTER_EXISTS_EMAIL); } else { AccountPtr acc(new Account(username, password, email)); store.addAccount(acc); - LOG_INFO(username << ": Account registered.", 1); - reply.writeByte(ERRMSG_OK); } } @@ -457,13 +413,10 @@ AccountHandler::handleUnregisterMessage(AccountClient &computer, std::string username = msg.readString(); std::string password = msg.readString(); - LOG_INFO(username << " wants to be deleted from our accounts.", 1); - MessageOut reply(APMSG_UNREGISTER_RESPONSE); if (stringFilter->findDoubleQuotes(username)) { - LOG_INFO(username << ": has got double quotes in it.", 1); reply.writeByte(ERRMSG_INVALID_ARGUMENT); } else @@ -474,8 +427,6 @@ AccountHandler::handleUnregisterMessage(AccountClient &computer, if (!accPtr.get() || accPtr->getPassword() != password) { - LOG_INFO("Account does not exist or bad password for " - << username << ".", 1); reply.writeByte(ERRMSG_INVALID_ARGUMENT); } else @@ -491,7 +442,7 @@ AccountHandler::handleUnregisterMessage(AccountClient &computer, } // Delete account and associated characters - LOG_INFO("Farewell " << username << " ...", 1); + LOG_INFO("Farewell " << username << " ..."); store.delAccount(accPtr); reply.writeByte(ERRMSG_OK); } @@ -511,31 +462,23 @@ AccountHandler::handlePasswordChangeMessage(AccountClient &computer, if (computer.getAccount().get() == NULL) { - LOG_INFO("Not logged in. Can't change your Account's Password.", 1); reply.writeByte(ERRMSG_NO_LOGIN); } else if (newPassword.length() < MIN_PASSWORD_LENGTH || newPassword.length() > MAX_PASSWORD_LENGTH) { - LOG_INFO(computer.getAccount()->getName() << - ": New password too long or too short.", 1); reply.writeByte(ERRMSG_INVALID_ARGUMENT); } else if (stringFilter->findDoubleQuotes(newPassword)) { - LOG_INFO(newPassword << ": has got double quotes in it.", 1); reply.writeByte(ERRMSG_INVALID_ARGUMENT); } else if (oldPassword != computer.getAccount()->getPassword()) { - LOG_INFO(computer.getAccount()->getName() << - ": Old password is wrong.", 1); reply.writeByte(ERRMSG_FAILURE); } else { - LOG_INFO(computer.getAccount()->getName() << - ": The password was changed.", 1); computer.getAccount()->setPassword(newPassword); reply.writeByte(ERRMSG_OK); } @@ -555,38 +498,31 @@ AccountHandler::handleCharacterCreateMessage(AccountClient &computer, MessageOut reply(APMSG_CHAR_CREATE_RESPONSE); if (computer.getAccount().get() == NULL) { - LOG_INFO("Not logged in. Can't create a Character.", 1); reply.writeByte(ERRMSG_NO_LOGIN); } else if (!stringFilter->filterContent(name)) { - LOG_INFO(name << ": Character has got bad words in it.", 1); reply.writeByte(ERRMSG_INVALID_ARGUMENT); } else if (stringFilter->findDoubleQuotes(name)) { - LOG_INFO(name << ": has got double quotes in it.", 1); reply.writeByte(ERRMSG_INVALID_ARGUMENT); } else if (hairStyle < 0 || hairStyle > MAX_HAIRSTYLE_VALUE) { - LOG_INFO(name << ": Character's hair Style is invalid.", 1); reply.writeByte(CREATE_INVALID_HAIRSTYLE); } else if (hairColor < 0 || hairColor > MAX_HAIRCOLOR_VALUE) { - LOG_INFO(name << ": Character's hair Color is invalid.", 1); reply.writeByte(CREATE_INVALID_HAIRCOLOR); } else if (gender < 0 || gender > MAX_GENDER_VALUE) { - LOG_INFO(name << ": Character's gender is invalid.", 1); reply.writeByte(CREATE_INVALID_GENDER); } else if ((name.length() < MIN_CHARACTER_LENGTH) || (name.length() > MAX_CHARACTER_LENGTH)) { - LOG_INFO(name << ": Character's name too short or too long.", 1); reply.writeByte(ERRMSG_INVALID_ARGUMENT); } else @@ -594,7 +530,6 @@ AccountHandler::handleCharacterCreateMessage(AccountClient &computer, Storage &store = Storage::instance("tmw"); if (store.doesCharacterNameExist(name)) { - LOG_INFO(name << ": Character's name already exists.", 1); reply.writeByte(CREATE_EXISTS_NAME); computer.send(reply); return; @@ -604,8 +539,6 @@ AccountHandler::handleCharacterCreateMessage(AccountClient &computer, Players &chars = computer.getAccount()->getCharacters(); if (chars.size() >= MAX_OF_CHARACTERS) { - LOG_INFO("Already has " << chars.size() - << " characters. Can't create another Character.", 1); reply.writeByte(CREATE_TOO_MUCH_CHARACTERS); computer.send(reply); return; @@ -638,25 +571,18 @@ AccountHandler::handleCharacterCreateMessage(AccountClient &computer, if (totalStats > POINTS_TO_DISTRIBUTES_AT_LVL1) { - LOG_INFO(name << ": Character's stats are too high to be of " - "level 1.", 1); reply.writeByte(CREATE_RAW_STATS_TOO_HIGH); } else if (totalStats < POINTS_TO_DISTRIBUTES_AT_LVL1) { - LOG_INFO(name << ": Character's stats are too low to be of " - "level 1.", 1); reply.writeByte(CREATE_RAW_STATS_TOO_LOW); } else if ((highestStat - lowestStat) > (signed) MAX_DIFF_BETWEEN_STATS) { - LOG_INFO(name << ": Character's stats difference is too high to " - "be accepted.", 1); reply.writeByte(CREATE_RAW_STATS_INVALID_DIFF); } else if (!validNonZeroRawStats) { - LOG_INFO(name << ": One stat is equal to zero.", 1); reply.writeByte(CREATE_RAW_STATS_EQUAL_TO_ZERO); } else @@ -676,7 +602,7 @@ AccountHandler::handleCharacterCreateMessage(AccountClient &computer, computer.getAccount()->addCharacter(newCharacter); LOG_INFO("Character " << name << " was created for " - << computer.getAccount()->getName() << "'s account.", 1); + << computer.getAccount()->getName() << "'s account."); store.flush(computer.getAccount()); // flush changes reply.writeByte(ERRMSG_OK); diff --git a/src/account-server/dalstorage.cpp b/src/account-server/dalstorage.cpp index ee9901fa..278d28db 100644 --- a/src/account-server/dalstorage.cpp +++ b/src/account-server/dalstorage.cpp @@ -113,7 +113,7 @@ DALStorage::open(void) mDb->connect(getName(), getUser(), getPassword()); if (!dbFileShown) { - LOG_INFO("Using " << dbFile << " as Database Name.", 0); + LOG_INFO("Using " << dbFile << " as Database Name."); dbFileShown = true; } #elif defined (SQLITE_SUPPORT) @@ -122,7 +122,7 @@ DALStorage::open(void) mDb->connect(dbFile, "", ""); if (!dbFileShown) { - LOG_INFO("SQLite uses ./" << dbFile << " as DB.", 0); + LOG_INFO("SQLite uses ./" << dbFile << " as DB."); dbFileShown = true; } #endif @@ -167,10 +167,10 @@ DALStorage::open(void) createTable(CHANNELS_TBL_NAME, SQL_CHANNELS_TABLE); } catch (const DbConnectionFailure& e) { - LOG_ERROR("unable to connect to the database: " << e.what(), 0); + LOG_ERROR("unable to connect to the database: " << e.what()); } catch (const DbSqlQueryExecFailure& e) { - LOG_ERROR("SQL query failure: " << e.what(), 0); + LOG_ERROR("SQL query failure: " << e.what()); } mIsOpen = mDb->isConnected(); @@ -243,8 +243,8 @@ DALStorage::getAccount(const std::string& userName) int size = charInfo.rows(); Players players; - LOG_INFO(userName << "'s account has " << size - << " character(s) in database.", 1); + LOG_DEBUG(userName << "'s account has " << size + << " character(s) in database."); // Two steps: it seems like multiple requests cannot be alive at the same time. std::vector< unsigned > playerIDs; @@ -375,7 +375,7 @@ DALStorage::getEmailList() } catch (const dal::DbSqlQueryExecFailure& e) { // TODO: throw an exception. - LOG_ERROR("SQL query failure: " << e.what(), 0); + LOG_ERROR("SQL query failure: " << e.what()); } return emailList; @@ -402,7 +402,7 @@ bool DALStorage::doesEmailAddressExist(std::string const &email) return iReturn != 0; } catch (std::exception const &e) { // TODO: throw an exception. - LOG_ERROR("SQL query failure: " << e.what(), 0); + LOG_ERROR("SQL query failure: " << e.what()); } return true; @@ -429,7 +429,7 @@ bool DALStorage::doesCharacterNameExist(const std::string& name) return iReturn != 0; } catch (std::exception const &e) { // TODO: throw an exception. - LOG_ERROR("SQL query failure: " << e.what(), 0); + LOG_ERROR("SQL query failure: " << e.what()); } return true; @@ -469,14 +469,14 @@ DALStorage::getChannelList() channelInfo(i,3)))); LOG_DEBUG("Channel (" << channelInfo(i,0) << ") loaded: " << channelInfo(i,1) - << ": " << channelInfo(i,2), 5); + << ": " << channelInfo(i,2)); } return channels; } catch (const dal::DbSqlQueryExecFailure& e) { // TODO: throw an exception. - LOG_ERROR("SQL query failure: " << e.what(), 0); + LOG_ERROR("SQL query failure: " << e.what()); } return channels; @@ -520,7 +520,7 @@ DALStorage::updateChannels(std::map<short, ChatChannel>& channelList) << i->second.getPassword() << "\");"; LOG_DEBUG("Channel (" << i->first << ") saved: " << i->second.getName() - << ": " << i->second.getAnnouncement(), 5); + << ": " << i->second.getAnnouncement()); } mDb->execSql(sql.str()); @@ -531,7 +531,7 @@ DALStorage::updateChannels(std::map<short, ChatChannel>& channelList) } catch (const dal::DbSqlQueryExecFailure& e) { // TODO: throw an exception. - LOG_ERROR("SQL query failure: " << e.what(), 0); + LOG_ERROR("SQL query failure: " << e.what()); } } diff --git a/src/account-server/main-account.cpp b/src/account-server/main-account.cpp index 1d83020b..195071d3 100644 --- a/src/account-server/main-account.cpp +++ b/src/account-server/main-account.cpp @@ -123,14 +123,14 @@ void initialize() // Initialize the logger. using namespace utils; - Logger::instance().setLogFile(logPath); + Logger::setLogFile(logPath); // write the messages to both the screen and the log file. - Logger::instance().setTeeMode(true); + Logger::setTeeMode(true); config.init(configPath); - LOG_INFO("Using Config File: " << configPath, 0); - LOG_INFO("Using Log File: " << logPath, 0); + LOG_INFO("Using Config File: " << configPath); + LOG_INFO("Using Log File: " << logPath); // --- Initialize the managers // Initialize the slang's and double quotes filter. @@ -153,13 +153,13 @@ void initialize() #if defined (MYSQL_SUPPORT) - LOG_INFO("Using MySQL DB Backend.", 0); + LOG_INFO("Using MySQL DB Backend."); #elif defined (POSTGRESQL_SUPPORT) - LOG_INFO("Using PostGreSQL DB Backend.", 0); + LOG_INFO("Using PostGreSQL DB Backend."); #elif defined (SQLITE_SUPPORT) - LOG_INFO("Using SQLite DB Backend.", 0); + LOG_INFO("Using SQLite DB Backend."); #else - LOG_WARN("No Database Backend Support.", 0); + LOG_WARN("No Database Backend Support."); #endif // Initialize configuration defaults @@ -243,15 +243,15 @@ void parseOptions(int argc, char *argv[]) // Set Verbosity to level unsigned short verbosityLevel; verbosityLevel = atoi(optarg); - utils::Logger::instance().setVerbosity(verbosityLevel); - LOG_INFO("Setting Log Verbosity Level to " << verbosityLevel, 0); + utils::Logger::setVerbosity(utils::Logger::Level(verbosityLevel)); + LOG_INFO("Setting Log Verbosity Level to " << verbosityLevel); break; case 'p': // Change the port to listen on. unsigned short portToListenOn; portToListenOn = atoi(optarg); config.setValue("ListenOnPort", portToListenOn); - LOG_INFO("Setting Default Port to " << portToListenOn, 0); + LOG_INFO("Setting Default Port to " << portToListenOn); break; } } @@ -265,7 +265,7 @@ int main(int argc, char *argv[]) { int elapsedWorldTicks; - LOG_INFO("The Mana World Server v" << PACKAGE_VERSION, 0); + LOG_INFO("The Mana World Account+Chat Server v" << PACKAGE_VERSION); // Parse Command Line Options parseOptions(argc, argv); @@ -298,14 +298,14 @@ int main(int argc, char *argv[]) if (elapsedWorldTicks > 1) { - LOG_WARN(elapsedWorldTicks -1 << " World Tick(s) skipped " + LOG_WARN(elapsedWorldTicks - 1 << " World Tick(s) skipped " "because of insufficient time. please buy a faster " - "machine ;-)", 0); + "machine ;-)"); }; // Print world time at 10 second intervals to show we're alive if (worldTime % 100 == 0) { - LOG_INFO("World time: " << worldTime, 0); + LOG_INFO("World time: " << worldTime); } // Handle all messages that are in the message queues @@ -316,7 +316,7 @@ int main(int argc, char *argv[]) worldTimer.sleep(); } - LOG_INFO("Received: Quit signal, closing down...", 0); + LOG_INFO("Received: Quit signal, closing down..."); serverHandler->stopListen(); chatHandler->stopListen(); accountHandler->stopListen(); diff --git a/src/account-server/serverhandler.cpp b/src/account-server/serverhandler.cpp index 572492e7..f6d41fc5 100644 --- a/src/account-server/serverhandler.cpp +++ b/src/account-server/serverhandler.cpp @@ -33,7 +33,7 @@ bool ServerHandler::startListen(enet_uint16 port) { - LOG_INFO("Server handler started:", 0); + LOG_INFO("Game server handler started:"); return ConnectionHandler::startListen(port); } @@ -49,7 +49,7 @@ void ServerHandler::computerDisconnected(NetComputer *comp) { if (i->second.server == comp) { - LOG_INFO("Unregistering map " << i->first << '.', 0); + LOG_INFO("Unregistering map " << i->first << '.'); servers.erase(i++); } else @@ -97,12 +97,12 @@ void ServerHandler::processMessage(NetComputer *comp, MessageIn &msg) Server s = { address, port, comp }; LOG_INFO("Game server " << address << ':' << port << " wants to register " << (msg.getUnreadLength() / 2) - << " maps.", 0); + << " maps."); while (msg.getUnreadLength()) { int id = msg.readShort(); - LOG_INFO("Registering map " << id << '.', 0); + LOG_INFO("Registering map " << id << '.'); if (servers.insert(std::make_pair(id, s)).second) { MessageOut outMsg(AGMSG_ACTIVE_MAP); @@ -111,7 +111,7 @@ void ServerHandler::processMessage(NetComputer *comp, MessageIn &msg) } else { - LOG_ERROR("Server Handler: map is already registered.", 0); + LOG_ERROR("Server Handler: map is already registered."); } } } break; @@ -149,12 +149,12 @@ void ServerHandler::processMessage(NetComputer *comp, MessageIn &msg) else { LOG_ERROR("Server Change: No game server for map " << - ptr->getMap() << ".", 0); + ptr->getMap() << "."); } } break; default: - LOG_WARN("Invalid message type: " << msg.getId(), 0); + LOG_WARN("Invalid message type: " << msg.getId()); result.writeShort(XXMSG_INVALID); break; } diff --git a/src/chat-server/chathandler.cpp b/src/chat-server/chathandler.cpp index 323abe76..2e8a9912 100644 --- a/src/chat-server/chathandler.cpp +++ b/src/chat-server/chathandler.cpp @@ -90,7 +90,7 @@ void registerChatClient(std::string const &token, std::string const &name, int l bool ChatHandler::startListen(enet_uint16 port) { - LOG_INFO("Chat handler started:", 0); + LOG_INFO("Chat handler started:"); return ConnectionHandler::startListen(port); } @@ -142,7 +142,8 @@ void ChatHandler::processMessage(NetComputer *comp, MessageIn &message) if (i == pendingLogins.end()) { for (ChatPendingClients::iterator i = pendingClients.begin(), i_end = pendingClients.end(); - i != i_end; ++i) { + i != i_end; ++i) + { if (i->second == &computer) return; } pendingClients.insert(std::make_pair(magic_token, &computer)); @@ -167,7 +168,7 @@ void ChatHandler::processMessage(NetComputer *comp, MessageIn &message) if (stringFilter->filterContent(text)) { short channel = message.readShort(); - LOG_INFO("Say: (Channel " << channel << "): " << text, 2); + LOG_DEBUG("Say: (Channel " << channel << "): " << text); if ( channel == 0 ) // Let's say that is the default channel for now. { if ( text.substr(0, 1) == "@" || text.substr(0, 1) == "#" || text.substr(0, 1) == "/" ) @@ -420,7 +421,7 @@ void ChatHandler::processMessage(NetComputer *comp, MessageIn &message) break; default: - LOG_WARN("Invalid message type", 0); + LOG_WARN("Invalid message type"); result.writeShort(XXMSG_INVALID); break; } @@ -431,7 +432,7 @@ void ChatHandler::processMessage(NetComputer *comp, MessageIn &message) void ChatHandler::handleCommand(ChatClient &computer, std::string const &command) { - LOG_INFO("Chat: Received unhandled command: " << command, 2); + LOG_INFO("Chat: Received unhandled command: " << command); MessageOut result; result.writeShort(CPMSG_ERROR); result.writeByte(CHAT_UNHANDLED_COMMAND); @@ -446,7 +447,7 @@ void ChatHandler::warnPlayerAboutBadWords(ChatClient &computer) result.writeByte(CHAT_USING_BAD_WORDS); // The Channel computer.send(result); - LOG_INFO(computer.characterName << " says bad words.", 2); + LOG_INFO(computer.characterName << " says bad words."); } void ChatHandler::announce(ChatClient &computer, std::string const &text) @@ -455,7 +456,7 @@ void ChatHandler::announce(ChatClient &computer, std::string const &text) if (computer.accountLevel == AL_ADMIN || computer.accountLevel == AL_GM ) { - LOG_INFO("ANNOUNCE: " << text, 0); + LOG_INFO("ANNOUNCE: " << text); // Send it to every beings. result.writeShort(CPMSG_ANNOUNCEMENT); result.writeString(text); @@ -467,14 +468,14 @@ void ChatHandler::announce(ChatClient &computer, std::string const &text) result.writeByte(ERRMSG_INSUFFICIENT_RIGHTS); computer.send(result); LOG_INFO(computer.characterName << - " couldn't make an announcement due to insufficient rights.", 2); + " couldn't make an announcement due to insufficient rights."); } } void ChatHandler::sayToPlayer(ChatClient &computer, std::string const &playerName, std::string const &text) { MessageOut result; - LOG_INFO(computer.characterName << " says to " << playerName << ": " << text, 2); + LOG_DEBUG(computer.characterName << " says to " << playerName << ": " << text); // Send it to the being if the being exists result.writeShort(CPMSG_PRIVMSG); result.writeString(computer.characterName); @@ -492,7 +493,7 @@ void ChatHandler::sayToPlayer(ChatClient &computer, std::string const &playerNam void ChatHandler::sayInChannel(ChatClient &computer, short channel, std::string const &text) { MessageOut result; - LOG_INFO(computer.characterName << " says in channel " << channel << ": " << text, 2); + LOG_DEBUG(computer.characterName << " says in channel " << channel << ": " << text); // Send it to every beings in channel result.writeShort(CPMSG_PUBMSG); result.writeShort(channel); @@ -518,7 +519,8 @@ void ChatHandler::sendInChannel(short channelId, MessageOut &msg) std::vector< std::string > const &users = chatChannelManager->getUserListInChannel(channelId); for (NetComputers::iterator i = clients.begin(), i_end = clients.end(); - i != i_end; ++i) { + i != i_end; ++i) + { // If the being is in the channel, send it std::vector< std::string >::const_iterator j_end = users.end(), j = std::find(users.begin(), j_end, static_cast< ChatClient * >(*i)->characterName); diff --git a/src/configuration.cpp b/src/configuration.cpp index c2a84b23..277a37e2 100644 --- a/src/configuration.cpp +++ b/src/configuration.cpp @@ -61,7 +61,7 @@ void Configuration::init(const std::string &filename) xmlNodePtr node = xmlDocGetRootElement(doc); if (!node || !xmlStrEqual(node->name, BAD_CAST "configuration")) { - LOG_WARN("Warning: No configuration file (" << filename.c_str() << ")", 0); + LOG_WARN("Warning: No configuration file (" << filename.c_str() << ")"); return; } @@ -126,7 +126,7 @@ void Configuration::write() void Configuration::setValue(const std::string &key, std::string value) { - LOG_DEBUG("Configuration::setValue(" << key << ", " << value << ")", 2); + LOG_DEBUG("Configuration::setValue(" << key << ", " << value << ")"); options[key] = value; diff --git a/src/controller.cpp b/src/controller.cpp index b70e17e8..a243006c 100644 --- a/src/controller.cpp +++ b/src/controller.cpp @@ -36,8 +36,8 @@ void Controlled::update() setDestination(randomPos); mCountDown = 10 + rand() % 10; - LOG_INFO("Setting new random destination " << randomPos.x << "," - << randomPos.y << " for being " << getPublicID(), 2); + LOG_DEBUG("Setting new random destination " << randomPos.x << "," + << randomPos.y << " for being " << getPublicID()); } else { diff --git a/src/game-server/accountconnection.cpp b/src/game-server/accountconnection.cpp index 68a1430f..d681cb64 100644 --- a/src/game-server/accountconnection.cpp +++ b/src/game-server/accountconnection.cpp @@ -40,7 +40,7 @@ bool AccountConnection::start() { return false; } - LOG_INFO("Connection established to the account server.", 0); + LOG_INFO("Connection established to the account server."); MessageOut msg(GAMSG_REGISTER); msg.writeString(config.getValue("gameServerAddress", "localhost")); msg.writeShort(int(config.getValue("gameServerPort", DEFAULT_SERVER_PORT + 3))); @@ -94,7 +94,7 @@ void AccountConnection::processMessage(MessageIn &msg) } break; default: - LOG_WARN("Invalid message type", 0); + LOG_WARN("Invalid message type"); break; } } diff --git a/src/game-server/being.cpp b/src/game-server/being.cpp index da8f1f2c..516732aa 100644 --- a/src/game-server/being.cpp +++ b/src/game-server/being.cpp @@ -32,7 +32,7 @@ void Being::damage(Damage damage) mHitpoints -= HPloss; mHitsTaken.push_back(HPloss); - LOG_DEBUG("Being " << getPublicID() << " got hit", 0); + LOG_DEBUG("Being " << getPublicID() << " got hit"); } void Being::performAttack(MapComposite *map) diff --git a/src/game-server/gamehandler.cpp b/src/game-server/gamehandler.cpp index ae18e893..98a10938 100644 --- a/src/game-server/gamehandler.cpp +++ b/src/game-server/gamehandler.cpp @@ -112,7 +112,7 @@ void registerGameClient(std::string const &token, Player *ch) bool GameHandler::startListen(enet_uint16 port) { - LOG_INFO("Game handler started:", 0); + LOG_INFO("Game handler started:"); return ConnectionHandler::startListen(port); } @@ -298,13 +298,13 @@ void GameHandler::processMessage(NetComputer *comp, MessageIn &message) case PGMSG_ATTACK: { LOG_DEBUG("Player " << computer.character->getPublicID() - << " attacks", 0); + << " attacks"); computer.character->setDirection(message.readByte()); computer.character->setAction(PLAYER_ATTACK); } break; default: - LOG_WARN("Invalid message type", 0); + LOG_WARN("Invalid message type"); result.writeShort(XXMSG_INVALID); break; } diff --git a/src/game-server/itemmanager.cpp b/src/game-server/itemmanager.cpp index 08adb9de..b80f295b 100644 --- a/src/game-server/itemmanager.cpp +++ b/src/game-server/itemmanager.cpp @@ -33,7 +33,7 @@ ItemManager::ItemManager(std::string const &itemReferenceFile) char *data = (char *)resman->loadFile(itemReferenceFile, size); if (!data) { - LOG_ERROR("Item Manager: Could not find " << itemReferenceFile << "!", 0); + LOG_ERROR("Item Manager: Could not find " << itemReferenceFile << "!"); free(data); return; } @@ -44,7 +44,7 @@ ItemManager::ItemManager(std::string const &itemReferenceFile) if (!doc) { LOG_ERROR("Item Manager: Error while parsing item database (" - << itemReferenceFile << ")!", 0); + << itemReferenceFile << ")!"); return; } @@ -52,16 +52,17 @@ ItemManager::ItemManager(std::string const &itemReferenceFile) if (!node || !xmlStrEqual(node->name, BAD_CAST "items")) { LOG_ERROR("Item Manager: " << itemReferenceFile - << " is not a valid database file!", 0); + << " is not a valid database file!"); xmlFreeDoc(doc); return; } - LOG_INFO("Loading item reference...", 0); + LOG_INFO("Loading item reference..."); unsigned nbItems = 0; for (node = node->xmlChildrenNode; node != NULL; node = node->next) { - if (!xmlStrEqual(node->name, BAD_CAST "item")) { + if (!xmlStrEqual(node->name, BAD_CAST "item")) + { continue; } @@ -70,7 +71,7 @@ ItemManager::ItemManager(std::string const &itemReferenceFile) if (id == 0) { LOG_WARN("Item Manager: An (ignored) item has no ID in " - << itemReferenceFile << "!", 0); + << itemReferenceFile << "!"); continue; } @@ -113,47 +114,21 @@ ItemManager::ItemManager(std::string const &itemReferenceFile) if (maxPerSlot == 0) { LOG_WARN("Item Manager: Missing max per slot properties for item: " - << id << " in " << itemReferenceFile << ".", 0); + << id << " in " << itemReferenceFile << "."); } if (weight == 0) { LOG_WARN("Item Manager: Missing weight for item: " - << id << " in " << itemReferenceFile << ".", 0); + << id << " in " << itemReferenceFile << "."); } - LOG_INFO("Item: ID: " << id << ", itemType: " << itemType - << ", weight: " << weight << ", value: " << value << - ", scriptName: " << scriptName << ", maxPerSlot: " << maxPerSlot << ".", 3); - // Log level 5 - LOG_INFO("Modifiers:: element: " << modifiers.element << - ", lifetime: " << modifiers.lifetime - << std::endl << - ", strength: " << modifiers.rawStats[STAT_STRENGTH] << - ", agility: " << modifiers.rawStats[STAT_AGILITY] << - ", vitality: " << modifiers.rawStats[STAT_VITALITY] - << std::endl << - ", intelligence: " << modifiers.rawStats[STAT_INTELLIGENCE] << - ", dexterity: " << modifiers.rawStats[STAT_DEXTERITY] << - ", luck: " << modifiers.rawStats[STAT_LUCK] - << std::endl << - ", heat: " << modifiers.computedStats[STAT_HEAT] << - ", attack: " << modifiers.computedStats[STAT_ATTACK] << - ", defence: " << modifiers.computedStats[STAT_DEFENCE] - << std::endl << - ", magic: " << modifiers.computedStats[STAT_MAGIC] << - ", accuracy: " << modifiers.computedStats[STAT_ACCURACY] << - ", speed: " << modifiers.computedStats[STAT_SPEED] << - std::endl << - ", hp: " << modifiers.hp << - ", mp: " << modifiers.mp << - std::endl << - ", range: " << modifiers.range << - ", weapon_type: " << modifiers.weaponType << - ", status_effect: " << modifiers.beingStateEffect, 5); + LOG_DEBUG("Item: ID: " << id << ", itemType: " << itemType + << ", weight: " << weight << ", value: " << value << + ", scriptName: " << scriptName << ", maxPerSlot: " << maxPerSlot << "."); } LOG_INFO("Loaded " << nbItems << " items from " - << itemReferenceFile << ".", 0); + << itemReferenceFile << "."); xmlFreeDoc(doc); } diff --git a/src/game-server/main-game.cpp b/src/game-server/main-game.cpp index 62a0c0e1..63e1f66e 100644 --- a/src/game-server/main-game.cpp +++ b/src/game-server/main-game.cpp @@ -144,14 +144,14 @@ void initialize() // Initialize the logger. using namespace utils; - Logger::instance().setLogFile(logPath); + Logger::setLogFile(logPath); // Write the messages to both the screen and the log file. - Logger::instance().setTeeMode(true); + Logger::setTeeMode(true); config.init(configPath); - LOG_INFO("Using config file: " << configPath, 0); - LOG_INFO("Using log file: " << logPath, 0); + LOG_INFO("Using config file: " << configPath); + LOG_INFO("Using log file: " << logPath); // --- Initialize the managers // Initialize the slang's and double quotes filter. @@ -178,7 +178,7 @@ void initialize() // --- Initialize scripting subsystem. #ifdef RUBY_SUPPORT - LOG_INFO("Script language: " << scriptLanguage, 0); + LOG_INFO("Script language: " << scriptLanguage); // Initialize ruby ruby_init(); @@ -192,7 +192,7 @@ void initialize() rb_load_file("scripts/init.rb"); rubyStatus = ruby_exec(); #else - LOG_WARN("No scripting language support.", 0); + LOG_WARN("No scripting language support."); #endif } @@ -271,15 +271,15 @@ void parseOptions(int argc, char *argv[]) // Set Verbosity to level unsigned short verbosityLevel; verbosityLevel = atoi(optarg); - utils::Logger::instance().setVerbosity(verbosityLevel); - LOG_INFO("Setting log verbosity level to " << verbosityLevel, 0); + utils::Logger::setVerbosity(utils::Logger::Level(verbosityLevel)); + LOG_INFO("Setting log verbosity level to " << verbosityLevel); break; case 'p': // Change the port to listen on. unsigned short portToListenOn; portToListenOn = atoi(optarg); config.setValue("gameServerPort", portToListenOn); - LOG_INFO("Setting default port to " << portToListenOn, 0); + LOG_INFO("Setting default port to " << portToListenOn); break; } } @@ -293,7 +293,7 @@ int main(int argc, char *argv[]) { int elapsedWorldTicks; - LOG_INFO("The Mana World Server v" << PACKAGE_VERSION, 0); + LOG_INFO("The Mana World Game Server v" << PACKAGE_VERSION); // Parse command line options parseOptions(argc, argv); @@ -330,12 +330,12 @@ int main(int argc, char *argv[]) { LOG_WARN(elapsedWorldTicks -1 << " World Tick(s) skipped " "because of insufficient time. Please buy a faster " - "machine ;-)", 0); + "machine ;-)"); }; // Print world time at 10 second intervals to show we're alive if (worldTime % 100 == 0) { - LOG_INFO("World time: " << worldTime, 0); + LOG_INFO("World time: " << worldTime); } // Handle all messages that are in the message queues @@ -349,7 +349,7 @@ int main(int argc, char *argv[]) worldTimer.sleep(); } - LOG_INFO("Received: Quit signal, closing down...", 0); + LOG_INFO("Received: Quit signal, closing down..."); gameHandler->stopListen(); accountHandler->stop(); delete gameState; diff --git a/src/game-server/mapmanager.cpp b/src/game-server/mapmanager.cpp index accf7ca0..1bceb8e2 100644 --- a/src/game-server/mapmanager.cpp +++ b/src/game-server/mapmanager.cpp @@ -37,7 +37,7 @@ MapManager::MapManager(std::string const &mapReferenceFile) char *data = (char *)resman->loadFile(mapReferenceFile, size); if (!data) { - LOG_ERROR("Map Manager: Could not find " << mapReferenceFile << "!", 0); + LOG_ERROR("Map Manager: Could not find " << mapReferenceFile << "!"); free(data); return; } @@ -48,7 +48,7 @@ MapManager::MapManager(std::string const &mapReferenceFile) if (!doc) { LOG_ERROR("Map Manager: Error while parsing map database (" - << mapReferenceFile << ")!", 0); + << mapReferenceFile << ")!"); return; } @@ -56,12 +56,12 @@ MapManager::MapManager(std::string const &mapReferenceFile) if (!node || !xmlStrEqual(node->name, BAD_CAST "maps")) { LOG_ERROR("Map Manager: " << mapReferenceFile - << " is not a valid database file!", 0); + << " is not a valid database file!"); xmlFreeDoc(doc); return; } - LOG_INFO("Loading map reference...", 0); + LOG_INFO("Loading map reference..."); for (node = node->xmlChildrenNode; node != NULL; node = node->next) { if (!xmlStrEqual(node->name, BAD_CAST "map")) { @@ -99,10 +99,10 @@ Map *MapManager::getMap(int mapId) map = MapReader::readMap("maps/" + file); if (!map) { - LOG_ERROR("Unable to load map \"" << file << "\" (id " << mapId << ")", 0); + LOG_ERROR("Unable to load map \"" << file << "\" (id " << mapId << ")"); return NULL; } - LOG_INFO("Loaded map \"" << file << "\" (id " << mapId << ")", 0); + LOG_INFO("Loaded map \"" << file << "\" (id " << mapId << ")"); } return map; } @@ -119,7 +119,7 @@ void MapManager::raiseActive(int mapId) Maps::iterator i = maps.find(mapId); assert(i != maps.end()); i->second.isActive = true; - LOG_INFO("Activating map \"" << i->second.fileName << "\" (id " << i->first << ")", 0); + LOG_INFO("Activating map \"" << i->second.fileName << "\" (id " << i->first << ")"); } bool MapManager::isActive(int mapId) const diff --git a/src/game-server/mapreader.cpp b/src/game-server/mapreader.cpp index 63d81a64..cc26f03f 100644 --- a/src/game-server/mapreader.cpp +++ b/src/game-server/mapreader.cpp @@ -44,7 +44,7 @@ Map *MapReader::readMap(const std::string &filename) if (buffer == NULL) { - LOG_ERROR("Error: Map file not found (" << filename.c_str() << ")", 0); + LOG_ERROR("Error: Map file not found (" << filename.c_str() << ")"); return NULL; } @@ -64,7 +64,7 @@ Map *MapReader::readMap(const std::string &filename) if (!doc) { - LOG_ERROR("Error while parsing map file (" << filename << ")!", 0); + LOG_ERROR("Error while parsing map file (" << filename << ")!"); return NULL; } @@ -78,7 +78,7 @@ Map *MapReader::readMap(const std::string &filename) } else { - LOG_ERROR("Error: Not a map file (" << filename << ")!", 0); + LOG_ERROR("Error: Not a map file (" << filename << ")!"); } xmlFreeDoc(doc); @@ -122,7 +122,7 @@ static Map *readMap(xmlNodePtr node, std::string const &path) { if (xmlHasProp(node, BAD_CAST "source")) { - LOG_WARN("Warning: External tilesets not supported yet.", 0); + LOG_WARN("Warning: External tilesets not supported yet."); } else { @@ -163,7 +163,7 @@ static void readLayer(xmlNodePtr node, Map *map) { if (xmlHasProp(node, BAD_CAST "compression")) { - LOG_WARN("Warning: no layer compression supported!", 0); + LOG_WARN("Warning: no layer compression supported!"); return; } diff --git a/src/net/connection.cpp b/src/net/connection.cpp index 8a5c8d0e..faff533c 100644 --- a/src/net/connection.cpp +++ b/src/net/connection.cpp @@ -79,7 +79,7 @@ void Connection::send(MessageOut const &msg, bool reliable, unsigned channel) } else { - LOG_WARN("Failure to create packet!", 0); + LOG_ERROR("Failure to create packet!"); } } @@ -92,12 +92,15 @@ void Connection::process() switch (event.type) { case ENET_EVENT_TYPE_RECEIVE: - if (event.packet->dataLength >= 2) { + if (event.packet->dataLength >= 2) + { MessageIn msg((char *)event.packet->data, event.packet->dataLength); processMessage(msg); - } else { - LOG_ERROR("Message too short.", 0); + } + else + { + LOG_WARN("Message too short."); } // Clean up the packet now that we are done using it. enet_packet_destroy(event.packet); diff --git a/src/net/connectionhandler.cpp b/src/net/connectionhandler.cpp index 7782a74a..69ac9337 100644 --- a/src/net/connectionhandler.cpp +++ b/src/net/connectionhandler.cpp @@ -49,7 +49,7 @@ bool ConnectionHandler::startListen(enet_uint16 port) address.host = ENET_HOST_ANY; address.port = port; - LOG_INFO("Listening on port " << port << "...", 0); + LOG_INFO("Listening on port " << port << "..."); host = enet_host_create(&address /* the address to bind the server host to */, MAX_CLIENTS /* allow up to MAX_CLIENTS clients and/or outgoing connections */, 0 /* assume any amount of incoming bandwidth */, @@ -96,7 +96,7 @@ void ConnectionHandler::process() LOG_INFO("A new client connected from " << ip4ToString(event.peer->address.host) << ":" << event.peer->address.port << " to port " << - host->address.port, 0); + host->address.port); NetComputer *comp = computerConnected(event.peer); clients.push_back(comp); @@ -124,13 +124,13 @@ void ConnectionHandler::process() if (event.packet->dataLength >= 2) { MessageIn msg((char *)event.packet->data, event.packet->dataLength); - LOG_INFO("Received message " << msg.getId() << " (" - << event.packet->dataLength << " B) from " - << *comp, 2); + LOG_DEBUG("Received message " << msg.getId() << " (" + << event.packet->dataLength << " B) from " + << *comp); processMessage(comp, msg); } else { - LOG_ERROR("Message too short from " << *comp, 0); + LOG_ERROR("Message too short from " << *comp); } /* Clean up the packet now that we're done using it. */ @@ -140,7 +140,7 @@ void ConnectionHandler::process() case ENET_EVENT_TYPE_DISCONNECT: { NetComputer *comp = (NetComputer *)event.peer->data; - LOG_INFO(ip4ToString(event.peer->address.host) << " disconnected.", 0); + LOG_INFO(ip4ToString(event.peer->address.host) << " disconnected."); // Reset the peer's client information. computerDisconnected(comp); clients.erase(std::find(clients.begin(), clients.end(), comp)); @@ -155,7 +155,8 @@ void ConnectionHandler::process() void ConnectionHandler::sendToEveryone(const MessageOut &msg) { for (NetComputers::iterator i = clients.begin(), i_end = clients.end(); - i != i_end; ++i) { + i != i_end; ++i) + { (*i)->send(msg); } } diff --git a/src/net/netcomputer.cpp b/src/net/netcomputer.cpp index f963db55..3e4a4dbc 100644 --- a/src/net/netcomputer.cpp +++ b/src/net/netcomputer.cpp @@ -63,8 +63,7 @@ void NetComputer::send(const MessageOut &msg, bool reliable, unsigned int channel) { - LOG_INFO("Sending packet of length " << msg.getLength() << " to " - << *this, 2); + LOG_DEBUG("Sending packet of length " << msg.getLength() << " to " << *this); ENetPacket *packet; packet = enet_packet_create(msg.getData(), @@ -77,7 +76,7 @@ NetComputer::send(const MessageOut &msg, bool reliable, } else { - LOG_WARN("Failure to create packet!", 0); + LOG_ERROR("Failure to create packet!"); } } diff --git a/src/resourcemanager.cpp b/src/resourcemanager.cpp index 0ddf5931..fc62299a 100644 --- a/src/resourcemanager.cpp +++ b/src/resourcemanager.cpp @@ -91,7 +91,7 @@ ResourceManager::searchAndAddZipFiles() std::string filePath = std::string("data/") + std::string(findFileInfo.name); - LOG_INFO("Adding to PhysicsFS: " << findFileInfo.name, 0); + LOG_INFO("Adding to PhysicsFS: " << findFileInfo.name); // Add the zip file to our PhysicsFS search path PHYSFS_addToSearchPath(filePath.c_str(), 1); @@ -127,7 +127,7 @@ ResourceManager::searchAndAddZipFiles() std::string filePath = std::string(programPath) + std::string("/") + std::string(direntry->d_name); - LOG_INFO("Adding to PhysicsFS: " << filePath, 0); + LOG_INFO("Adding to PhysicsFS: " << filePath); // Add the zip file to our PhysicsFS search path PHYSFS_addToSearchPath(filePath.c_str(), 1); @@ -143,7 +143,7 @@ ResourceManager::loadFile(const std::string &fileName, int &fileSize) { // If the file doesn't exist indicate failure if (!PHYSFS_exists(fileName.c_str())) { - LOG_WARN("Warning: " << fileName << " not found!", 0); + LOG_WARN("Warning: " << fileName << " not found!"); return NULL; } @@ -152,7 +152,7 @@ ResourceManager::loadFile(const std::string &fileName, int &fileSize) // If the handler is an invalid pointer indicate failure if (file == NULL) { - LOG_WARN("Warning: " << fileName << " failed to load!", 0); + LOG_WARN("Warning: " << fileName << " failed to load!"); return NULL; } @@ -178,7 +178,7 @@ ResourceManager::loadTextFile(const std::string &fileName) if (!fileContents) { - LOG_ERROR("Couldn't load text file: " << fileName, 0); + LOG_ERROR("Couldn't load text file: " << fileName); return lines; } diff --git a/src/skill.cpp b/src/skill.cpp index 9d9c3065..e059f549 100644 --- a/src/skill.cpp +++ b/src/skill.cpp @@ -61,9 +61,9 @@ bool Skill::useSkill() { #ifdef SCRIPT_SUPPORT //run skill script - LOG_ERROR("Skill: Skills not implemented.", 0); + LOG_ERROR("Skill: Skills not implemented."); #else - LOG_ERROR("Skill: Could not use skill; scripting disabled.", 0); + LOG_ERROR("Skill: Could not use skill; scripting disabled."); #endif return true; } @@ -77,8 +77,8 @@ bool Skill::deleteSkill(const std::string &ident, bool delTree) { //prevent deletion of self if (ident == id) { - LOG_ERROR("Skill: Attempt to delete self.", 0); - return false; + LOG_ERROR("Skill: Attempt to delete self."); + return false; } for (unsigned int i = 0; i < children.size(); i++) { diff --git a/src/utils/logger.cpp b/src/utils/logger.cpp index 36d43f80..f7d26059 100644 --- a/src/utils/logger.cpp +++ b/src/utils/logger.cpp @@ -23,6 +23,7 @@ #include "logger.h" #include <ctime> +#include <fstream> #include <iomanip> #include <iostream> @@ -33,257 +34,97 @@ namespace utils { +static std::ofstream mLogFile; /**< Log file. */ +bool Logger::mHasTimestamp = true; /**< Timestamp flag. */ +bool Logger::mTeeMode = false; /**< Tee mode flag. */ +Logger::Level Logger::mVerbosity = Logger::INFO; /**< Verbosity level. */ /** - * Default constructor. - */ -Logger::Logger(void) - throw() - : mHasTimestamp(true), - mTeeMode(false), - mVerbosity(0) + * Gets the current time. + * + * @return the current time as string. + */ +static std::string getCurrentTime() { - // NOOP -} - - -/** - * Destructor. - */ -Logger::~Logger(void) - throw() -{ - // the destructor of std::ofstream takes care of closing the file - // if it is still open :) -} - - -/** - * Set the log file. - */ -void -Logger::setLogFile(const std::string& logFile) -{ - // close the current log file. - if (mLogFile.is_open()) { - mLogFile.close(); - } - - // open the file for output and remove the former file contents. - mLogFile.open(logFile.c_str(), std::ios::trunc); - - if (!mLogFile.is_open()) { - std::string msg("unable to open "); - msg += logFile; - msg += " for writing."; - - throw std::ios::failure(msg); - } - else { - // by default the streams do not throw any exception - // let std::ios::failbit and std::ios::badbit throw exceptions. - mLogFile.exceptions(std::ios::failbit | std::ios::badbit); - } -} + time_t now; + tm local; + // get current time_t value + time(&now); -/** - * Add/remove the timestamp. - */ -void -Logger::setTimestamp(bool flag) - throw() -{ - mHasTimestamp = flag; -} + // convert time_t to tm struct to break the time into individual + // constituents + local = *(localtime(&now)); + // stringify the time, the format is: [hh:mm:ss] + using namespace std; + ostringstream os; + os << "[" << setw(2) << setfill('0') << local.tm_hour + << ":" << setw(2) << setfill('0') << local.tm_min + << ":" << setw(2) << setfill('0') << local.tm_sec + << "]"; -/** - * Set tee mode. - */ -void -Logger::setTeeMode(bool flag) - throw() -{ - mTeeMode = flag; + return os.str(); } - -/** - * Log a generic message. - */ -void -Logger::log(const std::string& msg, unsigned short atVerbosity) +void Logger::output(std::ostream &os, std::string const &msg, char const *prefix) { - if ( mVerbosity >= atVerbosity ) + if (mHasTimestamp) { - if (mTeeMode) { - log(std::cout, msg); - - if (mLogFile.is_open()) { - log(mLogFile, msg); - } - } - else { - log((mLogFile.is_open() ? mLogFile : std::cout), msg); - } + os << getCurrentTime() << ' '; } -} - -/** - * Log a debug message. - */ -void -Logger::debug(const std::string& msg, unsigned short atVerbosity) -{ - if ( mVerbosity >= atVerbosity ) + if (prefix) { - if (mTeeMode) { - log(std::cout, msg, "[DBG]"); - - if (mLogFile.is_open()) { - log(mLogFile, msg, "[DBG]"); - } - } - else { - log((mLogFile.is_open() ? mLogFile : std::cout), msg, "[DBG]"); - } + os << prefix << ' '; } -} + os << msg << std::endl; +} -/** - * Log an info message. - */ -void -Logger::info(const std::string& msg, unsigned short atVerbosity) +void Logger::setLogFile(std::string const &logFile) { - if ( mVerbosity >= atVerbosity ) + // Close the current log file. + if (mLogFile.is_open()) { - if (mTeeMode) { - log(std::cout, msg, "[INF]"); - - if (mLogFile.is_open()) { - log(mLogFile, msg, "[INF]"); - } - } - else { - log((mLogFile.is_open() ? mLogFile : std::cout), msg, "[INF]"); - } + mLogFile.close(); } -} + // Open the file for output and remove the former file contents. + mLogFile.open(logFile.c_str(), std::ios::trunc); -/** - * Log a warn message. - */ -void -Logger::warn(const std::string& msg, unsigned short atVerbosity) -{ - if ( mVerbosity >= atVerbosity ) + if (!mLogFile.is_open()) { - if (mTeeMode) { - log(std::cerr, msg, "[WRN]"); - - if (mLogFile.is_open()) { - log(mLogFile, msg, "[WRN]"); - } - } - else { - log((mLogFile.is_open() ? mLogFile : std::cerr), msg, "[WRN]"); - } + throw std::ios::failure("unable to open " + logFile + "for writing"); } -} - - -/** - * Log an error message. - */ -void -Logger::error(const std::string& msg, unsigned short atVerbosity) -{ - if ( mVerbosity >= atVerbosity ) + else { - if (mTeeMode) { - log(std::cerr, msg, "[ERR]"); - - if (mLogFile.is_open()) { - log(mLogFile, msg, "[ERR]"); - } - } - else { - log((mLogFile.is_open() ? mLogFile : std::cerr), msg, "[ERR]"); - } + // by default the streams do not throw any exception + // let std::ios::failbit and std::ios::badbit throw exceptions. + mLogFile.exceptions(std::ios::failbit | std::ios::badbit); } } - -/** - * Log a fatal error message. - */ -void -Logger::fatal(const std::string& msg, unsigned short atVerbosity) +void Logger::output(std::string const& msg, Level atVerbosity) { - if (mTeeMode) { - log(std::cerr, msg, "[FTL]"); - - if (mLogFile.is_open()) { - log(mLogFile, msg, "[FTL]"); - } - } - else { - log((mLogFile.is_open() ? mLogFile : std::cerr), msg, "[FTL]"); - } -} + static char const *prefixes[] = + { "[FTL]", "[ERR]", "[WRN]", "[INF]", "[DBG]" }; + if (mVerbosity >= atVerbosity) + { + bool open = mLogFile.is_open(); -/** - * Log a generic message. - */ -void -Logger::log(std::ostream& os, - const std::string& msg, - const std::string& prefix) -{ - if (mHasTimestamp) { - os << getCurrentTime() << " "; - } + if (open) + { + output(mLogFile, msg, prefixes[atVerbosity]); + } - if (prefix != "") { - os << prefix << " "; + if (!open || mTeeMode) + { + output(atVerbosity <= WARN ? std::cerr : std::cout, + msg, prefixes[atVerbosity]); + } } - - os << msg << std::endl; } - -/** - * Get the current time. - */ -std::string -Logger::getCurrentTime(void) -{ - time_t now; - tm local; - - // get current time_t value - time(&now); - - // convert time_t to tm struct to break the time into individual - // constituents - local = *(localtime(&now)); - - // stringify the time, the format is: [hh:mm:ss] - using namespace std; - ostringstream os; - os << "[" << setw(2) << setfill('0') << local.tm_hour - << ":" << setw(2) << setfill('0') << local.tm_min - << ":" << setw(2) << setfill('0') << local.tm_sec - << "]"; - - return os.str(); -} - - } // namespace utils diff --git a/src/utils/logger.h b/src/utils/logger.h index 2eeaded8..0669577b 100644 --- a/src/utils/logger.h +++ b/src/utils/logger.h @@ -25,11 +25,8 @@ #define _TMWSERV_LOGGER_H_ #include <iosfwd> -#include <fstream> #include <sstream> -#include "singleton.h" - namespace utils { @@ -43,9 +40,6 @@ namespace utils * Limitations: * - not thread-safe. * - * Notes: - * - this class implements the Meyer's singleton design pattern. - * * Example of use: * * <pre> @@ -55,11 +49,9 @@ namespace utils * { * using namespace utils; * - * Logger& logger = Logger::instance(); - * logger.setLogFile("/path/to/logfile"); + * Logger::setLogFile("/path/to/logfile"); * * // log messages using helper macros. - * LOG("hello world") * LOG_DEBUG("level: " << 3) * LOG_INFO("init sound") * LOG_WARN("not implemented") @@ -67,29 +59,33 @@ namespace utils * LOG_FATAL("unable to init graphics") * * // log messages using APIs. - * logger.log("hello world"); - * * std::ostringstream os; * os << "level: " << 3; - * logger.debug(os.str()); + * Logger::output(os.str(), Logger::DEBUG); * - * logger.info("init sound"); - * logger.warn("not implemented"); - * logger.error("resource not found"); - * logger.fatal("unable to init graphics"); + * Logger::output("init sound", Logger::INFO); + * Logger::output("not implemented", Logger::WARN); + * Logger::output("resource not found", Logger::ERROR); + * Logger::output("unable to init graphics", Logger::FATAL); * * return 0; * } * </pre> */ -class Logger: public Singleton<Logger> +class Logger { - // friend so that Singleton can call the constructor. - friend class Singleton<Logger>; - public: + enum Level + { + FATAL = 0, + ERROR, + WARN, + INFO, + DEBUG + }; + /** - * Set the log file. + * Sets the log file. * * This method will open the log file for writing, the former file * contents are removed. @@ -98,116 +94,36 @@ class Logger: public Singleton<Logger> * * @exception std::ios::failure if the log file could not be opened. */ - void - setLogFile(const std::string& logFile); + static void setLogFile(std::string const &logFile); /** - * Add/remove the timestamp. + * Add/removes the timestamp. * * @param flag if true, a log message will always be timestamped * (default = true). */ - void - setTimestamp(bool flag = true) - throw(); + static void setTimestamp(bool flag = true) + { mHasTimestamp = flag; } /** - * Set tee mode. + * Sets tee mode. * * @param flag if true, write messages to both the standard (or error) * output and the log file (if set) (default = true). */ - void - setTeeMode(bool flag = true) - throw(); + static void setTeeMode(bool flag = true) + { mTeeMode = flag; } /** - * Set the verbosity level of the logger. + * Sets the verbosity level of the logger. * * @param verbosity is the level of verbosity. - * 0 = Standard infos - * 1 = + Infos on loading/unloading/reloading resources - * 2 = + Packets names and messages sent. - */ - void - setVerbosity(unsigned short verbosity = 0) { mVerbosity = verbosity; } - - /** - * Set tee mode. - * - * @param flag if true, write messages to both the standard (or error) - * output and the log file (if set) (default = true). - */ - unsigned short - getVerbosity() { return mVerbosity; } - - /** - * Log a generic message. - * - * @param msg the message to log. - * - * @param atVerbosity the minimum verbosity level - * to log this - * - * @exception std::ios::failure. - */ - void - log(const std::string &msg, unsigned short atVerbosity = 0); - - /** - * Log a debug message. - * - * @param msg the message to log. - * - * @param atVerbosity the minimum verbosity level - * to log this - * - * @exception std::ios::failure. - */ - void - debug(const std::string &msg, unsigned short atVerbosity = 0); - - /** - * Log an info message. - * - * @param msg the message to log. - * - * @param atVerbosity the minimum verbosity level - * to log this - * - * @exception std::ios::failure. - */ - void - info(const std::string &msg, unsigned short atVerbosity = 0); - - /** - * Log a warn message. - * - * @param msg the message to log. - * - * @param atVerbosity the minimum verbosity level - * to log this - * - * @exception std::ios::failure. - */ - void - warn(const std::string &msg, unsigned short atVerbosity = 0); - - /** - * Log an error message. - * - * @param msg the message to log. - * - * @param atVerbosity the minimum verbosity level - * to log this - * - * @exception std::ios::failure. */ - void - error(const std::string &msg, unsigned short atVerbosity = 0); + static void setVerbosity(Level verbosity) + { mVerbosity = verbosity; } /** - * Log a fatal error message. + * Logs a generic message. * * @param msg the message to log. * @@ -216,60 +132,23 @@ class Logger: public Singleton<Logger> * * @exception std::ios::failure. */ - void - fatal(const std::string &msg, unsigned short atVerbosity = 0); + static void output(std::string const &msg, Level atVerbosity); + static Level mVerbosity; /**< Verbosity level. */ private: - /** - * Default constructor. - */ - Logger(void) - throw(); - - /** - * Destructor. - */ - ~Logger(void) - throw(); - - /** - * Copy constructor. - */ - Logger(const Logger& rhs); - - /** - * Assignment operator. - */ - Logger& - operator=(const Logger& rhs); + static bool mHasTimestamp; /**< Timestamp flag. */ + static bool mTeeMode; /**< Tee mode flag. */ /** - * Log a generic message. + * Logs a generic message. * * @param os the output stream. * @param msg the message to log. - * @param prefix the message prefix (default = ""). + * @param prefix the message prefix. * * @exception std::ios::failure. */ - void - log(std::ostream& os, - const std::string& msg, - const std::string& prefix = ""); - - /** - * Get the current time. - * - * @return the current time as string. - */ - std::string - getCurrentTime(void); - - - std::ofstream mLogFile; /**< the log file */ - bool mHasTimestamp; /**< the timestamp flag */ - bool mTeeMode; /**< the tee mode flag */ - unsigned short mVerbosity; /**< keeps the verbosity level */ + static void output(std::ostream &os, std::string const &msg, char const *prefix); }; @@ -277,47 +156,39 @@ class Logger: public Singleton<Logger> // HELPER MACROS - -#define LOG(msg, atVerbosity) \ - do { \ - std::ostringstream os; \ - os << msg; \ - ::utils::Logger::instance().log(os.str(), atVerbosity); \ - } while(0) - -#define LOG_DEBUG(msg, atVerbosity) \ - do { \ - std::ostringstream os; \ - os << msg; \ - ::utils::Logger::instance().debug(os.str(), atVerbosity); \ +#define LOG_DEBUG(msg) \ + do if (::utils::Logger::mVerbosity >= ::utils::Logger::DEBUG) { \ + std::ostringstream os; \ + os << msg; \ + ::utils::Logger::output(os.str(), ::utils::Logger::DEBUG); \ } while (0) -#define LOG_INFO(msg, atVerbosity) \ - do { \ - std::ostringstream os; \ - os << msg; \ - ::utils::Logger::instance().info(os.str(), atVerbosity); \ +#define LOG_INFO(msg) \ + do if (::utils::Logger::mVerbosity >= ::utils::Logger::INFO) { \ + std::ostringstream os; \ + os << msg; \ + ::utils::Logger::output(os.str(), ::utils::Logger::INFO); \ } while (0) -#define LOG_WARN(msg, atVerbosity) \ - do { \ - std::ostringstream os; \ - os << msg; \ - ::utils::Logger::instance().warn(os.str(), atVerbosity); \ +#define LOG_WARN(msg) \ + do if (::utils::Logger::mVerbosity >= ::utils::Logger::WARN) { \ + std::ostringstream os; \ + os << msg; \ + ::utils::Logger::output(os.str(), ::utils::Logger::WARN); \ } while (0) -#define LOG_ERROR(msg, atVerbosity) \ - do { \ - std::ostringstream os; \ - os << msg; \ - ::utils::Logger::instance().error(os.str(), atVerbosity); \ +#define LOG_ERROR(msg) \ + do if (::utils::Logger::mVerbosity >= ::utils::Logger::ERROR) { \ + std::ostringstream os; \ + os << msg; \ + ::utils::Logger::output(os.str(), ::utils::Logger::ERROR); \ } while (0) -#define LOG_FATAL(msg) \ - do { \ - std::ostringstream os; \ - os << msg; \ - ::utils::Logger::instance().fatal(os.str(), 0); \ +#define LOG_FATAL(msg) \ + do if (::utils::Logger::mVerbosity >= ::utils::Logger::FATAL) { \ + std::ostringstream os; \ + os << msg; \ + ::utils::Logger::output(os.str(), ::utils::Logger::FATAL); \ } while (0) #endif // _TMWSERV_LOGGER_H_ diff --git a/src/utils/stringfilter.cpp b/src/utils/stringfilter.cpp index 79480838..ba1f1b99 100644 --- a/src/utils/stringfilter.cpp +++ b/src/utils/stringfilter.cpp @@ -77,7 +77,7 @@ void StringFilter::writeSlangFilterList() bool StringFilter::filterContent(const std::string& text) { if (!mInitialized) { - LOG_INFO("Slangs List is not initialized.", 2); + LOG_DEBUG("Slangs List is not initialized."); return true; } @@ -109,7 +109,6 @@ bool StringFilter::isEmailValid(const std::string& email) if ((email.length() < MIN_EMAIL_LENGTH) || (email.length() > MAX_EMAIL_LENGTH)) { - LOG_INFO(email << ": Email too short or too long.", 1); return false; } diff --git a/src/utils/zlib.cpp b/src/utils/zlib.cpp index b72c70f5..48e01c5f 100644 --- a/src/utils/zlib.cpp +++ b/src/utils/zlib.cpp @@ -31,16 +31,16 @@ static void logZlibError(int error) switch (error) { case Z_MEM_ERROR: - LOG_ERROR("Out of memory while decompressing data!", 0); + LOG_ERROR("Out of memory while decompressing data!"); break; case Z_VERSION_ERROR: - LOG_ERROR("Incompatible zlib version!", 0); + LOG_ERROR("Incompatible zlib version!"); break; case Z_DATA_ERROR: - LOG_ERROR("Incorrect zlib compressed data!", 0); + LOG_ERROR("Incorrect zlib compressed data!"); break; default: - LOG_ERROR("Unknown error while decompressing data!", 0); + LOG_ERROR("Unknown error while decompressing data!"); } } |