Skip to content

Instantly share code, notes, and snippets.

@yudenzel
Created May 24, 2019 08:29
Show Gist options
  • Select an option

  • Save yudenzel/af83b25c8b421b44b0c504b4a214deb8 to your computer and use it in GitHub Desktop.

Select an option

Save yudenzel/af83b25c8b421b44b0c504b4a214deb8 to your computer and use it in GitHub Desktop.
#include <time.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#ifdef __cplusplus
extern "C" {
#endif
void __file_log_print(const int lvl, const char* tag, const char* fmt, ...)
{
static const char* s_priorities[] = { "-", "+", "V", "D", "I", "W", "E", "F", "S" };
static int num_of_priorities = sizeof(s_priorities) / sizeof( s_priorities[0] );
static pthread_mutex_t s_log_mutex = PTHREAD_MUTEX_INITIALIZER;
static FILE *log_file_stream = NULL;
pthread_mutex_lock(&s_log_mutex);
// create file if not exists
if( !log_file_stream ) {
log_file_stream = fopen("/sdcard/log.log", "a");
}
if( log_file_stream ) {
long milliseconds; // Milliseconds
time_t epoch_seconds; // Seconds
struct timespec time_spec;
clock_gettime(CLOCK_REALTIME, &time_spec);
epoch_seconds = time_spec.tv_sec;
milliseconds = time_spec.tv_nsec / 1000000; // Convert nanoseconds to milliseconds
epoch_seconds += milliseconds / 1000;
milliseconds = milliseconds % 1000;
struct tm local_time = { 0 };
localtime_r(&epoch_seconds, &local_time);
// print time
fprintf(log_file_stream, "\n[%02d-%02d-%02d %02d:%02d:%02d.%03d] %d %d %s: %s: ",
local_time.tm_year+1900,
local_time.tm_mon+1,
local_time.tm_mday,
local_time.tm_hour,
local_time.tm_min,
local_time.tm_sec,
milliseconds,
getpid(),
gettid(),
((lvl >= 0 && lvl < num_of_priorities) ? s_priorities[lvl] : s_priorities[0]),
tag
);
// print msg
va_list args;
va_start(args, fmt);
vfprintf(log_file_stream, fmt, args);
va_end(args);
// flush log to system
fflush(log_file_stream);
}
pthread_mutex_unlock(&s_log_mutex);
}
#ifdef __cplusplus
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment