linux c log output code template sample code

  • 2020-12-18 02:03:41
  • OfStack

preface

This article mainly introduces the linux c log output code template related content, sharing for your reference and learning, the following words do not say much, let's have a look at the detailed introduction

The template

The template is divided into two files: ES11en.c and ES13en.h.

log.c


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

// log The file path 
#define filepath "./ps_com_log.log"
 
// Set a time 
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;
}
 
/*
 * print 
 * */
static int PrintfLog(char * logText, char * string){
 FILE * fd = NULL;
 char s[1024];
 char tmp[256];

 // Open the file using append mode 
 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);
}
 
 /*
 * Log write 
 * */
void LogWrite(char *logText,char *string)
{
 //[ Locking is required to support multithreading ] pthread_mutex_lock(&mutex_log); //lock. 
 // Print log information 
 PrintfLog(logText, string);
                  
 //[ Locking is required to support multithreading ] 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__ */

The test file

Now that you have the log output, here's a simple test:


#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;
}

The above code is very simple, not too much explanation.

Operation results:

[

*****[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!

]

conclusion


Related articles: