forked from ronkashi/SP-project
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SPLogger.c
51 lines (46 loc) · 1.34 KB
/
SPLogger.c
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
#include "SPLogger.h"
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
//File open mode
#define SP_LOGGER_OPEN_MODE "w"
// Global variable holding the logger
SPLogger logger = NULL;
struct sp_logger_t {
FILE* outputChannel; //The logger file
bool isStdOut; //Indicates if the logger is stdout
SP_LOGGER_LEVEL level; //Indicates the level
};
SP_LOGGER_MSG spLoggerCreate(const char* filename, SP_LOGGER_LEVEL level) {
if (logger != NULL) { //Already defined
return SP_LOGGER_DEFINED;
}
logger = (SPLogger) malloc(sizeof(*logger));
if (logger == NULL) { //Allocation failure
return SP_LOGGER_OUT_OF_MEMORY;
}
logger->level = level; //Set the level of the logger
if (filename == NULL) { //In case the filename is not set use stdout
logger->outputChannel = stdout;
logger->isStdOut = true;
} else { //Otherwise open the file in write mode
logger->outputChannel = fopen(filename, SP_LOGGER_OPEN_MODE);
if (logger->outputChannel == NULL) { //Open failed
free(logger);
logger = NULL;
return SP_LOGGER_CANNOT_OPEN_FILE;
}
logger->isStdOut = false;
}
return SP_LOGGER_SUCCESS;
}
void spLoggerDestroy() {
if (!logger) {
return;
}
if (!logger->isStdOut) {//Close file only if not stdout
fclose(logger->outputChannel);
}
free(logger);//free allocation
logger = NULL;
}