diff options
author | Yohann Ferreira <bertram@cegetel.net> | 2005-12-20 21:08:00 +0000 |
---|---|---|
committer | Yohann Ferreira <bertram@cegetel.net> | 2005-12-20 21:08:00 +0000 |
commit | c390ec7befcfeeda8504bdd74eb823b7ab721bf3 (patch) | |
tree | ad1c0164748a96ea5cb0a9b546585b7dd1c371f2 | |
parent | 609d235de3435fdc768207e59a2ee85172f291ba (diff) | |
download | manaserv-c390ec7befcfeeda8504bdd74eb823b7ab721bf3.tar.gz manaserv-c390ec7befcfeeda8504bdd74eb823b7ab721bf3.tar.bz2 manaserv-c390ec7befcfeeda8504bdd74eb823b7ab721bf3.tar.xz manaserv-c390ec7befcfeeda8504bdd74eb823b7ab721bf3.zip |
Adding command line argument parsing and log verbosity level handling.
-rw-r--r-- | ChangeLog | 6 | ||||
-rw-r--r-- | src/accounthandler.cpp | 106 | ||||
-rw-r--r-- | src/configuration.cpp | 7 | ||||
-rw-r--r-- | src/connectionhandler.cpp | 25 | ||||
-rw-r--r-- | src/dalstorage.cpp | 20 | ||||
-rw-r--r-- | src/main.cpp | 94 | ||||
-rw-r--r-- | src/mapmanager.cpp | 8 | ||||
-rw-r--r-- | src/mapreader.cpp | 18 | ||||
-rw-r--r-- | src/messagehandler.cpp | 2 | ||||
-rw-r--r-- | src/resourcemanager.cpp | 14 | ||||
-rw-r--r-- | src/skill.cpp | 6 | ||||
-rw-r--r-- | src/utils/logger.cpp | 111 | ||||
-rw-r--r-- | src/utils/logger.h | 98 |
13 files changed, 311 insertions, 204 deletions
@@ -1,6 +1,12 @@ 2005-12-20 Yohann Ferreira <bertram@cegetel.net> * src/Makefile.am: Adding the MapManager to files list. + * src/utils/logger.cpp, src/utils/logger.h, src/main.cpp, + src/configuration.cpp, src/connectionhandler.cpp, + src/mapmanager.cpp, src/mapreader.cpp, src/messagehandler.cpp, + src/skill.cpp, src/resourcemanager.cpp, src/dalstorage.cpp, + src/accounthandler.cpp: Adding command line argument parsing and + log verbosity level handling. 2005-12-18 Eugenio Favalli <elvenprogrammer@gmail.com> diff --git a/src/accounthandler.cpp b/src/accounthandler.cpp index 27865577..7441400e 100644 --- a/src/accounthandler.cpp +++ b/src/accounthandler.cpp @@ -27,7 +27,7 @@ #include "account.h" #include "messageout.h" #include "configuration.h" -#include <iostream> +#include "utils/logger.h" #include <cctype> using tmwserv::Account; @@ -61,12 +61,12 @@ void AccountHandler::receiveMessage(NetComputer &computer, MessageIn &message) { std::string username = message.readString(); std::string password = message.readString(); - std::cout << username << " is trying to login." << std::endl; + LOG_INFO(username << " is trying to login.", 1) if (computer.getAccount().get() != NULL) { - std::cout << "Already logged in as " << computer.getAccount()->getName() - << "." << std::endl; - std::cout << "Please logout first." << std::endl; + LOG_INFO("Already logged in as " << computer.getAccount()->getName() + << ".", 1) + LOG_INFO("Please logout first.", 1) result.writeShort(SMSG_LOGIN_ERROR); result.writeShort(LOGIN_ALREADY_LOGGED); break; @@ -77,18 +77,18 @@ void AccountHandler::receiveMessage(NetComputer &computer, MessageIn &message) if (!acc.get()) { // account doesn't exist -- send error to client - std::cout << username << ": Account does not exist." << std::endl; + LOG_INFO(username << ": Account does not exist.", 1) result.writeShort(SMSG_LOGIN_ERROR); result.writeByte(LOGIN_INVALID_USERNAME); } else if (acc->getPassword() != password) { // bad password -- send error to client - std::cout << "Bad password for " << username << std::endl; + LOG_INFO("Bad password for " << username, 1) result.writeShort(SMSG_LOGIN_ERROR); result.writeByte(LOGIN_INVALID_PASSWORD); } else { - std::cout << "Login OK by " << username << std::endl; + LOG_INFO("Login OK by " << username, 1) // Associate account with connection computer.setAccount(acc); @@ -99,15 +99,16 @@ void AccountHandler::receiveMessage(NetComputer &computer, MessageIn &message) tmwserv::Beings &chars = computer.getAccount()->getCharacters(); result.writeByte(chars.size()); - std::cout << username << "'s account has " << chars.size() << " character(s)." << std::endl; - + LOG_INFO(username << "'s account has " << chars.size() << " character(s).", 1) + std::string charNames = ""; for (unsigned int i = 0; i < chars.size(); i++) { result.writeString(chars[i]->getName()); - if (i >0) std::cout << ", "; - std::cout << chars[i]->getName(); + if (i >0) charNames += ", "; + charNames += chars[i]->getName(); } - std::cout << "." << std::endl; + charNames += "."; + LOG_INFO(charNames.c_str(), 1) } } break; @@ -116,7 +117,7 @@ void AccountHandler::receiveMessage(NetComputer &computer, MessageIn &message) { if ( computer.getAccount().get() == NULL ) { - std::cout << "Can't logout. Not even logged in." << std::endl; + LOG_INFO("Can't logout. Not even logged in.", 1) result.writeShort(SMSG_LOGOUT_ERROR); result.writeByte(LOGOUT_UNSUCCESSFULL); } @@ -125,7 +126,7 @@ void AccountHandler::receiveMessage(NetComputer &computer, MessageIn &message) std::string username = computer.getAccount()->getName(); if ( username == "" ) { - std::cout << "Account without name ? Logged out anyway..." << std::endl; + LOG_INFO("Account without name ? Logged out anyway...", 1) // computer.unsetCharacter(); Done by unsetAccount(); computer.unsetAccount(); result.writeShort(SMSG_LOGOUT_ERROR); @@ -133,7 +134,7 @@ void AccountHandler::receiveMessage(NetComputer &computer, MessageIn &message) } else { - std::cout << computer.getAccount()->getName() << " logs out." << std::endl; + LOG_INFO(computer.getAccount()->getName() << " logs out.", 1) // computer.unsetCharacter(); Done by unsetAccount(); computer.unsetAccount(); result.writeShort(SMSG_LOGOUT_CONFIRM); @@ -150,7 +151,7 @@ void AccountHandler::receiveMessage(NetComputer &computer, MessageIn &message) std::string email = message.readString(); // checking conditions for having a good account. - std::cout << username << " is trying to register." << std::endl; + LOG_INFO(username << " is trying to register.", 1) bool emailValid = false; // Testing Email validity @@ -158,14 +159,14 @@ void AccountHandler::receiveMessage(NetComputer &computer, MessageIn &message) { result.writeShort(SMSG_REGISTER_RESPONSE); result.writeByte(REGISTER_INVALID_EMAIL); - std::cout << email << ": Email too short or too long." << std::endl; + LOG_INFO(email << ": Email too short or too long.", 1) break; } if (store.doesEmailAlreadyExists(email)) // Search if Email already exists { result.writeShort(SMSG_REGISTER_RESPONSE); result.writeByte(REGISTER_EXISTS_EMAIL); - std::cout << email << ": Email already exists." << std::endl; + LOG_INFO(email << ": Email already exists.", 1) break; } if ((email.find_first_of('@') != std::string::npos)) // Searching for an @. @@ -186,25 +187,25 @@ void AccountHandler::receiveMessage(NetComputer &computer, MessageIn &message) { result.writeShort(SMSG_REGISTER_RESPONSE); result.writeByte(REGISTER_EXISTS_USERNAME); - std::cout << username << ": Username already exists." << std::endl; + LOG_INFO(username << ": Username already exists.", 1) } else if ((username.length() < MIN_LOGIN_LENGTH) || (username.length() > MAX_LOGIN_LENGTH)) // Username length { result.writeShort(SMSG_REGISTER_RESPONSE); result.writeByte(REGISTER_INVALID_USERNAME); - std::cout << username << ": Username too short or too long." << std::endl; + LOG_INFO(username << ": Username too short or too long.", 1) } else if ((password.length() < MIN_PASSWORD_LENGTH) || (password.length() > MAX_PASSWORD_LENGTH)) { result.writeShort(SMSG_REGISTER_RESPONSE); result.writeByte(REGISTER_INVALID_PASSWORD); - std::cout << email << ": Password too short or too long." << std::endl; + LOG_INFO(email << ": Password too short or too long.", 1) } else if (!emailValid) { result.writeShort(SMSG_REGISTER_RESPONSE); result.writeByte(REGISTER_INVALID_EMAIL); - std::cout << email << ": Email Invalid, only a@b.c format is accepted." << std::endl; + LOG_INFO(email << ": Email Invalid, only a@b.c format is accepted.", 1) } else { @@ -215,7 +216,7 @@ void AccountHandler::receiveMessage(NetComputer &computer, MessageIn &message) result.writeByte(REGISTER_OK); store.flush(); // flush changes - std::cout << username << ": Account registered." << std::endl; + LOG_INFO(username << ": Account registered.", 1) } } break; @@ -224,20 +225,20 @@ void AccountHandler::receiveMessage(NetComputer &computer, MessageIn &message) { std::string username = message.readString(); std::string password = message.readString(); - std::cout << username << " wants to be deleted from our accounts." << std::endl; + LOG_INFO(username << " wants to be deleted from our accounts.", 1) // see if the account exists Account *acc = store.getAccount(username); if (!acc) { // account doesn't exist -- send error to client - std::cout << username << ": Account doesn't exist anyway." << std::endl; + LOG_INFO(username << ": Account doesn't exist anyway.", 1) result.writeShort(SMSG_UNREGISTER_RESPONSE); result.writeByte(UNREGISTER_INVALID_USERNAME); } else if (acc->getPassword() != password) { // bad password -- send error to client - std::cout << "Won't delete it : Bad password for " << username << "." << std::endl; + LOG_INFO("Won't delete it : Bad password for " << username << ".", 1) result.writeShort(SMSG_UNREGISTER_RESPONSE); result.writeByte(UNREGISTER_INVALID_PASSWORD); @@ -254,7 +255,7 @@ void AccountHandler::receiveMessage(NetComputer &computer, MessageIn &message) } } // delete account and associated characters - std::cout << "Farewell " << username << " ..." << std::endl; + LOG_INFO("Farewell " << username << " ...", 1) store.delAccount(username); store.flush(); result.writeShort(SMSG_UNREGISTER_RESPONSE); @@ -268,7 +269,7 @@ void AccountHandler::receiveMessage(NetComputer &computer, MessageIn &message) if (computer.getAccount().get() == NULL) { result.writeShort(SMSG_CHAR_CREATE_RESPONSE); result.writeByte(CREATE_NOLOGIN); - std::cout << "Not logged in. Can't create a Character." << std::endl; + LOG_INFO("Not logged in. Can't create a Character.", 1) break; } @@ -278,7 +279,8 @@ void AccountHandler::receiveMessage(NetComputer &computer, MessageIn &message) { result.writeShort(SMSG_CHAR_CREATE_RESPONSE); result.writeByte(CREATE_TOO_MUCH_CHARACTERS); - std::cout << "Already has " << MAX_OF_CHARACTERS << " characters. Can't create another Character." << std::endl; + LOG_INFO("Already has " << MAX_OF_CHARACTERS + << " characters. Can't create another Character.", 1) break; } @@ -288,7 +290,7 @@ void AccountHandler::receiveMessage(NetComputer &computer, MessageIn &message) { result.writeShort(SMSG_CHAR_CREATE_RESPONSE); result.writeByte(CREATE_EXISTS_NAME); - std::cout << name << ": Character's name already exists." << std::endl; + LOG_INFO(name << ": Character's name already exists.", 1) break; } // Check for character's name length @@ -296,7 +298,7 @@ void AccountHandler::receiveMessage(NetComputer &computer, MessageIn &message) { result.writeShort(SMSG_CHAR_CREATE_RESPONSE); result.writeByte(CREATE_INVALID_NAME); - std::cout << name << ": Character's name too short or too long." << std::endl; + LOG_INFO(name << ": Character's name too short or too long.", 1) break; } //char hairStyle = message.readByte(); @@ -308,8 +310,8 @@ void AccountHandler::receiveMessage(NetComputer &computer, MessageIn &message) tmwserv::BeingPtr newCharacter(new tmwserv::Being(name, sex, 1, 0, stats)); computer.getAccount()->addCharacter(newCharacter); - std::cout << "Character " << name << " was created for " - << computer.getAccount()->getName() << "'s account." << std::endl; + LOG_INFO("Character " << name << " was created for " + << computer.getAccount()->getName() << "'s account.", 1) store.flush(); // flush changes result.writeShort(SMSG_CHAR_CREATE_RESPONSE); @@ -323,7 +325,7 @@ void AccountHandler::receiveMessage(NetComputer &computer, MessageIn &message) { result.writeShort(SMSG_CHAR_SELECT_RESPONSE); result.writeByte(SELECT_NOLOGIN); - std::cout << "Not logged in. Can't select a Character." << std::endl; + LOG_INFO("Not logged in. Can't select a Character.", 1) break; // not logged in } @@ -334,14 +336,14 @@ void AccountHandler::receiveMessage(NetComputer &computer, MessageIn &message) if ( chars.size() == 0 ) { result.writeByte(SELECT_NOT_YET_CHARACTERS); - std::cout << "Character Selection : Yet no characters created." << std::endl; + LOG_INFO("Character Selection : Yet no characters created.", 1) break; } // Character ID = 0 to Number of Characters - 1. if (charNum >= chars.size()) { // invalid char selection result.writeByte(SELECT_INVALID); - std::cout << "Character Selection : Selection out of ID range." << std::endl; + LOG_INFO("Character Selection : Selection out of ID range.", 1) break; } @@ -349,9 +351,9 @@ void AccountHandler::receiveMessage(NetComputer &computer, MessageIn &message) computer.setCharacter(chars[charNum]); result.writeByte(SELECT_OK); - std::cout << "Selected Character " << int(charNum) + LOG_INFO("Selected Character " << int(charNum) << " : " << - computer.getCharacter()->getName() << std::endl; + computer.getCharacter()->getName(), 1) } break; @@ -361,7 +363,7 @@ void AccountHandler::receiveMessage(NetComputer &computer, MessageIn &message) { result.writeShort(SMSG_CHAR_DELETE_RESPONSE); result.writeByte(DELETE_NOLOGIN); - std::cout << "Not logged in. Can't delete a Character." << std::endl; + LOG_INFO("Not logged in. Can't delete a Character.", 1) break; // not logged in } @@ -372,14 +374,15 @@ void AccountHandler::receiveMessage(NetComputer &computer, MessageIn &message) if ( chars.size() == 0 ) { result.writeByte(DELETE_NO_MORE_CHARACTERS); - std::cout << "Character Deletion : No characters in this account." << std::endl; + LOG_INFO("Character Deletion : No characters in " << computer.getAccount()->getName() + << "'s account.", 1) break; } // Character ID = 0 to Number of Characters - 1. if (charNum >= chars.size()) { // invalid char selection result.writeByte(DELETE_INVALID_NAME); - std::cout << "Character Deletion : Selection out of ID range." << std::endl; + LOG_INFO("Character Deletion : Selection out of ID range.", 1) break; } @@ -397,7 +400,7 @@ void AccountHandler::receiveMessage(NetComputer &computer, MessageIn &message) std::string deletedCharacter = chars[charNum].get()->getName(); computer.getAccount()->delCharacter(deletedCharacter); store.flush(); - std::cout << deletedCharacter << ": Character deleted..." << std::endl; + LOG_INFO(deletedCharacter << ": Character deleted...", 1) result.writeByte(DELETE_OK); } @@ -409,7 +412,7 @@ void AccountHandler::receiveMessage(NetComputer &computer, MessageIn &message) { result.writeShort(SMSG_CHAR_LIST_RESPONSE); result.writeByte(CHAR_LIST_NOLOGIN); - std::cout << "Not logged in. Can't list characters." << std::endl; + LOG_INFO("Not logged in. Can't list characters.", 1) break; // not logged in } @@ -419,14 +422,14 @@ void AccountHandler::receiveMessage(NetComputer &computer, MessageIn &message) tmwserv::Beings &chars = computer.getAccount()->getCharacters(); result.writeByte(chars.size()); - std::cout << computer.getAccount()->getName() << "'s account has " - << chars.size() << " character(s)." << std::endl; - + LOG_INFO(computer.getAccount()->getName() << "'s account has " + << chars.size() << " character(s).", 1) + std::string charStats = ""; for (unsigned int i = 0; i < chars.size(); i++) { result.writeString(chars[i]->getName()); - if (i >0) std::cout << ", "; - std::cout << chars[i]->getName(); + if (i >0) charStats += ", "; + charStats += chars[i]->getName(); result.writeByte(unsigned(short(chars[i]->getGender()))); result.writeByte(chars[i]->getLevel()); result.writeByte(chars[i]->getMoney()); @@ -437,12 +440,13 @@ void AccountHandler::receiveMessage(NetComputer &computer, MessageIn &message) result.writeByte(chars[i]->getDexterity()); result.writeByte(chars[i]->getLuck()); } - std::cout << "." << std::endl; + charStats += "."; + LOG_INFO(charStats.c_str(), 1) } break; default: - std::cout << "Invalid message type" << std::endl; + LOG_WARN("Invalid message type", 0) result.writeShort(SMSG_LOGIN_ERROR); result.writeByte(LOGIN_UNKNOWN); break; diff --git a/src/configuration.cpp b/src/configuration.cpp index 703d2c20..5f9caa2d 100644 --- a/src/configuration.cpp +++ b/src/configuration.cpp @@ -66,7 +66,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() << ")") + LOG_WARN("Warning: No configuration file (" << filename.c_str() << ")", 0) return; } @@ -131,9 +131,8 @@ void Configuration::write() void Configuration::setValue(const std::string &key, std::string value) { -#ifdef __DEBUG - std::cout << "Configuration::setValue(" << key << ", " << value << ")\n"; -#endif + LOG_DEBUG("Configuration::setValue(" << key << ", " << value << ")", 2) + options[key] = value; // Notify listeners diff --git a/src/connectionhandler.cpp b/src/connectionhandler.cpp index 52186187..c8ed1c6e 100644 --- a/src/connectionhandler.cpp +++ b/src/connectionhandler.cpp @@ -103,13 +103,13 @@ ConnectionHandler::startListen(ListenThreadData *ltd) // Allocate a socket set SDLNet_SocketSet set = SDLNet_AllocSocketSet(MAX_CLIENTS); if (!set) { - LOG_FATAL("SDLNet_AllocSocketSet: " << SDLNet_GetError()) + LOG_FATAL("SDLNet_AllocSocketSet: " << SDLNet_GetError(), 0) exit(1); } // Add the server socket to the socket set if (SDLNet_TCP_AddSocket(set, ltd->socket) < 0) { - LOG_FATAL("SDLNet_AddSocket: " << SDLNet_GetError()) + LOG_FATAL("SDLNet_AddSocket: " << SDLNet_GetError(), 0) exit(1); } @@ -118,12 +118,12 @@ ConnectionHandler::startListen(ListenThreadData *ltd) int numready = SDLNet_CheckSockets(set, 100); if (numready == -1) { - LOG_ERROR("SDLNet_CheckSockets: " << SDLNet_GetError()) + LOG_ERROR("SDLNet_CheckSockets: " << SDLNet_GetError(), 0) // When this is a system error, perror may help us perror("SDLNet_CheckSockets"); } else if (numready > 0) { - LOG_INFO(numready << " sockets with activity!") + LOG_INFO(numready << " sockets with activity!", 0) // Check server socket if (SDLNet_SocketReady(ltd->socket)) { @@ -132,13 +132,13 @@ ConnectionHandler::startListen(ListenThreadData *ltd) if (client) { // Add the client socket to the socket set if (SDLNet_TCP_AddSocket(set, client) < 0) { - LOG_ERROR("SDLNet_AddSocket: " << SDLNet_GetError()) + LOG_ERROR("SDLNet_AddSocket: " << SDLNet_GetError(), 0) } else { NetComputer *comp = new NetComputer(this, client); clients.push_back(comp); computerConnected(comp); - LOG_INFO(clients.size() << " client(s) connected") + LOG_INFO(clients.size() << " client(s) connected", 0) } } } @@ -168,10 +168,7 @@ ConnectionHandler::startListen(ListenThreadData *ltd) //buffer[result] = 0; //LOG_INFO("Received: " << buffer << ", Length: " // << result); - - - LOG_INFO("Received length: " - << result); + LOG_INFO("Received length: " << result, 2); #ifdef SCRIPT_SUPPORT // This could be good if you wanted to extend the @@ -207,11 +204,11 @@ ConnectionHandler::startListen(ListenThreadData *ltd) else { // bad message (no registered handler) LOG_ERROR("Unhandled message (" << messageId - << ") received from " << ipaddr); + << ") received from " << ipaddr, 0); } } else { - LOG_ERROR("Message too short from " << ipaddr); + LOG_ERROR("Message too short from " << ipaddr, 0); } } } @@ -234,12 +231,12 @@ ConnectionHandler::startListen(ListenThreadData *ltd) void ConnectionHandler::computerConnected(NetComputer *comp) { - LOG_INFO("A client connected!") + LOG_INFO("A client connected!", 0) } void ConnectionHandler::computerDisconnected(NetComputer *comp) { - LOG_INFO("A client disconnected!") + LOG_INFO("A client disconnected!", 0) } void ConnectionHandler::registerHandler( diff --git a/src/dalstorage.cpp b/src/dalstorage.cpp index 1a9a5141..fc3a70d9 100644 --- a/src/dalstorage.cpp +++ b/src/dalstorage.cpp @@ -81,7 +81,7 @@ DALStorage::open(void) mDb->connect(getName(), getUser(), getPassword()); if (!dbFileShown) { - LOG_INFO("Using " << dbFile << " as Database Name.") + LOG_INFO("Using " << dbFile << " as Database Name.", 0) dbFileShown = true; } #elif defined (SQLITE_SUPPORT) @@ -90,7 +90,7 @@ DALStorage::open(void) mDb->connect(dbFile, "", ""); if (!dbFileShown) { - LOG_INFO("SQLite uses ./" << dbFile << " as DB.") + LOG_INFO("SQLite uses ./" << dbFile << " as DB.", 0) dbFileShown = true; } #endif @@ -135,10 +135,10 @@ DALStorage::open(void) createTable(INVENTORIES_TBL_NAME, SQL_INVENTORIES_TABLE); } catch (const DbConnectionFailure& e) { - LOG_ERROR("unable to connect to the database: " << e.what()) + LOG_ERROR("unable to connect to the database: " << e.what(), 0) } catch (const DbSqlQueryExecFailure& e) { - LOG_ERROR("SQL query failure: " << e.what()) + LOG_ERROR("SQL query failure: " << e.what(), 0) } mIsOpen = mDb->isConnected(); @@ -225,8 +225,8 @@ DALStorage::getAccount(const std::string& userName) if (!charInfo.isEmpty()) { Beings beings; - std::cout << userName << "'s account has " << charInfo.rows() - << " character(s) in database." << std::endl; + LOG_INFO(userName << "'s account has " << charInfo.rows() + << " character(s) in database.", 1) // As the recordset functions are set to be able to get one recordset // at a time, we store charInfo in a temp array of strings @@ -365,7 +365,7 @@ DALStorage::delAccount(const std::string& userName) } catch (const dal::DbSqlQueryExecFailure& e) { // TODO: throw an exception. - LOG_ERROR("SQL query failure: " << e.what()) + LOG_ERROR("SQL query failure: " << e.what(), 0) } } @@ -398,7 +398,7 @@ DALStorage::getEmailList() } catch (const dal::DbSqlQueryExecFailure& e) { // TODO: throw an exception. - LOG_ERROR("SQL query failure: " << e.what()) + LOG_ERROR("SQL query failure: " << e.what(), 0) } return emailList; @@ -441,7 +441,7 @@ DALStorage::doesEmailAlreadyExists(std::string email) } catch (const dal::DbSqlQueryExecFailure& e) { // TODO: throw an exception. - LOG_ERROR("SQL query failure: " << e.what()) + LOG_ERROR("SQL query failure: " << e.what(), 0) } return false; @@ -485,7 +485,7 @@ DALStorage::doesCharacterNameExists(std::string name) } catch (const dal::DbSqlQueryExecFailure& e) { // TODO: throw an exception. - LOG_ERROR("SQL query failure: " << e.what()) + LOG_ERROR("SQL query failure: " << e.what(), 0) } return false; diff --git a/src/main.cpp b/src/main.cpp index f3064eda..2e50f440 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -21,6 +21,7 @@ */ #include <cstdlib> +#include <getopt.h> #include <iostream> #include <physfs.h> #include <SDL.h> @@ -95,7 +96,7 @@ Uint32 worldTick(Uint32 interval, void *param) event.type = TMW_WORLD_TICK; if (SDL_PushEvent(&event)) { - LOG_WARN("couldn't push world tick into event queue!") + LOG_WARN("couldn't push world tick into event queue!", 0) } return interval; @@ -115,7 +116,7 @@ void initialize() // initialize SDL. if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER) == -1) { - LOG_FATAL("SDL_Init: " << SDL_GetError()) + LOG_FATAL("SDL_Init: " << SDL_GetError(), 0) exit(1); } @@ -124,7 +125,7 @@ void initialize() // initialize SDL_net. if (SDLNet_Init() == -1) { - LOG_FATAL("SDLNet_Init: " << SDLNet_GetError()) + LOG_FATAL("SDLNet_Init: " << SDLNet_GetError(), 0) exit(2); } @@ -133,7 +134,7 @@ void initialize() // initialize scripting subsystem. #ifdef RUBY_SUPPORT - LOG_INFO("Script Language: " << scriptLanguage) + LOG_INFO("Script Language: " << scriptLanguage, 0) // initialize ruby ruby_init(); @@ -147,17 +148,17 @@ void initialize() rb_load_file("scripts/init.rb"); rubyStatus = ruby_exec(); #else - LOG_WARN("No Scripting Language Support.") + LOG_WARN("No Scripting Language Support.", 0) #endif #if defined (MYSQL_SUPPORT) - LOG_INFO("Using MySQL DB Backend.") + LOG_INFO("Using MySQL DB Backend.", 0) #elif defined (POSTGRESQL_SUPPORT) - LOG_INFO("Using PostGreSQL DB Backend.") + LOG_INFO("Using PostGreSQL DB Backend.", 0) #elif defined (SQLITE_SUPPORT) - LOG_INFO("Using SQLite DB Backend.") + LOG_INFO("Using SQLite DB Backend.", 0) #else - LOG_WARN("No Database Backend Support.") + LOG_WARN("No Database Backend Support.", 0) #endif // initialize configuration @@ -173,12 +174,12 @@ void initialize() #endif configPath += "/.tmwserv.xml"; config.init(configPath); - LOG_INFO("Using Config File: " << configPath) - LOG_INFO("Using Log File: " << LOG_FILE) - + LOG_INFO("Using Config File: " << configPath, 0) + LOG_INFO("Using Log File: " << LOG_FILE, 0) + // Initialize PhysicsFS PHYSFS_init(""); - + // TODO: only a test, maps should be loaded as they are needed tmwserv::MapManager::instance().loadMap("tulimshar.tmx.gz"); tmwserv::MapManager::instance().reloadMap("tulimshar.tmx.gz"); @@ -213,19 +214,74 @@ void deinitialize() // Get rid of persistent data storage tmwserv::Storage::destroy(); - + PHYSFS_deinit(); } /** + * Show command line arguments + */ +void printHelp() +{ + std::cout << "tmwserv" << std::endl << std::endl; + std::cout << "Options: " << std::endl; + std::cout << " -h --help : Display this help" << std::endl; + std::cout << " --verbosity n : Set the verbosity level" << std::endl; + exit(0); +} + +/** + * Parse the command line arguments + */ +void parseOptions(int argc, char *argv[]) +{ + const char *optstring = "h"; + + const struct option long_options[] = { + { "help", no_argument, 0, 'h' }, + { "verbosity", required_argument, 0, 'v' }, + 0 + }; + + while (optind < argc) { + int result = getopt_long(argc, argv, optstring, long_options, NULL); + + if (result == -1) { + break; + } + + switch (result) { + default: // Unknown option + case 'h': + // Print help + printHelp(); + break; + case 'v': + // Set Verbosity to level + unsigned short verbosityLevel = atoi(optarg); + tmwserv::utils::Logger::instance().setVerbosity(verbosityLevel); + LOG_INFO("Setting Log Verbosity Level to " << verbosityLevel, 0) + break; + } + } +} + + +/** * Main function, initializes and runs server. */ int main(int argc, char *argv[]) { #ifdef __USE_UNIX98 - LOG_INFO("The Mana World Server v" << PACKAGE_VERSION) + LOG_INFO("The Mana World Server v" << PACKAGE_VERSION, 0) #endif + // General Initialization + initialize(); + + // Parse Command Line Options + parseOptions(argc, argv); + // Ready for server work... std::auto_ptr<NetSession> session(new NetSession()); @@ -257,10 +313,8 @@ int main(int argc, char *argv[]) connectionHandler.registerHandler(CMSG_REQ_TRADE, gameHandler); connectionHandler.registerHandler(CMSG_EQUIP, gameHandler); - initialize(); - session->startListen(&connectionHandler, SERVER_PORT); - LOG_INFO("Listening on port " << SERVER_PORT << "...") + LOG_INFO("Listening on port " << SERVER_PORT << "...", 0) using namespace tmwserv; @@ -286,7 +340,7 @@ int main(int argc, char *argv[]) // Print world time at 10 second intervals to show we're alive if (worldTime % 100 == 0) { - LOG_INFO("World time: " << worldTime); + LOG_INFO("World time: " << worldTime, 0); } // - Handle all messages that are in the message queue @@ -303,7 +357,7 @@ int main(int argc, char *argv[]) SDL_Delay(100); } - LOG_INFO("Received: Quit signal, closing down...") + LOG_INFO("Received: Quit signal, closing down...", 0) session->stopListen(SERVER_PORT); deinitialize(); diff --git a/src/mapmanager.cpp b/src/mapmanager.cpp index c307ee33..6e8137d1 100644 --- a/src/mapmanager.cpp +++ b/src/mapmanager.cpp @@ -41,11 +41,11 @@ void MapManager::loadMap(const std::string& mapFile) Map *map = MapReader::readMap("maps/" + mapFile); if (map == NULL) { - LOG_ERROR("Error: Unable to load map file (" << mapFile << ")"); + LOG_ERROR("Error: Unable to load map file (" << mapFile << ")", 0); } else { - LOG_INFO("Loaded map " << maps.size() << " (" << mapFile << ")"); + LOG_INFO("Loaded map " << maps.size() << " (" << mapFile << ")", 0); maps[mapFile] = map; } } @@ -59,11 +59,11 @@ void MapManager::unloadMap(const std::string& mapFile) { delete i->second; maps.erase(i); - LOG_INFO("Unloaded map (" << mapFile << ")"); + LOG_INFO("Unloaded map (" << mapFile << ")", 0); } else { - LOG_WARN("Unable to unload map (" << mapFile << ")"); + LOG_WARN("Unable to unload map (" << mapFile << ")", 0); } } diff --git a/src/mapreader.cpp b/src/mapreader.cpp index ce41208d..1dd56eb7 100644 --- a/src/mapreader.cpp +++ b/src/mapreader.cpp @@ -120,7 +120,7 @@ Map *MapReader::readMap(const std::string &filename) if (buffer == NULL) { - LOG_ERROR("Error: Map file not found (" << filename.c_str() << ")"); + LOG_ERROR("Error: Map file not found (" << filename.c_str() << ")", 0); return NULL; } @@ -133,22 +133,22 @@ Map *MapReader::readMap(const std::string &filename) if (ret == Z_MEM_ERROR) { - LOG_ERROR("Error: Out of memory while decompressing map data!"); + LOG_ERROR("Error: Out of memory while decompressing map data!", 0); return NULL; } else if (ret == Z_VERSION_ERROR) { - LOG_ERROR("Error: Incompatible zlib version!"); + LOG_ERROR("Error: Incompatible zlib version!", 0); return NULL; } else if (ret == Z_DATA_ERROR) { - LOG_ERROR("Error: Incorrect zlib compressed data!"); + LOG_ERROR("Error: Incorrect zlib compressed data!", 0); return NULL; } else if (ret != Z_OK || inflated == NULL) { - LOG_ERROR("Error: Unknown error while decompressing map data!"); + LOG_ERROR("Error: Unknown error while decompressing map data!", 0); return NULL; } @@ -160,14 +160,14 @@ Map *MapReader::readMap(const std::string &filename) xmlNodePtr node = xmlDocGetRootElement(doc); if (!node || !xmlStrEqual(node->name, BAD_CAST "map")) { - LOG_ERROR("Error: Not a map file (" << filename << ")!"); + LOG_ERROR("Error: Not a map file (" << filename << ")!", 0); return NULL; } return readMap(node, filename); xmlFreeDoc(doc); } else { - LOG_ERROR("Error while parsing map file (" << filename << ")!"); + LOG_ERROR("Error while parsing map file (" << filename << ")!", 0); } return NULL; @@ -251,7 +251,7 @@ void MapReader::readLayer(xmlNodePtr node, Map *map, int layer) xmlFree(encoding); if (compression) { - LOG_WARN("Warning: no layer compression supported!"); + LOG_WARN("Warning: no layer compression supported!", 0); xmlFree(compression); return; } @@ -329,7 +329,7 @@ Tileset* MapReader::readTileset(xmlNodePtr node, const std::string &path, Map *map) { if (xmlHasProp(node, BAD_CAST "source")) { - LOG_WARN("Warning: External tilesets not supported yet."); + LOG_WARN("Warning: External tilesets not supported yet.", 0); return NULL; } diff --git a/src/messagehandler.cpp b/src/messagehandler.cpp index 9ec14971..a2517f39 100644 --- a/src/messagehandler.cpp +++ b/src/messagehandler.cpp @@ -26,5 +26,5 @@ #include "utils/logger.h" void MessageHandler::receiveMessage(NetComputer &computer, MessageIn &message) { - LOG_WARN("MessageHandler class created without receiveMessage override") + LOG_WARN("MessageHandler class created without receiveMessage override", 0) } diff --git a/src/resourcemanager.cpp b/src/resourcemanager.cpp index 64f45425..5f68d889 100644 --- a/src/resourcemanager.cpp +++ b/src/resourcemanager.cpp @@ -37,7 +37,7 @@ #include <dirent.h> #endif -#define TMW_DATADIR "" +#define TMWSERV_DATADIR "" ResourceManager *ResourceManager::instance = NULL; @@ -73,7 +73,7 @@ ResourceManager::searchAndAddZipFiles() { // Add the main data directory to our PhysicsFS search path PHYSFS_addToSearchPath("data", 1); - PHYSFS_addToSearchPath(TMW_DATADIR "data", 1); + PHYSFS_addToSearchPath(TMWSERV_DATADIR "data", 1); #ifdef _WIN32 // Define the path in which to search @@ -93,7 +93,7 @@ ResourceManager::searchAndAddZipFiles() std::string filePath = std::string("data/") + std::string(findFileInfo.name); - LOG_INFO("Adding to PhysicsFS: " << findFileInfo.name); + LOG_INFO("Adding to PhysicsFS: " << findFileInfo.name, 0); // Add the zip file to our PhysicsFS search path PHYSFS_addToSearchPath(filePath.c_str(), 1); @@ -129,7 +129,7 @@ ResourceManager::searchAndAddZipFiles() std::string filePath = std::string(programPath) + std::string("/") + std::string(direntry->d_name); - LOG_INFO("Adding to PhysicsFS: " << filePath); + LOG_INFO("Adding to PhysicsFS: " << filePath, 0); // Add the zip file to our PhysicsFS search path PHYSFS_addToSearchPath(filePath.c_str(), 1); @@ -145,7 +145,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!"); + LOG_WARN("Warning: " << fileName << " not found!", 0); return NULL; } @@ -154,7 +154,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!"); + LOG_WARN("Warning: " << fileName << " failed to load!", 0); return NULL; } @@ -180,7 +180,7 @@ ResourceManager::loadTextFile(const std::string &fileName) if (!fileContents) { - LOG_ERROR("Couldn't load text file: " << fileName); + LOG_ERROR("Couldn't load text file: " << fileName, 0); return lines; } diff --git a/src/skill.cpp b/src/skill.cpp index 12ead5c4..fab74163 100644 --- a/src/skill.cpp +++ b/src/skill.cpp @@ -59,9 +59,9 @@ bool Skill::addSkill(const std::string &ident, Skill *skill) { bool Skill::useSkill() { #ifdef SCRIPT_SUPPORT //run skill script - LOG_ERROR("Skill: Skills not implemented.") + LOG_ERROR("Skill: Skills not implemented.", 0) #else - LOG_ERROR("Skill: Could not use skill; scripting disabled.") + LOG_ERROR("Skill: Could not use skill; scripting disabled.", 0) #endif return true; } @@ -74,7 +74,7 @@ bool Skill::setScript(const std::string &scriptName) bool Skill::deleteSkill(const std::string &ident, bool delTree) { //prevent deletion of self if (ident == id) { - LOG_ERROR("Skill: Attempt to delete self.") + LOG_ERROR("Skill: Attempt to delete self.", 0) return false; } diff --git a/src/utils/logger.cpp b/src/utils/logger.cpp index 3f32ddb8..048fd5b1 100644 --- a/src/utils/logger.cpp +++ b/src/utils/logger.cpp @@ -44,7 +44,8 @@ namespace utils Logger::Logger(void) throw() : mHasTimestamp(true), - mTeeMode(false) + mTeeMode(false), + mVerbosity(0) { // NOOP } @@ -116,17 +117,20 @@ Logger::setTeeMode(bool flag) * Log a generic message. */ void -Logger::log(const std::string& msg) +Logger::log(const std::string& msg, unsigned short atVerbosity) { - if (mTeeMode) { - log(std::cout, msg); - - if (mLogFile.is_open()) { - log(mLogFile, msg); + if ( mVerbosity >= atVerbosity ) + { + if (mTeeMode) { + log(std::cout, msg); + + if (mLogFile.is_open()) { + log(mLogFile, msg); + } + } + else { + log((mLogFile.is_open() ? mLogFile : std::cout), msg); } - } - else { - log((mLogFile.is_open() ? mLogFile : std::cout), msg); } } @@ -135,17 +139,20 @@ Logger::log(const std::string& msg) * Log a debug message. */ void -Logger::debug(const std::string& msg) +Logger::debug(const std::string& msg, unsigned short atVerbosity) { - if (mTeeMode) { - log(std::cout, msg, "[DBG]"); - - if (mLogFile.is_open()) { - log(mLogFile, msg, "[DBG]"); + if ( mVerbosity >= atVerbosity ) + { + 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]"); } - } - else { - log((mLogFile.is_open() ? mLogFile : std::cout), msg, "[DBG]"); } } @@ -154,17 +161,20 @@ Logger::debug(const std::string& msg) * Log an info message. */ void -Logger::info(const std::string& msg) +Logger::info(const std::string& msg, unsigned short atVerbosity) { - if (mTeeMode) { - log(std::cout, msg, "[INF]"); - - if (mLogFile.is_open()) { - log(mLogFile, msg, "[INF]"); + if ( mVerbosity >= atVerbosity ) + { + 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]"); } - } - else { - log((mLogFile.is_open() ? mLogFile : std::cout), msg, "[INF]"); } } @@ -173,17 +183,20 @@ Logger::info(const std::string& msg) * Log a warn message. */ void -Logger::warn(const std::string& msg) +Logger::warn(const std::string& msg, unsigned short atVerbosity) { - if (mTeeMode) { - log(std::cerr, msg, "[WRN]"); - - if (mLogFile.is_open()) { - log(mLogFile, msg, "[WRN]"); + if ( mVerbosity >= atVerbosity ) + { + 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]"); } - } - else { - log((mLogFile.is_open() ? mLogFile : std::cerr), msg, "[WRN]"); } } @@ -192,17 +205,20 @@ Logger::warn(const std::string& msg) * Log an error message. */ void -Logger::error(const std::string& msg) +Logger::error(const std::string& msg, unsigned short atVerbosity) { - if (mTeeMode) { - log(std::cerr, msg, "[ERR]"); - - if (mLogFile.is_open()) { - log(mLogFile, msg, "[ERR]"); + if ( mVerbosity >= atVerbosity ) + { + 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]"); } - } - else { - log((mLogFile.is_open() ? mLogFile : std::cerr), msg, "[ERR]"); } } @@ -211,7 +227,7 @@ Logger::error(const std::string& msg) * Log a fatal error message. */ void -Logger::fatal(const std::string& msg) +Logger::fatal(const std::string& msg, unsigned short atVerbosity) { if (mTeeMode) { log(std::cerr, msg, "[FTL]"); @@ -223,7 +239,6 @@ Logger::fatal(const std::string& msg) else { log((mLogFile.is_open() ? mLogFile : std::cerr), msg, "[FTL]"); } - #ifdef WIN32 MessageBox(NULL, msg.c_str(), "Fatal error", MB_ICONERROR | MB_OK); #endif diff --git a/src/utils/logger.h b/src/utils/logger.h index 072f7c0f..f730600b 100644 --- a/src/utils/logger.h +++ b/src/utils/logger.h @@ -129,16 +129,38 @@ class Logger: public Singleton<Logger> setTeeMode(bool flag = true) throw(); + /** + * Set 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); + log(const std::string& msg, unsigned short atVerbosity = 0); /** @@ -146,10 +168,13 @@ class Logger: public Singleton<Logger> * * @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); + debug(const std::string& msg, unsigned short atVerbosity = 0); /** @@ -157,10 +182,13 @@ class Logger: public Singleton<Logger> * * @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); + info(const std::string& msg, unsigned short atVerbosity = 0); /** @@ -168,10 +196,13 @@ class Logger: public Singleton<Logger> * * @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); + warn(const std::string& msg, unsigned short atVerbosity = 0); /** @@ -179,10 +210,13 @@ class Logger: public Singleton<Logger> * * @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); + error(const std::string& msg, unsigned short atVerbosity = 0); /** @@ -190,10 +224,13 @@ class Logger: public Singleton<Logger> * * @param msg the message to log. * + * @param atVerbosity the minimum verbosity level + * to log this + * * @exception std::ios::failure. */ void - fatal(const std::string& msg); + fatal(const std::string& msg, unsigned short atVerbosity = 0); private: @@ -249,9 +286,10 @@ class Logger: public Singleton<Logger> private: - std::ofstream mLogFile; /**< the log file */ - bool mHasTimestamp; /**< the timestamp flag */ - bool mTeeMode; /**< the tee mode flag */ + std::ofstream mLogFile; /**< the log file */ + bool mHasTimestamp; /**< the timestamp flag */ + bool mTeeMode; /**< the tee mode flag */ + unsigned short mVerbosity; /**< keeps the verbosity level */ }; @@ -262,52 +300,46 @@ class Logger: public Singleton<Logger> // HELPER MACROS -#define LOG(msg) \ - { \ - std::ostringstream os; \ - os << msg; \ - ::tmwserv::utils::Logger::instance().log(os.str()); \ +#define LOG(msg, atVerbosity) \ + { \ + std::ostringstream os; \ + os << msg; \ + ::tmwserv::utils::Logger::instance().log(os.str(), atVerbosity); \ } - -#define LOG_DEBUG(msg) \ - { \ - std::ostringstream os; \ - os << msg; \ - ::tmwserv::utils::Logger::instance().debug(os.str()); \ +#define LOG_DEBUG(msg, atVerbosity) \ + { \ + std::ostringstream os; \ + os << msg; \ + ::tmwserv::utils::Logger::instance().debug(os.str(), atVerbosity); \ } - -#define LOG_INFO(msg) \ +#define LOG_INFO(msg, atVerbosity) \ { \ std::ostringstream os; \ os << msg; \ - ::tmwserv::utils::Logger::instance().info(os.str()); \ + ::tmwserv::utils::Logger::instance().info(os.str(), atVerbosity); \ } - -#define LOG_WARN(msg) \ +#define LOG_WARN(msg, atVerbosity) \ { \ std::ostringstream os; \ os << msg; \ - ::tmwserv::utils::Logger::instance().warn(os.str()); \ + ::tmwserv::utils::Logger::instance().warn(os.str(), atVerbosity); \ } - -#define LOG_ERROR(msg) \ +#define LOG_ERROR(msg, atVerbosity) \ { \ std::ostringstream os; \ os << msg; \ - ::tmwserv::utils::Logger::instance().error(os.str()); \ + ::tmwserv::utils::Logger::instance().error(os.str(), atVerbosity); \ } - -#define LOG_FATAL(msg) \ +#define LOG_FATAL(msg, atVerbosity) \ { \ std::ostringstream os; \ os << msg; \ - ::tmwserv::utils::Logger::instance().fatal(os.str()); \ + ::tmwserv::utils::Logger::instance().fatal(os.str(), atVerbosity); \ } - #endif // _TMWSERV_LOGGER_H_ |