c_cpp 带有旋转逻辑的C语言记录器实现
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 带有旋转逻辑的C语言记录器实现相关的知识,希望对你有一定的参考价值。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
static const char* LOG_LEVEL_DEBUG = "DEBUG";
static const char* LOG_LEVEL_INFO = "INFO";
static const char* LOG_LEVEL_WARNING = "WARNING";
static const char* LOG_LEVEL_ERROR = "ERROR";
#ifdef WIN32_UTF16_PATHNAMES
# error "UTF-16 pathnames not supported"
#endif
struct logger_t {
FILE* stream;
char time_buf[26];
const char* path;
struct tm* time_info;
unsigned rotation;
size_t curr_size;
size_t max_size;
time_t log_time;
};
/**
* sets log time according to local time.
*/
static inline void
logger_set_time(struct logger_t* log)
{
time(&(log->log_time));
log->time_info = localtime(&(log->log_time));
strftime(log->time_buf, 26, "%Y-%m-%d %H:%M:%S", log->time_info);
}
/**
* Initializes logger instance,
* checks if null on fopen
*/
static int
logger_init(struct logger_t* log,
const char* pathname, size_t max_size)
{
char path_bin[256];
strncpy(path_bin, log->path, 256);
strcat(path_bin, "0");
log->rotation = 0;
log->stream = fopen(path_bin, "a");
if(log->stream == NULL) return 0;
log->curr_size = 0;
log->max_size = max_size;
return 1;
}
/**
* rotating logic,
* will increment integer at the end of file name
*/
static int
logger_check_rotation(struct logger_t* log)
{
if(log->max_size > log->curr_size) {
return 1;
} else {
size_t cur_path_len;
char path_bin[256];
char rot_int[12];
strncpy(path_bin, log->path, 256);
fclose(log->stream);
log->rotation++;
sprintf(rot_int, "%u", log->rotation);
strcat(path_bin, rot_int);
log->stream = fopen(path_bin, "a");
if(log->stream == NULL) return 0;
return 1;
}
}
/**
* method to log events, with chosen level and pre-formatted message.
*/
extern int logger_log_event(struct logger_t* log,
const char* level,
const char* restrict mes)
{
size_t event_size;
if(!logger_check_rotation(log)) return 0;
logger_set_time(log);
event_size = strlen(log->time_buf) + strlen(level) +strlen(mes);
log->curr_size += event_size;
fprintf(log->stream, "%s %s %s", log->time_buf, level, mes);
return 1;
}
以上是关于c_cpp 带有旋转逻辑的C语言记录器实现的主要内容,如果未能解决你的问题,请参考以下文章
c_cpp 如何从3D矢量计算轴旋转或旋转矩阵
c_cpp 48.旋转图像
c_cpp 旋转链接列表
c_cpp 二元搜索 - 圆形旋转阵列的应用
c_cpp 在OBJECT周围旋转对象
c_cpp 旋转数组的最小数字的.cpp