This commit is contained in:
Hizenberg469
2025-01-10 20:51:19 +05:30
commit 7563c1ad59
6 changed files with 148 additions and 0 deletions

31
src/b_string.c Normal file
View File

@@ -0,0 +1,31 @@
#include "b_string.h"
#include <stdlib.h>
#include <string.h>
b_string_t *alloc_b_string(size_t len, const char* str)
{
b_string_t *b_str;
b_str = malloc(sizeof(b_string_t) + len + 1);
if(b_str)
{
memcpy(b_str->str, str, len);
/*NULL-terminate the string to indicate
* end of string.
*/
b_str->str[len] = '\0';
b_str->len = len;
}
return b_str;
}
void free_b_string(b_string_t *b_str)
{
free(b_str);
}

69
src/log.c Normal file
View File

@@ -0,0 +1,69 @@
#include "log.h"
#include <pthread.h>
#include <stdarg.h>
#include <time.h>
#include <unistd.h>
#include <sys/syscall.h>
/*
* This declaration of pthread mutex allow to
* initialize the mutex statically, for quick
* use. It is an alternate for pthread_mutex_init()
* function.
*/
static pthread_mutex_t log_lock = PTHREAD_MUTEX_INITIALIZER;
static int log_type = DEFAULT_LOG_TYPE;
static FILE *logfile = NULL;
void log_set_type(log_type_t typ)
{
pthread_mutex_lock(&log_lock);
log_type = typ;
pthread_mutex_unlock(&log_lock);
}
void log_set_logfile(FILE *f)
{
pthread_mutex_lock(&log_lock);
logfile = f;
pthread_mutex_unlock(&log_lock);
}
void log_printf(log_type_t typ, const char *fmt, ...)
{
va_list args;
long tid = (long)syscall(SYS_gettid);
time_t now = time(0);
char timestr[9];
strftime(timestr, sizeof(timestr), "%H:%M:%S", localtime(&now));
pthread_mutex_lock(&log_lock);
if( typ < log_type )
{
pthread_mutex_lock(&log_lock);
return;
}
fprintf(logfile, "[%.*s] [%05ld] ", 8, timestr, tid);
switch(typ){
case WARNING_LOG:
fprintf(logfile, "WARNING: ");
break;
case ERROR_LOG:
fprintf(logfile, "ERROR: ");
break;
}
va_start(args, fmt);
vfprintf(logfile, fmt, args);
va_end(args);
pthread_mutex_unlock(&log_lock);
fflush(logfile);
}