Get the App
SLTechnology News&Howtos  ›  Servers  › 

Sample code for log output code template under linux c

Shulou Source: shulou.com Published: 2022-06-02 03:27:26 10月12日 Update

Preface

This article mainly introduces the relevant content of the log output code template under linux c, which is shared for your reference and study. I won't say much below, let's take a look at the detailed introduction.

Template

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

Log.c

/ * * log.c * * / # include # include "log.h" / / log file path # define filepath ". / ps_com_log.log" / / set 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 [1024]; / / Open the file fd = fopen (filepath, "a +") by appending; if (fd = = NULL) {return-1;} memset (s, 0Coje sizeof (s)); memset (tmp, 0Jing sizeof (tmp)) Sprintf (tmp, "* [pid=%d]: [", getpid ()); strcpy (s, tmp); memset (tmp, 0jewellery 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); / / [lock is required to support multithreading] pthread_mutex_unlock (& mutex_log); / / unlock. }

Log.h

# ifndef _ LOG_H__#define _ LOG_H__#include # include # include void LogWrite (char * logText,char * string); # endif / * _ LOG_H__ * /

Test file

Now that you have the log output feature, let's briefly test it:

# 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", "Hello World!"); LogWrite ("iout", "Hallo World!"); return 0;}

The above code is very simple and does not explain too much.

Running result:

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

Summary

The above is the whole content of this article, I hope that the content of this article has a certain reference and learning value for your study or work, if you have any questions, you can leave a message and exchange, thank you for your support.

Tags: File content learning support code template output log thread H.e.l.l.o reference test two value information preface function that is way time Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Tech Info macOS OPPO Reno Linux Microsoft