Skip to content

Instantly share code, notes, and snippets.

@Moon93
Last active August 2, 2016 13:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Moon93/7db4e5c399ab5deafe5b17c014956366 to your computer and use it in GitHub Desktop.
Save Moon93/7db4e5c399ab5deafe5b17c014956366 to your computer and use it in GitHub Desktop.
Logging wrapper for printf. Uses shell commands to add some colours. Define loglevel in line 8 and output file in line 17 (replace stdout).
/**
* implements the logging functions
*/
#include "logging.h"
enum{Debug, Info, Warning, Error, Fatal, Off};
//define the loglevel here
int loglevel = Debug;
/**
* private function to wrap fprintf
*/
void printLog(char* message, char* logLevel) {
//get current time
time_t now = time(0);
fprintf(stdout, "%s - %s: %s\n", ctime(&now), logLevel, message);
fflush(stdout);
}
void logError(char* message, ...){
if(loglevel <= Error){
char* level = "\033[31mError\033[m";
va_list args;
va_start(args, message);
char buffer[512];
vsnprintf(buffer, sizeof(buffer), message, args);
printLog(buffer, level);
va_end(args);
}
}
void logWarning(char* message, ...){
if(loglevel <= Warning){
char* level = "\033[33mWarning\033[m";
va_list args;
va_start(args, message);
char buffer[512];
vsnprintf(buffer, sizeof(buffer), message, args);
printLog(buffer, level);
va_end(args);
}
}
void logInfo(char* message, ...){
if(loglevel <= Info){
char* level = "Info";
va_list args;
va_start(args, message);
char buffer[512];
vsnprintf(buffer, sizeof(buffer), message, args);
printLog(buffer, level);
va_end(args);
}
}
void logDebug(char* message, ...){
if(loglevel <= Debug){
char* level = "\033[2mDebug\033[m";
va_list args;
va_start(args, message);
char buffer[512];
vsnprintf(buffer, sizeof(buffer), message, args);
printLog(buffer, level);
va_end(args);
}
}
void logFatal(char* message, ...){
if(loglevel <= Fatal){
char* level = "\033[33mFatal\033[m";
va_list args;
va_start(args, message);
char buffer[512];
vsnprintf(buffer, sizeof(buffer), message, args);
printLog(buffer, level);
va_end(args);
}
}
#ifndef logging_h_
#define logging_h_
#include <stdio.h>
#include <time.h>
#include <stdarg.h>
void logError(char* message, ...);
void logWarning(char* message, ...);
void logInfo(char* message, ...);
void logDebug(char* message, ...);
void logFatal(char* message, ...);
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment