Linux共享库 日志方法

mylog.h

#ifdef __cplusplus
extern "C"
{
#endif

//写日志函数
//path:日志文件名
//msg:日志信息
int writelog(const char *path, const char * msg);

#ifdef __cplusplus

}

#endif

mylog.c

//日志共享库
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <time.h>

//获取当前时间字符串
int Gettimestr(char * buf)
{
    time_t tData = 0;
    //获取当前系统时间
    time(&tData);
    //定义时间结构体变量
    struct tm * eventTime = NULL;
    //将time_t类型转化成时间结构体类型
    eventTime = localtime(&tData);
    //tm_year表示年份,以1900为标准,1900的值是0,1901的值是1
    int iyear = eventTime->tm_year + 1900;
    //tm_mon表示月份,从0开始到11结束,按照通常习惯应该从1月份开始
    int imon = eventTime->tm_mon + 1;
    //tm_wday:表示一个星期的第几天 从1开始7结束
    //tm_yday:表示一年的第几天
    //tm_mday:表示正常的月天数
    int iday = eventTime->tm_mday;
    //时分秒
    int ihour = eventTime->tm_hour;
    int imin = eventTime->tm_min;
    int isec = eventTime->tm_sec;
    //拼接时间
    char timestr[30] = { 0 };
    sprintf(timestr, "%04d-%02d-%02d %02d:%02d:%02d", iyear, imon, iday, ihour,
            imin, isec);
    strcpy(buf, timestr);
    return 0;
}

//写日志
int writelog(const char *path, const char * msg)
{
    if (path == NULL || msg == NULL)
    {
        printf("writelog() 传入参数不可以为空!
");
        return -1;
    }
    //open the file stream
    FILE * pfa = NULL;
    pfa = fopen(path, "a");
    if (pfa == NULL)
    {
        printf("open the file failed ! error message : %s
", strerror(errno));
        return -1;
    }
    char strtime[30] = { 0 };
    Gettimestr(strtime);
    char resultmsg[1024] = { 0 };
    sprintf(resultmsg, "%s 
 	 %s
", strtime, msg);
    fputs(resultmsg, pfa);
    fclose(pfa);
    pfa = NULL;
    return 0;
}

makefile

.SUFFIXES:.c .o
CC=gcc
SRCS=mylog.c
OBJS=$(SRCS:.c=.o)
EXEC=libmylog.so

start:$(OBJS)
    $(CC) -shared -o $(EXEC) $(OBJS)
    @echo "^_^-----OK------^_^"
.c.o:
    $(CC) -Wall -g -fPIC -o $@ -c $<
clean:
    rm -f $(OBJS)
    rm -f $(EXEC)
原文地址:https://www.cnblogs.com/zhanggaofeng/p/5851498.html