使用C语言设计编写程序日志,实现时间戳、 日志级别、日志内容、 日志输出、 日志轮转功能,其中日志轮转功能具体指的是在文件内存超出一定限制后再新建一个日志文件,只需要给出具体的log.c,log.h和测试代码main,
时间: 2024-02-18 15:01:56 浏览: 71
用C语言实现高效日志功能(含源码)
5星 · 资源好评率100%
好的,我可以帮您设计实现这个程序日志,以下是log.h和log.c的代码实现,以及一个简单的测试代码main:
log.h
```c
#ifndef LOG_H
#define LOG_H
#include <stdio.h>
#include <stdarg.h>
#include <time.h>
#define LOG_LEVEL_DEBUG 1
#define LOG_LEVEL_INFO 2
#define LOG_LEVEL_WARN 3
#define LOG_LEVEL_ERROR 4
#define MAX_LOG_SIZE 1024 * 1024 // 日志文件最大大小,单位为字节
#define MAX_LOG_FILES 10 // 最多保留的日志文件数
typedef struct {
FILE *fp;
char *filename;
int level;
long size;
} log_t;
log_t *log_create(char *filename, int level);
void log_destroy(log_t *log);
void log_write(log_t *log, int level, const char *fmt, ...);
void log_rotate(log_t *log);
#endif
```
log.c
```c
#include "log.h"
static const char *LOG_LEVEL_STR[] = {"", "DEBUG", "INFO", "WARN", "ERROR"};
log_t *log_create(char *filename, int level) {
log_t *log = (log_t *) malloc(sizeof(log_t));
if (!log) {
fprintf(stderr, "Failed to allocate memory for log\n");
return NULL;
}
log->filename = filename;
log->level = level;
log->size = 0;
log->fp = fopen(log->filename, "a");
if (!log->fp) {
fprintf(stderr, "Failed to open log file %s\n", log->filename);
free(log);
return NULL;
}
return log;
}
void log_destroy(log_t *log) {
if (log) {
if (log->fp) {
fclose(log->fp);
log->fp = NULL;
}
free(log);
}
}
void log_write(log_t *log, int level, const char *fmt, ...) {
if (log && log->fp && level >= log->level) {
va_list args;
va_start(args, fmt);
time_t t = time(NULL);
struct tm *lt = localtime(&t);
char timestamp[20];
strftime(timestamp, sizeof(timestamp), "%Y-%m-%d %H:%M:%S", lt);
fprintf(log->fp, "[%s] [%s] ", timestamp, LOG_LEVEL_STR[level]);
vfprintf(log->fp, fmt, args);
fprintf(log->fp, "\n");
log->size = ftell(log->fp);
va_end(args);
if (log->size >= MAX_LOG_SIZE) {
log_rotate(log);
}
}
}
void log_rotate(log_t *log) {
if (log) {
fclose(log->fp);
log->fp = NULL;
char new_filename[100];
snprintf(new_filename, sizeof(new_filename), "%s.%d", log->filename, 1);
remove(new_filename);
for (int i = MAX_LOG_FILES - 1; i >= 1; i--) {
char old_filename[100], new_filename[100];
snprintf(old_filename, sizeof(old_filename), "%s.%d", log->filename, i - 1);
snprintf(new_filename, sizeof(new_filename), "%s.%d", log->filename, i);
remove(new_filename);
rename(old_filename, new_filename);
}
rename(log->filename, new_filename);
log->fp = fopen(log->filename, "a");
log->size = 0;
}
}
```
main.c
```c
#include "log.h"
int main() {
log_t *log = log_create("test.log", LOG_LEVEL_DEBUG);
if (!log) {
return 1;
}
for (int i = 0; i < 100000; i++) {
log_write(log, LOG_LEVEL_INFO, "This is a log message %d", i);
}
log_destroy(log);
return 0;
}
```
这个程序日志支持四个日志级别:DEBUG、INFO、WARN、ERROR,日志文件最大大小为1MB,最多保留10个日志文件。当日志文件大小超过1MB时,会自动轮转日志文件。
阅读全文