写入简单的日志log
Posted coolyuan
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了写入简单的日志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 ‘ ‘ va_start(args, fmt); vsnprintf(log_message, sizeof(log_message) - 1, fmt, args); printf("log_message : %s ", log_message); snprintf(buf, sizeof(buf) - 1, "%s %s[%d] %s", time_s, func, line, log_message); printf("buf : %s ", 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 "); }
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)
以上是关于写入简单的日志log的主要内容,如果未能解决你的问题,请参考以下文章