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:
The code includes the necessary header files:
<iostream>
,<fstream>
, and<string>
. These provide the necessary functionalities for input/output, file handling, and string manipulation.The
Logger
class is defined, which will be responsible for logging messages to a file. It has a public constructor that takes astd::string
parameterfilename
. This constructor opens the file with the given filename using theopen()
function of thestd::ofstream
class.The class also has a destructor,
~Logger()
, which is responsible for closing the file using theclose()
function of thestd::ofstream
class. This ensures that the file is properly closed when theLogger
object goes out of scope.The
log()
function is a public member function of theLogger
class, which takes astd::string
parametermessage
. This function writes themessage
to the file using the<<
operator of thestd::ofstream
class, and appends a newline character (std::endl
) to the message to separate log entries.The
private
section of theLogger
class contains a single member variable,file
, of typestd::ofstream
. This variable is used to store the file stream to which the log messages will be written.In the
main()
function, an instance of theLogger
class is created with the filename "log.txt". This creates aLogger
object namedlogger
, which automatically opens the file "log.txt" in the constructor.The
log()
function of thelogger
object is then called, passing the message "This is a log message." This writes the message to the file "log.txt".Finally, the
main()
function returns 0 to indicate successful execution.