Timestamped Log Struct

Timestamped Log Struct

Try using search engines to figure out how to get the current timestamp as a string. I've placed a working function for this in the hints.

Create a struct named Logger that allows for logging string entries to a file. The log file should be created (or opened if it exists) when an instance of the Logger struct is initialized. The struct should include a log function that takes a string message, and logs it with a timestamp (in YYYY-MM-DD HH:MM:SS format) to the log file. Each log entry should be on a new line.

Hint

Preview of how to get timestamp:

    // Function to get the current timestamp
    std::string getCurrentTimestamp() {
        auto now = std::chrono::system_clock::now();
        std::time_t currentTime = std::chrono::system_clock::to_time_t(now);
        std::tm* localTime = std::localtime(&currentTime);

        char buffer[20];
        std::strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", localTime);
        return std::string(buffer);
    }

Logger structure

struct Logger {
    std::ofstream logFile;

    Logger(const std::string& filename);
    std::string getCurrentTimestamp();
    void log(const std::string& message);
    ~Logger(); // destructor to close file can be a good idea
};

Answer

#include <iostream>
#include <fstream>
#include <chrono>
#include <ctime>

struct Logger {
    std::ofstream logFile;

    // Constructor to open/create the log file
    Logger(const std::string& filename) {
        logFile.open(filename, std::ios::app); // Open in append mode
        if (!logFile) {
            std::cerr << "Failed to open log file." << std::endl;
        }
    }

    // Function to get the current timestamp
    std::string getCurrentTimestamp() {
        auto now = std::chrono::system_clock::now();
        std::time_t currentTime = std::chrono::system_clock::to_time_t(now);
        std::tm* localTime = std::localtime(&currentTime);

        char buffer[20];
        std::strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", localTime);
        return std::string(buffer);
    }

    // Function to log a message with a timestamp
    void log(const std::string& message) {
        if (logFile) {
            logFile << getCurrentTimestamp() << " - " << message << std::endl;
        }
    }

    // Destructor to close the log file
    ~Logger() {
        if (logFile) {
            logFile.close();
        }
    }
};

int main() {
    Logger myLogger("logfile.txt");
    myLogger.log("This is a log entry.");
    myLogger.log("Another entry with a timestamp.");

    return 0;
}
Questions