123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125 |
- /*
- * logger.cpp
- *
- * Created on: Feb 3, 2016
- * Author: Philipp Hinz
- */
- #include <stdio.h>
- #include <stdarg.h>
- #include <time.h>
- #include "global.h"
- #include "logger.h"
- int lastlog = 0;
- //TODO print to stdout and to file
- /**
- * Prints a timestamp
- * @param stream target stream (stdout, stderr)
- */
- void logger_print_time(_IO_FILE* stream) {
- time_t timer;
- char buffer[26];
- struct tm* tm_info;
- time(&timer);
- tm_info = localtime(&timer);
- strftime(buffer, 26, "%d-%m-%Y %H:%M:%S", tm_info);
- fprintf(stream, "[%s] ", buffer);
- }
- /**
- * Outputs the printf like formatted message to stderr and colorizes it
- * @param format printf formatted string
- */
- void logger_error(const char* format, ...) {
- pthread_mutex_lock(&mutex_logger);
- va_list args;
- fprintf( stderr, KRED);
- if (optDate)
- logger_print_time(stderr);
- fprintf( stderr, "Error: ");
- va_start(args, format);
- vfprintf( stderr, format, args);
- va_end(args);
- fprintf( stderr, KNRM);
- lastlog = LOG_ERROR;
- pthread_mutex_unlock(&mutex_logger);
- }
- /**
- * Resets the logger to prevent the previous line being overdrawn.
- * Call after custom printf
- */
- void logger_reset() {
- lastlog = 0;
- }
- /**
- * prints the message to stdout and formats it
- * @param verboselevel minimum verbose level for output
- * @param logtype type of logmessage for coloring
- * @param format printf formatted string
- */
- void logger(logger_verbose_t verboselevel, logger_type_t logtype,
- const char* format, ...) {
- if (verbose < verboselevel)
- return;
- pthread_mutex_lock(&mutex_logger);
- switch (logtype) {
- case LOG_CAN:
- printf(KBOLD);
- break;
- case LOG_OK:
- printf(KGRN);
- break;
- case LOG_WARN:
- printf(KYEL);
- break;
- case LOG_ERROR:
- printf(KRED);
- break;
- case LOG_ERRORC:
- if (lastlog == LOG_ERRORC)
- printf(CLEARLINE);
- break;
- case LOG_INFO:
- default:
- break;
- }
- if (optDate)
- logger_print_time(stdout);
- va_list args;
- va_start(args, format);
- vprintf(format, args);
- va_end(args);
- if (logtype > 0)
- printf(KNRM);
- lastlog = logtype;
- pthread_mutex_unlock(&mutex_logger);
- }
- /**
- * prints the message to stdout
- * @param verboselevel minimum verbose level for output
- * @param format printf formatted string
- */
- void logger(logger_verbose_t verboselevel, const char* format, ...) {
- if (verbose < verboselevel)
- return;
- pthread_mutex_lock(&mutex_logger);
- if (optDate)
- logger_print_time(stdout);
- va_list args;
- va_start(args, format);
- vprintf(format, args);
- va_end(args);
- lastlog = 0;
- pthread_mutex_unlock(&mutex_logger);
- }
|