Request for Feedback: Review and Improvements for a C++ Logging Utility, I am new to C++

I have written a simple logging utility in C++ consisting of a header (log.h) and implementation (log.cpp) file. I aim to ensure the code is efficient and maintainable. Below is the code for both files. It is only for windows.

log.h

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>#ifndef LOG_H
#define LOG_H
#include <iostream>
#include <string>
#include <chrono>
#include <ctime>
namespace Logger {
enum class LogLevel {
DEBUG,
INFO,
WARNING,
ERROR,
CRITICAL
};
void log(LogLevel logLevel, const std::string& message, std::ostream& outputStream = std::cerr);
std::string getLevelString(LogLevel logLevel);
std::string getLevelColor(LogLevel logLevel);
}
#endif // LOG_H
</code>
<code>#ifndef LOG_H #define LOG_H #include <iostream> #include <string> #include <chrono> #include <ctime> namespace Logger { enum class LogLevel { DEBUG, INFO, WARNING, ERROR, CRITICAL }; void log(LogLevel logLevel, const std::string& message, std::ostream& outputStream = std::cerr); std::string getLevelString(LogLevel logLevel); std::string getLevelColor(LogLevel logLevel); } #endif // LOG_H </code>
#ifndef LOG_H
#define LOG_H

#include <iostream>
#include <string>
#include <chrono>
#include <ctime>

namespace Logger {
    enum class LogLevel {
        DEBUG,
        INFO,
        WARNING,
        ERROR,
        CRITICAL
    };

    void log(LogLevel logLevel, const std::string& message, std::ostream& outputStream = std::cerr);

    std::string getLevelString(LogLevel logLevel);
    std::string getLevelColor(LogLevel logLevel);
}

#endif // LOG_H

**

log.cpp**

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>#include "Log.h"
namespace Logger {
void log(LogLevel logLevel, const std::string& message, std::ostream& outputStream) {
auto now = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
std::tm tm;
if (localtime_s(&tm, &now) != 0) {
// Handle error, e.g., unable to convert time
outputStream << "Error: Unable to get local time." << std::endl;
return;
}
char timestamp[20]; // Enough to hold the timestamp
std::strftime(timestamp, sizeof(timestamp), "%Y-%m-%d %H:%M:%S", &tm);
outputStream << getLevelColor(logLevel);
outputStream << getLevelString(logLevel) << " [" << timestamp << "] " << message << "33[0m" << std::endl; // Reset color after message
}
std::string getLevelString(LogLevel logLevel) {
switch (logLevel) {
case LogLevel::DEBUG:
return "[DEBUG]";
case LogLevel::INFO:
return "[INFO]";
case LogLevel::WARNING:
return "[WARNING]";
case LogLevel::ERROR:
return "[ERROR]";
case LogLevel::CRITICAL:
return "[CRITICAL]";
default:
return "[UNKNOWN]";
}
}
std::string getLevelColor(LogLevel logLevel) {
switch (logLevel) {
case LogLevel::DEBUG:
return "33[34m"; // Blue
case LogLevel::INFO:
return "33[32m"; // Green
case LogLevel::WARNING:
return "33[33m"; // Yellow
case LogLevel::ERROR:
return "33[31m";
case LogLevel::CRITICAL:
return "33[35m"; // Red for both ERROR and CRITICAL
default:
return ""; // No color
}
}
}
</code>
<code>#include "Log.h" namespace Logger { void log(LogLevel logLevel, const std::string& message, std::ostream& outputStream) { auto now = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); std::tm tm; if (localtime_s(&tm, &now) != 0) { // Handle error, e.g., unable to convert time outputStream << "Error: Unable to get local time." << std::endl; return; } char timestamp[20]; // Enough to hold the timestamp std::strftime(timestamp, sizeof(timestamp), "%Y-%m-%d %H:%M:%S", &tm); outputStream << getLevelColor(logLevel); outputStream << getLevelString(logLevel) << " [" << timestamp << "] " << message << "33[0m" << std::endl; // Reset color after message } std::string getLevelString(LogLevel logLevel) { switch (logLevel) { case LogLevel::DEBUG: return "[DEBUG]"; case LogLevel::INFO: return "[INFO]"; case LogLevel::WARNING: return "[WARNING]"; case LogLevel::ERROR: return "[ERROR]"; case LogLevel::CRITICAL: return "[CRITICAL]"; default: return "[UNKNOWN]"; } } std::string getLevelColor(LogLevel logLevel) { switch (logLevel) { case LogLevel::DEBUG: return "33[34m"; // Blue case LogLevel::INFO: return "33[32m"; // Green case LogLevel::WARNING: return "33[33m"; // Yellow case LogLevel::ERROR: return "33[31m"; case LogLevel::CRITICAL: return "33[35m"; // Red for both ERROR and CRITICAL default: return ""; // No color } } } </code>
#include "Log.h"

