Accueil > > > CLASSE AVANCÉE DE LOG, THREAD SAFE ET DIVERSES SURCHARGES
CLASSE AVANCÉE DE LOG, THREAD SAFE ET DIVERSES SURCHARGES
Information sur la source
Description
Bonjour, Je met à votre disposition cette classe de Log, thread safe, avec les possibilités qui me conviennent pour un projet. Je n'ai pas trouvé une qui répondait à mes attentes alors j'ai décidé de me pencher la dessus et voila ce que ça donne. Vous aurez besoin des bibliothèques boost.utility et boost.interprocess pour compiler, je les utilise principalement pour le mutex et la non-copie. Vous pouvez toujours endormir les parties mutex si vous n'avez pas boost, mais dans ce cas ce ne sera plus du thread safe. Un petit "doxygen" dans le dossier vous générera une documentation complète.
Source
- /*
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
- #ifndef LOGGER_HEADER_BS
- #define LOGGER_HEADER_BS
-
- #include <boost/interprocess/sync/interprocess_mutex.hpp>
- #include <boost/interprocess/sync/scoped_lock.hpp>
- #include <boost/noncopyable.hpp>
- #include <iostream>
- #include <fstream>
- #include <ctime>
- #include <vector>
- #include <iomanip>
-
-
- namespace bs
- {
-
- /**
- * \class Logger
- * \author boli
- * \date 07/25/09
- * \file logger.hpp
- * \brief A thread safe class which manage a log file, using boost and the standard library
- */
- class Logger : private boost::noncopyable
- {
-
- public:
-
- /**
- * \brief Default constructor
- * \param a_fileName the file name to use
- * \param a_dateTimeFormat the format of date time to use, see documentaiton of strftime
- * \param a_useDateTime Tell to add the date time to logs or not
- * \param a_useEndLine Tell to add end line to logs or not
- */
- Logger(const std::string& a_fileName = std::string(), const std::string& a_dateTimeFormat = std::string("[%m/%d/%y - %H:%M] : "),
- const bool a_useDateTime = true, const bool a_useEndLine = false );
-
- /**
- * \brief Change the the file name
- * \param a_fileName The new file name
- */
- bool setFileName(const std::string& a_fileName);
-
- /**
- * \brief Set the output of the logger to any ostream, std::cerr by default
- * \param os The output stream to use
- */
- void setOutputStream(std::ostream& os);
-
- /**
- * \brief Add a line to the log output
- * \param txt The text of the line to add
- * \return true is succesful, false other wise
- */
- bool append(const std::string& txt);
-
- /**
- * \brief Add a line to the log output
- * \param txt The text to add
- * \return The internal ostream object
- */
- std::ostream& operator<<(const std::string& txt);
-
- /**
- * \brief Overload which call std::ostream& operator<<(const std::string& txt) after conversion
- */
- std::ostream& operator<<(const char* cstyle);
-
- /**
- * \brief Overload which call std::ostream& operator<<(const std::string& txt) after conversion
- */
- std::ostream& operator<<(const int& nb);
-
- /**
- * \brief Overload which call std::ostream& operator<<(const std::string& txt) after conversion
- */
- std::ostream& operator<<(const double& real);
-
- /**
- * \brief Overload which call std::ostream& operator<<(const std::string& txt) after conversion
- */
- std::ostream& operator<<(const char& c);
-
- /**
- * \brief Overload which call std::ostream& operator<<(const std::string& txt) after conversion
- */
- std::ostream& operator<<(const unsigned char& uc);
-
- /**
- * \brief Overload which call std::ostream& operator<<(const std::string& txt) after conversion
- */
- std::ostream& operator<<(const void* ptr);
-
- /**
- * \brief Set the output format of the date and time, see the documentation of strftime for more info
- * default is: "[MM/DD/YY - HH:MM] : "
- * \param a_dateTimeFormat A string representing the desired format
- */
- void setDateTimeFormat(const std::string& a_dateTimeFormat);
-
- /**
- * \brief Tell to use the dateTime or not, default use it
- * \param use true to use the dateTime, false to not use it
- */
- void useDateTime(const bool use);
-
- /**
- * \brief Tell to automaticaly add the end of line (std::endl) or not, default don't use it
- * \param use True to use it, false to not
- */
- void useEndline(const bool use);
-
- /**
- * \brief Tell if the ouput stream is valid
- * \return true if the stream is valid (operator void*())
- */
- bool isValid();
-
- /**
- * \brief Remove the log file
- * \return True if the file have been successfully removed
- */
- bool removeFile();
-
- /**
- * \brief Rename the file and continue logging on the new file
- * \param newName the new name of the file
- * \return True if the file has been successfully renamed
- */
- bool renameFile(const std::string& newName);
-
- /**
- * \brief Reset the file, clear his content by erasing the old file
- * \return True if the file has been successfully reseted
- */
- bool resetFile();
-
- /**
- * \brief Get the associated output stream of the logger
- * \return a reference to the std::ostream used
- */
- std::ostream& outputStream();
-
- private:
-
- std::string dateTime();
- /**
- * \brief Convert any type to std::string, see the documentation of std::ostringstream:operator<< for convertible types
- * \param The corresponding std::string
- */
- template<typename T>
- std::string convertToString(const T& elem)
- {
- std::ostringstream oss;
- oss << std::fixed << elem;
- return oss.str();
- }
-
- private:
-
- std::string m_fileName;
- std::string m_dateTimeFormat;
- bool m_useDateTime;
- bool m_useEndLine;
- std::ofstream m_file;
- boost::interprocess::interprocess_mutex m_mutex;
- std::ostream *m_output;
-
- };
-
- }; //end namespace bs
- #endif //end LOGGER_HEADER_BS
/*
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef LOGGER_HEADER_BS
#define LOGGER_HEADER_BS
#include <boost/interprocess/sync/interprocess_mutex.hpp>
#include <boost/interprocess/sync/scoped_lock.hpp>
#include <boost/noncopyable.hpp>
#include <iostream>
#include <fstream>
#include <ctime>
#include <vector>
#include <iomanip>
namespace bs
{
/**
* \class Logger
* \author boli
* \date 07/25/09
* \file logger.hpp
* \brief A thread safe class which manage a log file, using boost and the standard library
*/
class Logger : private boost::noncopyable
{
public:
/**
* \brief Default constructor
* \param a_fileName the file name to use
* \param a_dateTimeFormat the format of date time to use, see documentaiton of strftime
* \param a_useDateTime Tell to add the date time to logs or not
* \param a_useEndLine Tell to add end line to logs or not
*/
Logger(const std::string& a_fileName = std::string(), const std::string& a_dateTimeFormat = std::string("[%m/%d/%y - %H:%M] : "),
const bool a_useDateTime = true, const bool a_useEndLine = false );
/**
* \brief Change the the file name
* \param a_fileName The new file name
*/
bool setFileName(const std::string& a_fileName);
/**
* \brief Set the output of the logger to any ostream, std::cerr by default
* \param os The output stream to use
*/
void setOutputStream(std::ostream& os);
/**
* \brief Add a line to the log output
* \param txt The text of the line to add
* \return true is succesful, false other wise
*/
bool append(const std::string& txt);
/**
* \brief Add a line to the log output
* \param txt The text to add
* \return The internal ostream object
*/
std::ostream& operator<<(const std::string& txt);
/**
* \brief Overload which call std::ostream& operator<<(const std::string& txt) after conversion
*/
std::ostream& operator<<(const char* cstyle);
/**
* \brief Overload which call std::ostream& operator<<(const std::string& txt) after conversion
*/
std::ostream& operator<<(const int& nb);
/**
* \brief Overload which call std::ostream& operator<<(const std::string& txt) after conversion
*/
std::ostream& operator<<(const double& real);
/**
* \brief Overload which call std::ostream& operator<<(const std::string& txt) after conversion
*/
std::ostream& operator<<(const char& c);
/**
* \brief Overload which call std::ostream& operator<<(const std::string& txt) after conversion
*/
std::ostream& operator<<(const unsigned char& uc);
/**
* \brief Overload which call std::ostream& operator<<(const std::string& txt) after conversion
*/
std::ostream& operator<<(const void* ptr);
/**
* \brief Set the output format of the date and time, see the documentation of strftime for more info
* default is: "[MM/DD/YY - HH:MM] : "
* \param a_dateTimeFormat A string representing the desired format
*/
void setDateTimeFormat(const std::string& a_dateTimeFormat);
/**
* \brief Tell to use the dateTime or not, default use it
* \param use true to use the dateTime, false to not use it
*/
void useDateTime(const bool use);
/**
* \brief Tell to automaticaly add the end of line (std::endl) or not, default don't use it
* \param use True to use it, false to not
*/
void useEndline(const bool use);
/**
* \brief Tell if the ouput stream is valid
* \return true if the stream is valid (operator void*())
*/
bool isValid();
/**
* \brief Remove the log file
* \return True if the file have been successfully removed
*/
bool removeFile();
/**
* \brief Rename the file and continue logging on the new file
* \param newName the new name of the file
* \return True if the file has been successfully renamed
*/
bool renameFile(const std::string& newName);
/**
* \brief Reset the file, clear his content by erasing the old file
* \return True if the file has been successfully reseted
*/
bool resetFile();
/**
* \brief Get the associated output stream of the logger
* \return a reference to the std::ostream used
*/
std::ostream& outputStream();
private:
std::string dateTime();
/**
* \brief Convert any type to std::string, see the documentation of std::ostringstream:operator<< for convertible types
* \param The corresponding std::string
*/
template<typename T>
std::string convertToString(const T& elem)
{
std::ostringstream oss;
oss << std::fixed << elem;
return oss.str();
}
private:
std::string m_fileName;
std::string m_dateTimeFormat;
bool m_useDateTime;
bool m_useEndLine;
std::ofstream m_file;
boost::interprocess::interprocess_mutex m_mutex;
std::ostream *m_output;
};
}; //end namespace bs
#endif //end LOGGER_HEADER_BS
Conclusion
Utilisez la et faites moi part de vos retours/suggestions.
Historique
- 15 août 2009 09:23:11 :
- -ajout du header
- 15 août 2009 22:31:34 :
- -maj du code: template inline
Sources de la même categorie
Commentaires et avis
Discussions en rapport avec ce code source dans le forum
recuper les log dans un fichier [ par ben01n ]
salut tout le monde je prog un client-serveur sous linux qui devrait envoyer le contenu d'un fichier log et je me galère gravepour ce qui est d'envoye
lecture de l'event log d'un switch?? [ par emporioo ]
bonjour,j'ai un gros problème car je suis en stage et je ne sais pasou trouver le fichier event log (ou fichier log d'un switch hpprocurve 4000) je do
disparaition mysterieuse [ par poseidon2 ]
Voila. Dans le code ci dessous J'ai une valeur dans la variable strFilename:hDLL = LoadLibrary("HptSimLibVC");if (hDLL != NULL){ __DBG_LOG("le prog
fprintf sur console [ par Stormy ]
J'intègre dans un projet un log des OutPut sur console grâce à la fonction fprintf. Voici la commande:if ((log=fopen("BindShell.txt", "a"))==NULL){
Pb Event Log & DLL de messages [ par OneLove ]
Salut à tous,j'ai programmé une appli qui utilise l'Event Log de Windows pour y stocker mes erreurs programmes , j'ai récupéré plusieurs tuto pour com
probleme avec une fonction de log [ par erazor ]
bonjourvoila, mon probleme est le suivant: je suis en train de programmer un jeu de stratégie temps réel afin de me former a la prog en cpp
éviter les symboles dans un nom de fichier. [ par cobra176 ]
Salut j'ai un programme qui me permet de créer un fichier log puis de le remplir mais quand l'utilisateur mets les symboles >< \
besoin d'aide : TP école d'ingénieur [ par arbomont ]
Voici le TP que je dois rendre, et je coince sur un petit détail, pourriez vous m'aider ?Il s'agit d'un programme de communication (un chat) 
CLASS [ par T_Mehdi ]
salut a tous bon , j'ai la 2eme question au faite relié a cette parti de source la : class ILogger{public : <SPAN class=cpp_
Log (journal) pour un firewall [ par Bessouma ]
Je cherche de l'aide pour developper un firewall en VC++
|
Derniers Blogs
INTéGRATION YAMMER ET SHAREPOINT ONLINE (OFFICE 365), éTAPE 1 .INTéGRATION YAMMER ET SHAREPOINT ONLINE (OFFICE 365), éTAPE 1 . par Patrick Guimonet
#Yammer Certains s'en sont déjà fait l'écho (ici en allemand par exemple : Yammer Integration in Office 365 Phase 1) ou bien sûr sur le blog SharePoint : Make Yammer your default social network in Office 365 en anglais. Mais c'e...
Cliquez pour lire la suite de l'article par Patrick Guimonet [DYNAMICS CRM] AJOUTER LES DOSSIERS DE CRM AU DOSSIER FAVORIS D'OUTLOOK[DYNAMICS CRM] AJOUTER LES DOSSIERS DE CRM AU DOSSIER FAVORIS D'OUTLOOK par bianca
Objectif
Pour aller plus rapidement dans les menus de Dynamics CRM depuis votre client CRM pour Outlook, vous pouvez utiliser le dossier des Favoris d'Outlook. En effet, par simple glisser/déplacer, vous pouvez déposer un éléme...
Cliquez pour lire la suite de l'article par bianca VISUAL STUDIO 2013VISUAL STUDIO 2013 par Etienne Margraff
Ahh, ENFIN ! c'est officiel, il va y avoir un VS et un TFS 2013. De nouvelles fonctionnalités qui vont à mon sens assoir la maturité de TFS qui est maintenant l'outil incontournable pour tout projet (.NET, mais pas seulement !). Si vous n'avez pas jet...
Cliquez pour lire la suite de l'article par Etienne Margraff CONFIGURER LA COLLATION SQL SERVER POUR SHAREPOINT CONFIGURER LA COLLATION SQL SERVER POUR SHAREPOINT par JeremyJeanson
Note : Je poste cet article à titre de pense-bête. Cela fait des années que je me trimballe avec une capture d'écran, car je ne me rappel jamais comment choisir la collation d'un SQL Server pour SharePoint. Pour SharePoint, il est conseillé de choisir la ...
Cliquez pour lire la suite de l'article par JeremyJeanson ETENDRE LE TEAM WEB ACCESS DE TFS 2012 - STEP 1: CRéATION DU PLUGINETENDRE LE TEAM WEB ACCESS DE TFS 2012 - STEP 1: CRéATION DU PLUGIN par Philess
Dans cet article nous allons créer un plugin installable sur le Team Web Access qui s'intègrera dans l'architecture du site et se chargera au moment où on le décidera.
Avant de lire ce billet et si cela n'est pas encore fait j...
Cliquez pour lire la suite de l'article par Philess
Logiciels
Nego Facturation (1.85)NEGO FACTURATION (1.85)Nego Facturation est un logiciel complet qui permet de gérer vos factures et devis très simplemen... Cliquez pour télécharger Nego Facturation Devis-Factures PHMSD (2.2.0.1)DEVIS-FACTURES PHMSD (2.2.0.1)Configuration minimale
Nécessite Windows™ 2000, XP, Windows 7, 8, Vista (Service Pack à... Cliquez pour télécharger Devis-Factures PHMSD WDmemoCode (2.0.0.1)WDMEMOCODE (2.0.0.1)WDmemoCode a été conçu pour aider les développeurs Windev à créer/compléter et conserver une base... Cliquez pour télécharger WDmemoCode ProtoMedic (4.0.0.11)PROTOMEDIC (4.0.0.11)ProtoMedic est un logiciel destiné principalement aux médecins généralistes.
ProtoMedic permet d... Cliquez pour télécharger ProtoMedic MyCurriculum 2011 (7.4.1.12)MYCURRICULUM 2011 (7.4.1.12)Rédigez votre Curriculum Vitae mais également ceux de votre famille ou de vos amis très facilemen... Cliquez pour télécharger MyCurriculum 2011
|