Tiny Logger: Timestamped Logs with Levels (No Dependencies)
Tiny Logger: Timestamped Logs with Levels (No Dependencies)
Introduction
Creating a logger from scratch can seem like an overkill, but it's actually quite straightforward when you leverage the standard library. Our Tiny Logger will allow us to log messages with different levels (e.g., INFO, ERROR) and include timestamps for each entry.
Implementation
Here's a simple implementation of the logger in just a few lines of code:
#include <iostream>
#include <string>
#include <chrono>
#include <ctime>
enum LogLevel {
INFO,
ERROR
};
std::string getTimestamp() {
auto now = std::chrono::system_clock::now();
auto time_t_now = std::chrono::system_clock::to_time_t(now);
char buf[100] = {0};
strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", std::localtime(&time_t_now));
return std::string(buf);
}
void log(LogLevel level, const std::string& message) {
std::string levelStr = (level == INFO) ? "INFO" : "ERROR";
std::cout << "[" << getTimestamp() << "] [" << levelStr << "] " << message << std::endl;
}
int main() {
log(INFO, "This is an informational message.");
log(ERROR, "This is an error message.");
return 0;
}
Explanation
Let's break down the code:
- LogLevel Enum: Defines two log levels, `INFO` and `ERROR`, which can be easily extended.
- getTimestamp Function: Retrieves the current timestamp as a formatted string.
- log Function: Takes a `LogLevel` and a message string, formats them with the timestamp, and outputs to the console.
Conclusion
Creating a tiny logger in C++ is straightforward and doesn't require any external dependencies. By using basic standard library features like `std::chrono` for timestamps and `enum` for log levels, you can build a robust logging system that fits well into any project. This simple yet effective solution helps maintain clean and informative logs, making debugging and monitoring easier.