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
CSS CONTENT STATE SELECTORS (PERSONNAL DRAFT)CSS CONTENT STATE SELECTORS (PERSONNAL DRAFT) par FREMYCOMPANY
Bonjour à tous, Je viens de publier une proposition comprenant 5 pseudo-classes pour le CSS Working Group ayant trait à l'état de chargement d'un élément (ex: IMG,VIDEO,AUDIO,OBJECT pour l'HTML.). Si le c½ur vous en dit, vous pouvez retrouver cette p...
Cliquez pour lire la suite de l'article par FREMYCOMPANY MBA : POURQUOI FAIRE ET COMMENT LE CHOISIR ?MBA : POURQUOI FAIRE ET COMMENT LE CHOISIR ? par ROMELARD Fabrice
Formation initiale Durant la formation, le découpage classique est le suivant (je donnerai les équivalences Suisse lorsque je les connaîtrais) : Ecole primaire jusqu'au Collège : Formation générale permettant d'obtenir les méthodes...
Cliquez pour lire la suite de l'article par ROMELARD Fabrice Y'A DES ERREURS QUI PEUVENT RENDRE LE DéVELOPPEUR VIOLENTY'A DES ERREURS QUI PEUVENT RENDRE LE DéVELOPPEUR VIOLENT par Aleks
Quand on a ce genre d'erreur sans log :
Et bas on a juste envie de choper le gas de Microsoft qu'a développé ça et lui foutre des baffes de Coboye ! ...
Cliquez pour lire la suite de l'article par Aleks [HYPER-V 3] PRéSENTATION DES COMMANDLETS POWERSHELL[HYPER-V 3] PRéSENTATION DES COMMANDLETS POWERSHELL par Pierrick CATRO-BROUILLET
Avec la sortie prochaine de la Beta Consumer Preview de Windows 8, j'avais envie de revenir sur une des fonctionnalités que j'attends le plus et que, en bon geek que je suis, j'utilise déjà : Hyper-V 3 ainsi son module PowerShell.
Il y a déjà pléthor...
Cliquez pour lire la suite de l'article par Pierrick CATRO-BROUILLET IIS7 - COMPRESSION GZIPIIS7 - COMPRESSION GZIP par cyril
La compression GZIP permet d'améliorer les performances de navigation en compressant ce qu'envoie le serveur à un client. Pour comprendre comment cela fonctionne, regardons ce qu'il se passe au niveau HTTP lorsqu'un client tente d'accéder à une ress...
Cliquez pour lire la suite de l'article par cyril
Forum
ARBRE BINAIREARBRE BINAIRE par pacotheking
Cliquez pour lire la suite par pacotheking
Logiciels
Easy-Planning (1.0.0.1)EASY-PLANNING (1.0.0.1)Basé sur les mêmes principes que MyPlanning, Easy-Planning permet de créer des plannings sous la ... Cliquez pour télécharger Easy-Planning Academy System (17.1.3.0)ACADEMY SYSTEM (17.1.3.0)Logiciel de gestion des établissements.
- élèves/étudiants (inscription, dossier, absence...)
-... Cliquez pour télécharger Academy System COLLECTOR PLUS (3.00B)COLLECTOR PLUS (3.00B)COLLECTOR PLUS version 3.00B est un logiciel utilisant une base de données alimentée par :
- L... Cliquez pour télécharger COLLECTOR PLUS PONAMEDIA PREMIUM - HELLLOOO FLASH DEMO (V7.4)PONAMEDIA PREMIUM - HELLLOOO FLASH DEMO (V7.4)PONAMEDIA TV DEVIENS HELLLOOO FLASH
LA TV SUR VOTRE ORDINATEUR.
Toute une plateforme Multi... Cliquez pour télécharger PONAMEDIA PREMIUM - HELLLOOO FLASH DEMO LettresFaciles 2011 (8.0.0.1)LETTRESFACILES 2011 (8.0.0.1)LettresFaciles est un logiciel facilitant la création et la rédaction de lettres types.
Son inte... Cliquez pour télécharger LettresFaciles 2011
|