Created
February 12, 2014 06:46
-
-
Save de1o/8951022 to your computer and use it in GitHub Desktop.
a simple log function in Clang, based on http://blog.linuxphp.org/archives/1474/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
//是Linux 系统的日期时间头文件。通常会包含include time.h | |
#include <sys/time.h> | |
// 是ISO C99 标准日期时间头文件。编写的代码平台无关的需要引入 | |
#include <time.h> | |
//让函式能够接收不定量参数,va_list需要 | |
#include <stdarg.h> | |
#define DEBUG 1 | |
#define LOGFILE "write.log" | |
//编写的代码平台无关的 | |
#define __need_time_t | |
#define __need_timespec | |
#define LOG_ERROR 0 | |
#define LOG_WARNING 1 | |
#define LOG_DEBUG 2 | |
//fmt为格式化字串,如%d%s%c%f | |
static void WriteLog(int level, const char *fmt, ...) | |
{ | |
va_list ap; | |
FILE *fp; | |
//char *c = "-*+", | |
char buf[64]; | |
char *c[] = {"ERROR", "WARNING", "DEBUG"}; | |
time_t now; | |
int cnt; | |
#ifdef DEBUG | |
fp = stdout; | |
#else | |
fp = fopen(LOGFILE, "a+"); | |
if (!fp) return; | |
#endif | |
va_start(ap, fmt); | |
//1970年1月1日00:00:00(称为UNIX系统的Epoch时间)到当前时刻的秒数 | |
now = time(NULL); | |
//gmtime 把日期和时间转换为格林威治(GMT)时间的函数,结果由结构tm返回 | |
//strftime将tm结构体时间格式化,%d 十进制表示的每月的第几天%b 月分的简写 | |
strftime(buf, 64, "[%d %b %H:%M:%S]", gmtime(&now)); | |
//格式化输出到一个流/文件中 | |
fprintf(fp, "%s %s ", buf, c[level]); | |
//格式化输出到一个流/文件中 | |
cnt = vfprintf(fp, fmt, ap); | |
//fprintf(fp, " write %d bite",cnt); | |
fprintf(fp, "\n"); | |
//清除文件缓冲区,文件以写方式打开时将缓冲区内容写入文件 | |
//fflush(stdout)刷新标准输出缓冲区,把输出缓冲区里的东西打印到标准输出设备上 | |
fflush(fp); | |
va_end(ap); | |
#ifndef DEBUG | |
fclose(fp); | |
#endif | |
} | |
int main(int argc, char *argv[]) | |
{ | |
WriteLog(LOG_ERROR, "%s %s ","this is a test", "hello world"); | |
WriteLog(LOG_WARNING, "%s %s ", "this is a test2", "hello world"); | |
WriteLog(LOG_DEBUG, "%s %s ", "this is a test3", "hello world"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment