寫入簡單的日誌log

log.c:

#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <time.h>
#include <unistd.h>

#include "
log.h" void logmessage(char *logheader, char *fmt, ...) { va_list args; char buf[1024]; va_start(args, fmt); vsnprintf(buf, sizeof(buf) - 1, fmt, args); openlog(logheader, 0, 0); syslog(0, buf); closelog(); va_end(args); return; } void logcurrent(const char *func, int line, char *fmt, ...) { va_list args; FILE *fp = NULL; char tmp[128]; char buf[1024]; char log_message[1024]; char *path; char *time_s; time_t t; time_s = tmp; t = time(NULL); time_s = ctime(&t); time_s[strlen(time_s) - 1] = ' '; // remove '\n' va_start(args, fmt); vsnprintf(log_message, sizeof(log_message) - 1, fmt, args); printf("log_message : %s\n", log_message); snprintf(buf, sizeof(buf) - 1, "%s %s[%d] %s", time_s, func, line, log_message); printf("buf : %s\n", buf); path = get_current_dir_name(); strcat(path, "/log.text"); fp = fopen(path, "a+"); if (fp == NULL) { perror("fopen"); return; } if (fwrite(buf, strlen(buf), 1, fp) == 0) { perror("fwrite"); return; } if (fp) { fclose(fp); } va_end(args); return; } int main(void) { tcp_log("%s", "1234567890z"); logcurrent(__func__, __LINE__, "abc\n"); }

 

log.h:

#ifndef __LOG_H__
#define __LOG_H__

#ifndef SYS_LOG
#define tcp_log(fmt, args...) logcurrent(__func__, __LINE__, fmt, ## args)
#else
#define tcp_log(fmt, args...) logmessage(log_header, fmt, ## args)
#endif
#endif

 

Makefile:

CC = gcc
TARGET = log-test
SOURCE = log.c

all: clean
    $(CC) $(SOURCE) -o $(TARGET)

clean:
    rm -rf $(TARGET)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章