namespace Logger {
    void log(LogLevel logLevel, const std::string& message, std::ostream& outputStream) {
        auto now = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
        std::tm tm;
        if (localtime_s(&tm, &now) != 0) {
            // Handle error, e.g., unable to convert time
            outputStream << "Error: Unable to get local time." << std::endl;
            return;
        }

        char timestamp[20]; // Enough to hold the timestamp
        std::strftime(timestamp, sizeof(timestamp), "%Y-%m-%d %H:%M:%S", &tm);

        outputStream << getLevelColor(logLevel);
        outputStream << getLevelString(logLevel) << " [" << timestamp << "] " << message << "33[0m" << std::endl; // Reset color after message
    }

    std::string getLevelString(LogLevel logLevel) {
        switch (logLevel) {
        case LogLevel::DEBUG:
            return "[DEBUG]";
        case LogLevel::INFO:
            return "[INFO]";
        case LogLevel::WARNING:
            return "[WARNING]";
        case LogLevel::ERROR:
            return "[ERROR]";
        case LogLevel::CRITICAL:
            return "[CRITICAL]";
        default:
            return "[UNKNOWN]";
        }
    }

    std::string getLevelColor(LogLevel logLevel) {
        switch (logLevel) {
        case LogLevel::DEBUG:
            return "33[34m"; // Blue
        case LogLevel::INFO:
            return "33[32m"; // Green
        case LogLevel::WARNING:
            return "33[33m"; // Yellow
        case LogLevel::ERROR:
            return "33[31m";
        case LogLevel::CRITICAL:
            return "33[35m"; // Red for both ERROR and CRITICAL
        default:
            return ""; // No color
        }
    }
}

Questions:

Time Handling: I am using localtime_s for converting time to a local time structure and then formatting it using std::strftime. Are there any potential pitfalls with this approach, particularly regarding portability and thread safety? Is there a better way to handle timestamps?

Color Coding: The log levels are color-coded using ANSI escape codes. Is this a good practice for terminal output, or are there better alternatives for cross-platform compatibility?

Default Parameters: I have used std::cerr as the default output stream. Is this a reasonable default, or should I consider a different approach? How can I allow more flexibility in setting the default output stream?

Error Handling: In the event of a failure in localtime_s, the error is logged to the same output stream. Is this an appropriate way to handle such errors, or are there better error-handling practices for logging libraries?

Code Structure and Readability: Are there any improvements I can make to the structure or style of my code to enhance readability and maintainability?

Extensibility: How can I make this logging utility more extensible? For example, supporting different timestamp formats, log destinations, or additional log levels.

Performance Considerations: Are there any performance optimizations I should consider, especially in scenarios where logging occurs frequently? For instance, should I look into buffering log messages or minimizing the time taken for each log call?

Any other feedback or best practices would be greatly appreciated!

Thank you in advance for your time and expertise.

this is the output

New contributor

Kaushik Das is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

1

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật