blob: 6878f895052224b61b41d18f670b09ff42921fb7 [file] [log] [blame]
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>
#define MAX_LOG_FILES 9
#define LOG_BUFFER_SIZE 8192 // 8KB
#define MAX_BUFFER_SIZE (16*1024)
static FILE *current_log_file = NULL;
static char log_buffer[LOG_BUFFER_SIZE];
static int log_buffer_index = 0;
static char current_header[8192];
static int current_header_len = 0;
#define LOG_PATH "/var/log/mtklog/mdlog2/"
void libdlta_init(const char *name, const char *desc)
{
memset(log_buffer, 0, LOG_BUFFER_SIZE);
log_buffer_index = 0;
memset(current_header, 0, sizeof(current_header));
current_header_len = 0;
int result = -1;
struct stat st = {0};
if(stat(LOG_PATH, &st) == -1)
{
result = system("mkdir -p " LOG_PATH );
if(result == 0)
{
printf("Directory created successfully.\n");
}
else
{
printf("Failed to create directory. Error code: %d\n", result);
}
}
return ;
}
void libdlta_deinit(void)
{
if (current_log_file != NULL)
{
if (log_buffer_index > 0)
{
fwrite(log_buffer, 1, log_buffer_index, current_log_file);
}
fclose(current_log_file);
current_log_file = NULL;
}
memset(log_buffer,0, LOG_BUFFER_SIZE);
log_buffer_index = 0;
return;
}
void rotate_logs(void)
{
char old_name[256];
char new_name[256];
snprintf(new_name, sizeof(new_name), "%smdlog_%d.muxz", LOG_PATH, MAX_LOG_FILES - 1);
remove(new_name);
for (int i = MAX_LOG_FILES - 1; i > 0; i--)
{
snprintf(old_name, sizeof(old_name), "%smdlog_%d.muxz", LOG_PATH, i - 1);
snprintf(new_name, sizeof(new_name), "%smdlog_%d.muxz", LOG_PATH, i);
rename(old_name, new_name);
}
}
void open_new_log_file(const char *header_buf, unsigned int header_len)
{
static char buffer[MAX_BUFFER_SIZE] = {0};
rotate_logs();
current_log_file = fopen(LOG_PATH"mdlog_0.muxz", "a+");
if (current_log_file == NULL)
{
perror("Failed to open new log file");
return;
}
if (setvbuf(current_log_file, buffer, _IOFBF, LOG_BUFFER_SIZE) != 0)
{
perror("Failed to set buffer for log file");
}
fwrite(header_buf, 1, header_len, current_log_file);
if(header_len <= sizeof(current_header))
{
memcpy(current_header, header_buf, header_len);
current_header_len = header_len;
}
}
void libdlta_sendlog(const char *header_buf, unsigned int header_len, const char *log_buf, unsigned int log_len)
{
if (current_log_file == NULL || header_len != current_header_len || memcmp(header_buf, current_header, header_len) != 0)
{
if (current_log_file != NULL)
{
libdlta_deinit();
}
open_new_log_file(header_buf, header_len);
}
if (log_len + log_buffer_index > LOG_BUFFER_SIZE)
{
fwrite(log_buffer, 1, log_buffer_index, current_log_file);
log_buffer_index = 0;
}
if (log_len < LOG_BUFFER_SIZE)
{
memcpy(log_buffer + log_buffer_index, log_buf, log_len);
log_buffer_index += log_len;
}
else
{
fwrite(log_buf, 1, log_len, current_log_file);
}
}