Open In App

Logging System in C++

Last Updated : 29 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The logging system is a very critical component to track how the application behaves, find the problems, and understand the performance of the system. We can create a simple also very effective logging system in C++ to capture and record various events and data that occur during the execution of a program.

logging system in cpp

Designing Consideration for a Logging System

A basic logging system should include the following functionalities to implement a logging system:

  • Logging Levels: Use various log levels to group communications according to their significance or seriousness. The log levels DEBUG, INFO, WARNING, ERROR, and CRITICAL are often seen.
  • Final Destinations: Permit users to choose the destination of log messages with flexibility. Log files, console output, and external services are examples of this.
  • Context and Timestamps: To give log entries a chronological context, provide timestamps. You can just choose to provide additional context by including file names, line numbers, or function names.
  • Setup: Give developers the ability to dynamically customize the logging system so they may change the destinations or reporting levels without having to change the code.

Implementing a Simple Logging System in C++

The below program implements a logging system in C++.

C++




// C++ program to implement a basic logging system.
  
#include <ctime>
#include <fstream>
#include <iostream>
#include <sstream>
using namespace std;
  
// Enum to represent log levels
enum LogLevel { DEBUG, INFO, WARNING, ERROR, CRITICAL };
  
class Logger {
public:
    // Constructor: Opens the log file in append mode
    Logger(const string& filename)
    {
        logFile.open(filename, ios::app);
        if (!logFile.is_open()) {
            cerr << "Error opening log file." << endl;
        }
    }
  
    // Destructor: Closes the log file
    ~Logger() { logFile.close(); }
  
    // Logs a message with a given log level
    void log(LogLevel level, const string& message)
    {
        // Get current timestamp
        time_t now = time(0);
        tm* timeinfo = localtime(&now);
        char timestamp[20];
        strftime(timestamp, sizeof(timestamp),
                 "%Y-%m-%d %H:%M:%S", timeinfo);
  
        // Create log entry
        ostringstream logEntry;
        logEntry << "[" << timestamp << "] "
                 << levelToString(level) << ": " << message
                 << endl;
  
        // Output to console
        cout << logEntry.str();
  
        // Output to log file
        if (logFile.is_open()) {
            logFile << logEntry.str();
            logFile
                .flush(); // Ensure immediate write to file
        }
    }
  
private:
    ofstream logFile; // File stream for the log file
  
    // Converts log level to a string for output
    string levelToString(LogLevel level)
    {
        switch (level) {
        case DEBUG:
            return "DEBUG";
        case INFO:
            return "INFO";
        case WARNING:
            return "WARNING";
        case ERROR:
            return "ERROR";
        case CRITICAL:
            return "CRITICAL";
        default:
            return "UNKNOWN";
        }
    }
};
  
int main()
{
    Logger logger("logfile.txt"); // Create logger instance
  
    // Example usage of the logger
    logger.log(INFO, "Program started.");
    logger.log(DEBUG, "Debugging information.");
    logger.log(ERROR, "An error occurred.");
  
    return 0;
}


Output

[2024-01-22 10:49:14] INFO: Program started.
[2024-01-22 10:49:14] DEBUG: Debugging information.
[2024-01-22 10:49:14] ERROR: An error occurred.





Advantages of Logging in Programming

A key component of software development is logging, which tracks data on a program’s execution. It fulfills several functions, such as:

  1. Debugging: logging aids in identifying and diagnosing the problems in the code as it offers insights into the execution flow and variable values at various stages.
  2. Monitoring: logs are very useful to track the problems, monitor program behavior, and locate performance bottlenecks.
  3. Auditing: By maintaining a record of noteworthy occurrences, user actions, or system activity, logging makes auditing and compliance easier.
  4. Troubleshooting: When users run into difficulties, logs may provide important information for identifying and fixing problems.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads