5分钟学会:超级简单的日志函数
日志函数本质上就是把数据写入到文件中。因此没有什么难度,这里直接上代码:
void log_event(int level, const char *message, const char *filename){
time_t now = time(NULL);
char *level_str;
FILE *fp;
switch(level) {
case LOG_LEVEL_INFO: {
level_str = "INFO";
break;
}
case LOG_LEVEL_WARNING: {
level_str = "WARNING";
break;
}
case LOG_LEVEL_ERROR : {
level_str = "ERROR";
break;
}
default: {
level_str = "UNKNOWN";
break;
}
}
fp = fopen(filename, "a");
if(fp == NULL) {
perror("Open file ERROR!");
return ;
}
if(fp != NULL) {
fprintf(fp, "%s [%s]: %s\n", ctime(&now), level_str, message);
fclose(fp);
}
return ;
}