qnx log写入文件 简单实现
qnx log写入文件 简单实现
#ifndef __COMMON_LOG__
#define __COMMON_LOG__
#include "fcntl.h"
#include "pthread.h"
#include "stdarg.h"
#include "unistd.h"
#include <stdio.h>
#include <string.h>
//#define _LOG_FILE_NAME "/tmp/easy.log"
#define _LOG_FILE_NAME "easy.log"
#if defined _LOG_FILE_NAME
void __file_log_com(char *log_str, ...);
#define __file__ \
({ \
char *_rs = strrchr((char*)__FILE__, '/'); \
_rs ? (_rs + 1) : __FILE__; \
})
#define _COM_FILE_PARSE(lgType, prefix, fmt, args...) \
do { \
__file_log_com("[%s][%s:%s:%d][%s]" fmt, lgType, __file__, __func__, __LINE__, prefix, ##args); \
} while (0)
#define ts_log_info(dev, fmt, args...) _COM_FILE_PARSE("info", dev, fmt, ##args)
#define ts_log_err(dev, fmt, args...) _COM_FILE_PARSE("error", dev, fmt, ##args)
#define ts_log_warn(dev, fmt, args...) _COM_FILE_PARSE("warning", dev, fmt, ##args)
#define ts_log_dbg(dev, fmt, args...) _COM_FILE_PARSE("debug", dev, fmt, ##args)
#else
#define ts_log_info(dev, fmt, args...)
#define ts_log_err(dev, fmt, args...)
#define ts_log_warn(dev, fmt, args...)
#define ts_log_dbg(dev, fmt, args...)
#endif
static pthread_mutex_t _log_mutex;
static FILE *_log_fp = NULL;
// qnx 简单log写入文件 实现
void __file_log_com(char *log_str, ...) {
va_list arg;
if (NULL != _log_fp) {
pthread_mutex_lock(&_log_mutex);
va_start(arg, log_str);
(void)vfprintf(_log_fp, log_str, arg);
va_end(arg);
//(void)fprintf(___fp, " \n");
//(void)fclose(fp);
fflush(_log_fp);
pthread_mutex_unlock(&_log_mutex);
}
}
void com_file_log_init(char *filename) {
_log_fp = fopen(filename, "w");
if (!_log_fp)
return perror(__func__);
pthread_mutex_init(&_log_mutex, NULL);
}
int main() {
printf( "hello\n");
com_file_log_init(_LOG_FILE_NAME);
char* dev_name = (char*)"E800";
ts_log_info(dev_name, "hello world");
// __file_log_com("%s,%s", dev_name, "e800");
printf( "finish\n");
return 0;
}
#endif
运行结果:
hello
finish
写入文件样子: