[学习分享] DEBUG_LOG output

weixin_38063296 2016-01-04 08:27:58

#include <stdio.h>
#include <stdarg.h>
#include <sys/stat.h>
#include <time.h>
#include <stdlib.h>
#define LOG_SWITCH "/tmp/log_file"
#define LOG_FILE_SIZE 1024 * 1024
void print_log(const char * fmt , ... )
{
    va_list args;
    time_t sec;
    struct tm * ltm;
    FILE *lfp;
    struct stat ST;
    if( stat(LOG_SWITCH,&ST) == 0 )
    {
        if(ST.st_size > LOG_FILE_SIZE)
        {
           lfp = fopen(LOG_SWITCH, "w");   
        }
        else
        {
            lfp = fopen(LOG_SWITCH, "a");
        }
    }
    else
    {
        return;
    }
    sec = time(NULL);
    ltm = localtime(&sec);
    fprintf(lfp,"%04d-%02d-%02d/%02d:%02d:%02d ",ltm->tm_year+1900,ltm->tm_mon+1,ltm->tm_mday,\
                            ltm->tm_hour,ltm->tm_min,ltm->tm_sec);
    va_start(args,fmt);
    vfprintf(lfp,fmt,args);
    va_end(args);
    fclose(lfp);
}
//description
//judge whether the LOG_SWITCH is exist or not,if exist ,output the debug info to the LOG_SWITCH  . else output nothing
//one of the examples
int main(void)
{
    print_log("[rayklaus][%s:%s:%d]\n",__FILE__,__FUNCTION__,__LINE__);
    print_log("[rayklaus][%s:%s:%d]\n",__FILE__,__FUNCTION__,__LINE__);
    print_log("[rayklaus][%s:%s:%d]\n",__FILE__,__FUNCTION__,__LINE__);
    print_log("[rayklaus][%s:%s:%d]\n",__FILE__,__FUNCTION__,__LINE__);
    return 0;
}
...全文
46 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

476

社区成员

发帖
与我相关
我的任务
社区描述
其他技术讨论专区
其他 技术论坛(原bbs)
社区管理员
  • 其他技术讨论专区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