linux c下log输出代码模板

模板

模本分为两个文件:log.c和log.h.

log.c

/** log.c **/
#include <unistd.h>
#include "log.h"

// log文件路径
#define filepath "./ps_com_log.log"
 
//设定时间
static char * settime(char * time_s){
    time_t timer=time(NULL);
    strftime(time_s, 20, "%Y-%m-%d %H:%M:%S",localtime(&timer));
    return time_s;
}
 
/*
 *打印
 * */
static int PrintfLog(char * logText, char *  string){
    FILE * fd = NULL;
    char s[1024];
    char tmp[256];

    //使用追加方式打开文件
    fd = fopen(filepath,"a+");
    if(fd == NULL){
        return -1;
    }
    
    memset(s, 0, sizeof(s));
    memset(tmp, 0,sizeof(tmp));
    
    sprintf(tmp, "*****[pid=%d]:[", getpid());
    strcpy(s, tmp);
    
    memset(tmp, 0,sizeof(tmp));
    settime(tmp);
    strcat(s, tmp);

    strcat(s, "]*****");
    fprintf(fd, "%s", s);

    fprintf(fd, "*[%s]*****:\n",logText);   
    fprintf(fd, "%s\n",string); 
    fclose(fd);
}
 
 /*
  *日志写入
  * */
void LogWrite(char *logText,char *string)
{
    //[为支持多线程需要加锁] pthread_mutex_lock(&mutex_log); //lock. 
    //打印日志信息
    PrintfLog(logText, string);
                                                                        
    //[为支持多线程需要加锁] pthread_mutex_unlock(&mutex_log); //unlock. 
                                                            
}

log.h

#ifndef __LOG_H__
#define __LOG_H__
#include <stdio.h>
#include <string.h>
#include <time.h>
 

void LogWrite(char * logText,char *string);

#endif /* __LOG_H__ */

测试文件

既然有了log输出功能,下面就简单测试一下:

#include "stdio.h"
#include "log.h"
int main(int argv,char**argc){
    printf("test\n");
    LogWrite("INFO","Hello World!");
    LogWrite("error","H.e.l.l.o W.o.r.l.d!");
    LogWrite("mint","H e l l o W o r l d!");
    LogWrite("iout","Hallo World!");

    return 0;
}

以上代码很简单,不在过多解释。

运行结果:

*****[pid=15971]:[2018-12-05 14:24:21]******[INFO]*****:
Hello World!
*****[pid=15971]:[2018-12-05 14:24:21]******[error]*****:
H.e.l.l.o W.o.r.l.d!
*****[pid=15971]:[2018-12-05 14:24:21]******[mint]*****:
H e l l o W o r l d!
*****[pid=15971]:[2018-12-05 14:24:21]******[iout]*****:
Hallo World!
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,120评论 19 139
  • linux资料总章2.1 1.0写的不好抱歉 但是2.0已经改了很多 但是错误还是无法避免 以后资料会慢慢更新 大...
    数据革命阅读 14,374评论 2 33
  • 兰花终于开了,淡淡的香味,若有若无。不如茉莉浓香四溢。 它羞涩的样子惹人怜爱。花朵是黄色的,透着绿意。袅袅婷婷的,...
    曦华阅读 1,603评论 0 0
  • 不多不少,从感到不安在日记里絮叨,到你告诉我你要离开,整整一个月的光景。 ...
    我想遇见真实的自己阅读 1,666评论 0 0
  • 庞立鹏,2018年,06.23号,星期日,天气晴,立鹏写作业一点也不着急,下午了写作业,看会儿书写会儿作业,我说立...
    董月光阅读 818评论 0 0

友情链接更多精彩内容