c++ logger class example

Here is an example of a logger class in C++:

#include <iostream>
#include <fstream>
#include <string>

class Logger {
public:
    Logger(const std::string& filename) {
        file.open(filename);
    }

    ~Logger() {
        file.close();
    }

    void log(const std::string& message) {
        file << message << std::endl;
    }

private:
    std::ofstream file;
};

int main() {
    Logger logger("log.txt");
    logger.log("This is a log message.");

    return 0;
}

Explanation:

  1. The code includes the necessary header files: <iostream>, <fstream>, and <string>. These provide the necessary functionalities for input/output, file handling, and string manipulation.

  2. The Logger class is defined, which will be responsible for logging messages to a file. It has a public constructor that takes a std::string parameter filename. This constructor opens the file with the given filename using the open() function of the std::ofstream class.

  3. The class also has a destructor, ~Logger(), which is responsible for closing the file using the close() function of the std::ofstream class. This ensures that the file is properly closed when the Logger object goes out of scope.

  4. The log() function is a public member function of the Logger class, which takes a std::string parameter message. This function writes the message to the file using the << operator of the std::ofstream class, and appends a newline character (std::endl) to the message to separate log entries.

  5. The private section of the Logger class contains a single member variable, file, of type std::ofstream. This variable is used to store the file stream to which the log messages will be written.

  6. In the main() function, an instance of the Logger class is created with the filename "log.txt". This creates a Logger object named logger, which automatically opens the file "log.txt" in the constructor.

  7. The log() function of the logger object is then called, passing the message "This is a log message." This writes the message to the file "log.txt".

  8. Finally, the main() function returns 0 to indicate successful execution.