+ timestamps for logging

This commit is contained in:
Julian Hinxlage 2019-11-05 15:19:51 +01:00
parent 53afcffba8
commit 9b89e46de2
2 changed files with 61 additions and 1 deletions

View File

@ -1,7 +1,13 @@
/**
* @author Julian Hinxlage
* @since 0.1.0
*/
#include "log.h"
#include <iostream>
//converts the level to a string of the level
const char *getLevelName(LogLevel level){
switch(level){
case LogLevel::DEBUG:
@ -19,6 +25,7 @@ const char *getLevelName(LogLevel level){
}
}
//converts the level to a ansi color code
const char *getLevelColor(LogLevel level){
switch(level){
case LogLevel::DEBUG:
@ -38,19 +45,61 @@ const char *getLevelColor(LogLevel level){
LogLevel logLevel = LogLevel::INFO;
//log the current time
void logTime(){
time_t rawtime;
time(&rawtime);
struct tm *timeinfo;
timeinfo = localtime(&rawtime);
if (timeinfo->tm_hour < 10) {
std::cout << "0";
}
std::cout << timeinfo->tm_hour;
std::cout << ":";
if (timeinfo->tm_min < 10) {
std::cout << "0";
}
std::cout << timeinfo->tm_min;
std::cout << ":";
if (timeinfo->tm_sec < 10) {
std::cout << "0";
}
std::cout << timeinfo->tm_sec;
}
//log the message
void log(const std::string &msg, LogLevel level) {
if(level >= logLevel) {
std::string levelName = getLevelName(level);
int maxLevelNameLength = 8;
//time
std::cout << "[";
logTime();
std::cout << "] ";
//color and level name;lo
std::cout << "[";
std::cout << "\033[" << getLevelColor(level) << "m" << levelName << "\033[0m";
std::cout << "] ";
for (int i = levelName.size(); i < maxLevelNameLength; i++) {
std::cout << " ";
}
std::cout << msg << "\n";
//message
for(char c : msg){
if(c == '\n'){
//intend newlines so that they align with the start of the message
std::cout << "\n";
for(int i = 0; i < 22;i++){
std::cout << " ";
}
}else{
std::cout << c;
}
}
std::cout << "\n";
}
}

View File

@ -12,8 +12,19 @@ enum LogLevel{
OFF = 6
};
/**
* log the messgae with logLevel and timestamp
* @author Julian Hinxlage
* @since 0.1.0
*/
void log(const std::string &msg, LogLevel level = LogLevel::INFO);
/**
* set the logLevel, the log function will use this to determine if the message is logged
* @author Julian Hinxlage
* @since 0.1.0
*/
void setLogLevel(LogLevel level);
#endif //LIBRARY_LOG_H