begin process at 2013 06 20 09:42:12
  Trouver un code source :
 
dans
 
Accueil > 

Code

 > 

Fichiers / Disque

 > CLASSE AVANCÉE DE LOG, THREAD SAFE ET DIVERSES SURCHARGES

CLASSE AVANCÉE DE LOG, THREAD SAFE ET DIVERSES SURCHARGES


 Information sur la source

Note :
9,5 / 10 - par 2 personnes
9,50 / 10

  • 1

  • 2

  • 3

  • 4

  • 5

  • 6

  • 7

  • 8

  • 9

  • 10
Catégorie :Fichiers / Disque Classé sous :Loggeur, classe log, fichier log, de log, log Niveau :Expert Date de création :15/08/2009 Date de mise à jour :15/08/2009 22:31:34 Vu / téléchargé :94 881 / 151

Auteur : sboli

Ecrire un message privé
Commentaire sur cette source (8)
Ajouter un commentaire et/ou une note

 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.


 Fichier Zip

Les Membres Club peuvent télécharger directement un fichier contenu dans le zip sans télécharger le zip en entier !

Télécharger le zip


 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

COMPTER LE NOMBRE DE PAGES D'UN FICHIER PDF par Renfield
Source avec Zip Source avec une capture GENERE BMP par lajouad
Source avec Zip Source avec une capture GETIONNAIRE D'UNE BIBLIOTHÉQUE EN C par benzarabel
FONCTION D'ÉDITION DE FICHIER BIT À BIT [C-MULTIPLATEFORME] par lynxtyle
Source avec Zip Source avec une capture UN GESTIONNAIRE DU FICHIER par benzarabel

 Sources en rapport avec celle ci

CALCULE LOG(X) par tagtog
Source avec Zip OUTPUTDEBUGSTRINGEX par kts_system
Source avec Zip Source avec une capture FENÊTRE DE DEBUG GTK+ POUR OPENGL par Arnaud16022
Source avec Zip Source avec une capture CALCULATRICE AVEC FICHIER DE LOG par michaelFollo
Source avec Zip Source avec une capture WINAPIOVERRIDE32 par yex

Commentaires et avis

Commentaire de CptPingu le 15/08/2009 19:35:56 administrateur CS 9/10

Le projet est codé proprement, félicitations:
- Pas de using namespace std; \o/
- Pas de system("pause"), mais un équivalent portable.
- De la doc
- Bonne séparation
- .hpp et pas .h
- Une convention pour nommer les attributs de classe m_truc (même si perso je préfère _truc :p)

Néanmoins quelques toutes petites remarques:
- Le code du template ne doit pas être dans un .cpp, mais devrait être dans le .hpp, ou encore mieux dans un .hxx (fichier qui devrait contenir les méthodes "templatés" et le code "inliné"). Un code template n'existe pas, et est généré à la compilation, il doit donc être dans un header.
- using namespace bs; ne sert à rien. Mieux vaut vaut préférer bs::Logger !

Projet intéressant, qui pourrait s'avérer utile.

Commentaire de sboli le 15/08/2009 22:05:11

citation:
{Le code du template ne doit pas être dans un .cpp, mais devrait être dans le .hpp, ou encore mieux dans un .hxx (fichier qui devrait contenir les méthodes "templatés" et le code "inliné"). Un code template n'existe pas, et est généré à la compilation, il doit donc être dans un header.}
Effectivement, où avais-je la tête.
citation:
{Projet intéressant, qui pourrait s'avérer utile.}
Je l'utilise dans un projet avec quelques modifications (singleton, surcharges de l'op<< pour certaines classes)et quel bonheur.

Commentaire de shenron666 le 16/08/2009 12:01:47 10/10

ouah sérieux ça fait un bail que je n'avais pas vu un code aussi propre utile et bien écrit
mêmes remarques que CptPingu, du standard, du portable, moi je préfère m_ le m étant pour "member" ;)

j'avais créé le même genre de classe mais pas threadsafe il y a un temps
une méthode que j'avais implémentée me permettait d'envoyer entre autres les fin de ligne : std::endl
le prototype étant le suivant :
CLogger& operator<<(std::ostream& (__cdecl *_Pfn)(std::ostream&));
il suffit ensuite d'appeler Pfn avec ton ofstream en paramètre

