linux c下log輸出代碼模板示例代碼
前言
本文主要介紹了關(guān)于linux c下log輸出代碼模板的相關(guān)內(nèi)容,分享出來(lái)供大家參考學(xué)習(xí),下面話不多說(shuō)了,來(lái)一起看看詳細(xì)的介紹吧
模板
模本分為兩個(gè)文件:log.c和log.h.
log.c
/** log.c **/ #include <unistd.h> #include "log.h" // log文件路徑 #define filepath "./ps_com_log.log" //設(shè)定時(shí)間 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]; //使用追加方式打開(kāi)文件 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); } /* *日志寫(xiě)入 * */ 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__ */
測(cè)試文件
既然有了log輸出功能,下面就簡(jiǎn)單測(cè)試一下:
#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; }
以上代碼很簡(jiǎn)單,不在過(guò)多解釋。
運(yùn)行結(jié)果:
*****[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!
總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,如果有疑問(wèn)大家可以留言交流,謝謝大家對(duì)腳本之家的支持。
相關(guān)文章
.htaccess rewrite 規(guī)則詳細(xì)說(shuō)明
用Apache虛擬主機(jī)的朋友很多,apache提供的.htaccess模塊可以為每個(gè)虛擬主機(jī)設(shè)定rewrite規(guī)則,這對(duì)網(wǎng)站SEO優(yōu)化相當(dāng)有用,同時(shí)也改善了用戶體驗(yàn)2016-04-04ubuntu系統(tǒng)下matplotlib中文亂碼問(wèn)題的解決方法
本篇文章主要介紹了ubuntu系統(tǒng)下matplotlib中文亂碼問(wèn)題的解決方法,具有一定的參考價(jià)值,有興趣的可以了解一下2017-06-06Linux日志中查找關(guān)鍵字及其前后的信息實(shí)例方法
在本篇文章里小編給大家整理的是關(guān)于Linux日志中查找關(guān)鍵字及其前后的信息實(shí)例方法,需要的朋友們可以學(xué)習(xí)下。2019-10-10linux下如何創(chuàng)建守護(hù)進(jìn)程的步驟
本篇文章主要介紹了linux下如何創(chuàng)建守護(hù)進(jìn)程的步驟,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-07-07