2024-04-22 00:09:51 +08:00

113 lines
2.9 KiB
C

/*********************************************************************************************************
* ------------------------------------------------------------------------------------------------------
* file description
* ------------------------------------------------------------------------------------------------------
* \file vlog.c
* \unit vlog
* \brief This is a simple log module for C language
* \author Lamdonn
* \version v1.0.0
* \license GPL-2.0
* \copyright Copyright (C) 2023 Lamdonn.
********************************************************************************************************/
#include "vlog.h"
#include <stdio.h>
static char channel_table = VLOG_CHANNEL_0; /* Channel configuration, default only opens channel 0 */
static char vlog_buffer[VLOG_BUFFER_SIZE]; /* vlog output buffer */
static vlog_func_t vlog_func = 0; /* Additional vlog callback function */
static FILE *vlog_file = 0; /* Offline recorded files */
/**
* \brief output log information
* \param[in] channel: VLOG_CHANNEL_XXX, from 0 to 7
* \param[in] format: format string
* \param[in] ...: format parameters
* \return log string length
*/
int vlog(char channel, const char *format, ...)
{
int len = 0;
va_list args;
/* Check channel effectiveness */
if (channel & channel_table)
{
va_start(args, format);
len = vsnprintf(vlog_buffer, sizeof(vlog_buffer), format, args);
/* Output to default console */
printf(vlog_buffer);
/* Output to offline file */
if (vlog_file) fwrite(vlog_buffer, sizeof(char), len, vlog_file);
/* Output to callback function */
if (vlog_func) vlog_func(vlog_buffer, len);
va_end(args);
}
return len;
}
/**
* \brief set vlog channel configuration
* \param[in] channel: VLOG_CHANNEL_XXX, from 0 to 7, multiple channels can be selected through `|`
* \return none
*/
void vlog_set_channel(char channel)
{
channel_table = channel;
}
/**
* \brief get vlog channel configuration
* \return channel configuration
*/
char vlog_get_channel(void)
{
return channel_table;
}
/**
* \brief start vlog offline save, need to be used in pairs with vlog_stop_offline()
* \param[in] *filename: offline save file name
* \return 1 success or 0 fail
*/
int vlog_start_offline(const char *filename)
{
FILE *file;
file = fopen(filename, "a+");
if (!file) return 0;
vlog_file = file;
return 1;
}
/**
* \brief stop vlog offline save, need to be used in pairs with vlog_start_offline()
* \return none
*/
void vlog_stop_offline(void)
{
if (vlog_file)
{
fclose(vlog_file);
vlog_file = 0;
}
}
/**
* \brief set additional vlog callback function
* \return none
*/
void vlog_set_func(vlog_func_t func)
{
vlog_func = func;
}