concernant le fichier de log en lui même, je préfère à chaque appel du log :
- ouvrir le fichier
- logguer l'info
- fermer le fichier

parceque si ton programme plante alors ton fichier log sera tronqué et tu n'aura pas tes infos de log à jour
sinon, un flush après chaque envoi au fichier suffirait peut-etre, je n'ai pas testé

Commentaire de sboli le 16/08/2009 22:03:10

Avec l'op<< je retourne directement l'ostream donc c'est possible d'utiliser std::endl et tout les autres manipulateurs de flux, voire l'exemple du main.
Pour ce qui est de plantage du programme, c'est à l'utilisateur de la classe de se préoccuper de ça, vu que la classe s'utilise comme un flux standard, (donc std::endl, std::flush).
D'ailleurs je n'aurais pas à l'idée de rajouter des lignes de log sans std::endl (ou l'option useEndLine(true))sinon le fichier serait un vrai foutoir.
Sinon pour ta première remarque, si c'est à propos du "a_", je l'utilise pour identifier les variables qui ne feront rien d'autre qu'être "assignés" à des membres.

Commentaire de shenron666 le 18/08/2009 00:35:18

une question dans ce cas, est-ce que ceci fonctionne ?
log << std::endl;

Commentaire de CptPingu le 18/08/2009 09:37:30 administrateur CS

Non, ça ne le gère pas, mais si tu veux ajouter cette feature sans toucher à son code, ceci devrait le faire:

Logger&
operator<<(Logger& out,
       std::ostream& (*fn)(std::ostream&))
{
  std::ostringstream oss;
  fn(oss);
  out << oss.str();
  return out;
}

Commentaire de shenron666 le 18/08/2009 19:19:24

je pensai bien que ce n'était pas géré
par contre, ton code peut être plus simple :
Logger& operator<<(Logger& out, std::ostream& (*fn)(std::ostream&))
{
  fn(out.outputStream());
  return out;
}

enfin c'était juste pour te titiller un peu sur des cas particuliers ;)

Commentaire de Kotomine le 02/09/2009 09:34:45

Question de profane de la bibliothèque Boost (j'y connais absolument rien):
A quoi sert ton lien d'héritage ? Pour des mutex de boost ?

D'autres questions esthétiques:
* je me souviens quand je codais mes serveurs, j'avais fait une implémentation d'un logger à l'arrache (c'était une encapsulation d'un bête printf(stderr)), mais j'avais un problème,dans mon fichier, les données était classée par thread (puis date) et non par date ; t'as ce même probleme ? (J'étais sous linux 2.6 /pthread).. une histoire de flush je pense

* Pour les includes de templates, j'utilisais la nomenclature ".inl" (pour inline)

En tout cas, excellente qualité de code.
Quel éditeur ?

 Ajouter un commentaire


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&#233;gie temps r&#233;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&#233;er un fichier log puis de le remplir mais quand&nbsp;l'utilisateur &nbsp;mets les symboles &gt;&lt; \ besoin d'aide : TP école d'ingénieur [ par arbomont ] Voici le TP que je dois rendre, et je coince sur un petit d&#233;tail, pourriez vous m'aider ?Il s'agit d'un programme de communication (un chat)&nbsp CLASS [ par T_Mehdi ] salut a tous bon , j'ai la 2eme question au faite reli&#233; a cette parti de source la : class ILogger{public :&nbsp;&nbsp; <SPAN class=cpp_ Log (journal) pour un firewall [ par Bessouma ] Je cherche de l'aide pour developper un firewall en VC++


Nos sponsors


Sondage...

CalendriCode

Juin 2013
LMMJVSD
     12
3456789
10111213141516
17181920212223
24252627282930

Consulter la suite du CalendriCode

Photothèque

A découvrir



 
Développement réalisé par Nicolas SOREL (Nix) avec l'aide de : Cyril DURAND et Emmanuel (EBArtSoft), Merci à Vincent pour ses précieux conseils.
CodeS-SourceS.com© Toute reproduction même partielle est interdite sauf accord écrit du Webmaster
CodeS-SourceS.com© est une marque déposée tous droits réservés

Google Coop CodeS-SourceS Google Coop CodeS-SourceS
Temps d'éxécution de la page : 4,696 sec (3)

Nous contacter | Annoncer sur CodeS-SourceS | Mentions légales