// Module: log.c
//
// logging library
// ANSI escape codes:
// gist.github.com/fnky/458719343aabd01cfb17a3a4f7296797
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <time.h>
#include "log.h"
#include <unistd.h>
#ifndef u8
#define u8 uint8_t
#define s8 int8_t
#endif
// Define ANSI colors, to be used within printf() text
// The foreground colors 30 - 38, are the "normal" darker colors
// The foreground colors 90 - 98, are the "bright" lighter colors
// These #defines rely on string concatenation to function as desired
#define COLOR_YELLOW_ON_BLACK "\033[93m\033[40m"
#define COLOR_YELLOW_ON_BLUE "\033[93m\033[44m"
#define COLOR_YELLOW_ON_GREEN "\033[93m\033[42m"
#define COLOR_YELLOW_ON_RED "\033[93m\033[41m"
#define COLOR_YELLOW_ON_VIOLET "\033[93m\033[45m"
#define COLOR_WHITE
#define COLOR_RED
#define COLOR_GREEN "\033[92m" /* Bright Green text */
#define COLOR_VIOLET "\033[95m" /* Bright Violet text */
#define COLOR_YELLOW "\033[93m" /* Bright Yellow text */
#define COLOR_RESET "\033[0m" /* Reset text color to previous color */
#define TEXT_ADMIN "\e[31m"
#define TEXT_ORANGE "\e[38;5;202m"
#define TEXT_BROWN "\e[38;5;130m"
#define TEXT_YELLOW "\e[93m"
#define TEXT_PUKE "\e[33m"
#define TEXT_LIME "\e[92m"
#define TEXT_GREEN "\e[32m"`
#define TEXT_AQUA "\e[96m"
#define MAX_LOG_ITEM 150 // maximum number of bytes for a log (with length, time, level, and text
// Definition of a "log item":
typedef struct {
u8 length; // includes sizeof(time), sizeof(level), strlen(text)
u8 time[4]; // 32 bits, stored in network byte order, MSB first (index 0)
u8 level;
char text[MAX_LOG_ITEM-6]; // log text
} log_item_t;
// Implementation rules / notes:
// 1) Use a "staging buffer" of some max length to write formatted text into
// This buffer will NOT contain ANSI color escapes or line termination.
// 2) A small data structure is used on the front of the "log item" to
// contain time stamp, log level, and string length.
// u8 length - bytes following
uint32_t get_time(void)
{
uint32_t milliseconds;
struct timespec ts;
if (clock_gettime(CLOCK_MONOTONIC_RAW /*CLOCK_MONOTONIC*/, &ts) == -1) {
perror("clock_gettime");
exit(EXIT_FAILURE);
}
milliseconds = (ts.tv_sec * 1000) + (ts.tv_nsec / 1000000); // convert seconds into milliseconds & nanoseconds into milliseconds
printf("%s: %u\n",__func__,milliseconds);
return milliseconds;
}
int main(int argc, const char* argv[])
{
get_time();
printf(COLOR_VIOLET "COLOR_VIOLET" COLOR_RESET "\n");
for(int ansi = 30; ansi<=37; ansi++)
printf("\033[%dm Foreground Color: %d\033[0m\n",ansi,ansi);
for(int ansi = 90; ansi<=97; ansi++)
printf("\033[%dm Foreground Color: %d\033[0m\n",ansi,ansi);
for(int ansi = 40; ansi<=47; ansi++)
printf("\033[%dm Background Color: %d\033[0m\n",ansi,ansi);
for(int ansi = 100; ansi<=107; ansi++)
printf("\033[%dm Background Color: %d\033[0m\n",ansi,ansi);
usleep(1000);
get_time();
return 0;
}