linux c下log輸出代碼模板示例代碼
前言
本文主要介紹了關(guān)于linux c下log輸出代碼模板的相關(guān)內(nèi)容,分享出來供大家參考學(xué)習(xí),下面話不多說了,來一起看看詳細(xì)的介紹吧
模板
模本分為兩個文件:log.c和log.h.
log.c
/** log.c **/
#include <unistd.h>
#include "log.h"
// log文件路徑
#define filepath "./ps_com_log.log"
//設(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];
//使用追加方式打開文件
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;
}
以上代碼很簡單,不在過多解釋。
運(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é)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。
相關(guān)文章
Linux下雙網(wǎng)卡Firewalld的配置流程(推薦)
firewalld提供了一個 動態(tài)管理的防火墻,用以支持不同網(wǎng)絡(luò)區(qū)域的規(guī)則,分配對一個網(wǎng)絡(luò)及其相關(guān)鏈接和界面一定程度的信任。這篇文章給大家介紹了Linux下雙網(wǎng)卡Firewalld的配置流程,需要的朋友參考下吧2018-04-04
Linux下如何檢查網(wǎng)卡bonding狀態(tài)和切換主備網(wǎng)卡
這篇文章主要介紹了Linux下如何檢查網(wǎng)卡bonding狀態(tài)和切換主備網(wǎng)卡問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-11-11
Linux 系統(tǒng)雙網(wǎng)卡綁定配置實(shí)現(xiàn)
這篇文章主要介紹了Linux 系統(tǒng)雙網(wǎng)卡綁定配置實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-06-06
linux操作系統(tǒng)下配置ssh/sftp和權(quán)限設(shè)置方法
這篇文章主要介紹了linux操作系統(tǒng)下配置ssh/sftp和權(quán)限設(shè)置方法 ,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2018-11-11

