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
UNE JOLIE-HORLOGE ET PAS QU'UN PEU !UNE JOLIE-HORLOGE ET PAS QU'UN PEU ! par neodante
Pour les possesseurs d'iPhone, ça y est Bijin Tokei - qui se traduit littéralement en Français par " Jolie Horloge " - est arrivé et GRATUITEMENT s'il vous plaît ! Après la version Tokyo, Hokkaido, night club, racing, Gal, "pour les mademoiselles'", . voi...
Cliquez pour lire la suite de l'article par neodante TECHDAYS PARIS 2010 : CONNECTEZ VOS DONNéES à SHAREPOINT 2010 AVEC LES BUSINESS CONNECTIVITY SERVICESTECHDAYS PARIS 2010 : CONNECTEZ VOS DONNéES à SHAREPOINT 2010 AVEC LES BUSINESS CONNECTIVITY SERVICES par ROMELARD Fabrice
Animé par: Gaetan Bouveret et Julien Chomarat Business Connectivity Services (BCS) est dans SharePoint 2010 la version 2 de Business Data Catalog (BDC dans SharePoint 2007). Il s'agit de la solution permettant de visualiser des données provenan...
Cliquez pour lire la suite de l'article par ROMELARD Fabrice [DIVERS] SUIVRE VOS SéRIES PRéFéRéS SUR LA TOILE[DIVERS] SUIVRE VOS SéRIES PRéFéRéS SUR LA TOILE par orion
Comme de nombreux geek, je suis un grand amateur de série TV et je rate régulièrement des épisodes de mes séries préférés. Une solution s'offre à vous avec ce merveilleux site : Tv Gorge - www.tvgorge.com Moteur de recherche à l'appui, vous pouvez ...
Cliquez pour lire la suite de l'article par orion TECHDAYS PARIS 2010 : LA BI DANS SHAREPOINT 2010TECHDAYS PARIS 2010 : LA BI DANS SHAREPOINT 2010 par ROMELARD Fabrice
Animé par: Vincent Bellet et Baptiste Giraudier La BI dans SharePoint 2010, Les nouveaux services d'application dans SP2010 et SQL Server Reporting services 2008 R2. La BI dans SharePoint est généralisée pour tous afin de permettre à tous les coll...
Cliquez pour lire la suite de l'article par ROMELARD Fabrice
Forum
RE : WIN APIRE : WIN API par racpp
Cliquez pour lire la suite par racpp WIN APIWIN API par omarino_007
Cliquez pour lire la suite par omarino_007
Logiciels
DB-MAIN (9.1.0)DB-MAIN (9.1.0)DB-MAIN is a data-modeling and data-architecture tool. It is designed to help developers and anal... Cliquez pour télécharger DB-MAIN Xilisoft DPG Convertisseur (5.1.37.0120)XILISOFT DPG CONVERTISSEUR (5.1.37.0120)Xilisoft DPG Convertisseur offre aux fans de Nintendo DS une bonne solution leur permettant de dé... Cliquez pour télécharger Xilisoft DPG Convertisseur GraphicsGale (2.01.01)GRAPHICSGALE (2.01.01)GraphicsGale est un logiciel de PixelArt avec de nombreuse fonctionnalités permettant de réalisé ... Cliquez pour télécharger GraphicsGale Architecte 3D (Platinum 2010)ARCHITECTE 3D (PLATINUM 2010)Architecte 3D Platinium vous permet de concevoir facilement les plans votre future maison, de l'é... Cliquez pour télécharger Architecte 3D TeamViewer 5 (TeamViewer 5)TEAMVIEWER 5 (TEAMVIEWER 5)Dépanner un ami,expliquer une manipulation devient un jeu d'enfant.
Prise en main d'un autre ord... Cliquez pour télécharger TeamViewer 5
|