[C++]Simple log class

Results 1 to 2 of 2
  1. #1
    Account Upgraded | Title Enabled! Mindblaster7 is offline
    MemberRank
    Oct 2008 Join Date
    DenmarkLocation
    773Posts

    [C++]Simple log class

    In my try to teach myself C++, I thought it would be helpful for me to have a functioning logging class for future "projects". This was written on my Windows box, in VC++ 2010.

    I wanted to share this to others for use and to get tips for optimization and such.

    I wrote the class in a file called "log.h":
    PHP Code:
    #include <iostream>
    #include <fstream>
    using namespace std;
    class 
    Log_Module {
    public:
            
    void init(string filename) {
            if (!
    out.is_open()) {
                
    out.open(filename);
                
    file_name filename;
            }
            else
                
    cout << "There were already an open log file." << endl;
        }
        
    template <typename T>
        
    void log(T log_this){
            if (
    out.is_open() && out.good())
                
    out << log_this << endl;
            else {
                
    int var = 1;
                while(!
    out.is_open()) {
                    if (!
    file_name.length() > 0)
                        break;
                    if (var <= 
    10)
                        
    out.open(file_name);
                    else
                        break;

                    ++var;
                }
                if (!
    out.is_open())
                    
    cout << "The log file could not be opened." << endl;
                else
                    
    loglog_this );
            }
        }
        
    void log_close(){
            
    out.close();
        }
    private:
        
    ofstream out;
        
    string file_name;
    }; 
    And heres a little example:
    PHP Code:
    #include "log.h"

    int main() {
        
    Log_Module l;
        
    l.init("C:\\Users\\Andreas\\Desktop\\log_out.txt");
        
    l.log("Log a string.");
        
    l.log(0x33FEE);
        
    l.log(new signed int);
        
    l.log(new unsigned int);
        
    l.log((bool) true);
        
    l.log((double) 20.22);
        
    l.log_close();

    Output:
    Code:
    Log a string.
    212974
    002D5250
    002D63F0
    1
    20.22


  2. #2
    Just Me iceman4154 is offline
    MemberRank
    Oct 2007 Join Date
    Columbus, OhioLocation
    217Posts

    Re: [C++]Simple log class

    Well I know it will still work regardless but shouldn't your class have a constructor whether it takes arguments or not? Also, another note I find it a lot easy to keep track of classes when I use a header or .h file for the definition of the class and a .cpp file for the actual declaration or main code to the class. Just a thought, feel free to discuss your differences in thought or ask any questions.



Advertisement