gcontini
2020-03-14 35087e2c3f200639cf32c96e81cdbb08a5acb8eb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include "logger.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <time.h>
 
#ifndef LOG_DISABLED
 
#ifdef __unix__
#include <unistd.h>
#define MAX_PATH 255
#else
#include <windows.h>
#endif
 
static FILE *logFile = NULL;
 
static void timenow(char * buffer) {
    time_t rawtime;
    struct tm *timeinfo;
 
    time(&rawtime);
    timeinfo = localtime(&rawtime);
 
    strftime(buffer, 64, "%Y-%m-%d %H:%M:%S", timeinfo);
}
 
static void getLogFname(char* logpath) {
#ifdef __unix__
    const char *folder = getenv("TMPDIR");
    if (folder == 0) {
        folder = "/tmp";
    }
    strncpy(logpath, folder, MAX_PATH);
    strncat(logpath, "/open-license.log", MAX_PATH - strlen(logpath));
#else
    const int plen = GetTempPath(MAX_PATH, logpath);
    if(plen == 0) {
        fprintf(stderr, "Error getting temporary directory path");
    }
    strncat(logpath, "open-license.log", MAX_PATH - strlen(logpath));
#endif
}
 
void _log(const char* format, ...) {
    va_list args;
    char * buffer;
    if (logFile == NULL) {
        char logpath[MAX_PATH];
        getLogFname(logpath);
        logFile = fopen(logpath, "a");
        if (logFile == NULL) {
            //what shall we do here?
            return;
        }
    }
    buffer = (char *) malloc(sizeof(char) * strlen(format) + 64);
    timenow(buffer);
    sprintf(&buffer[strlen(buffer) - 1], "-[%d]-", getpid());
    strcat(buffer, format);
    va_start(args, format);
    vfprintf(logFile, buffer, args);
    va_end(args);
    free(buffer);
}
 
void _shutdown_log() {
    if (logFile != NULL) {
        fclose(logFile);
        logFile = NULL;
    }
}
#endif