-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlog.c
94 lines (71 loc) · 2.41 KB
/
log.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
// 2013 - Ryan Leonard <[email protected]>
#include "log.h"
#include "util.h"
#include <stdio.h>
#include <time.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <fcntl.h>
int initLog(char *fileName, char *prefixMessage, struct Log *log){
int ret;
// Verify passed parameters
if (log == NULL || fileName == NULL || prefixMessage == NULL)
return NullParamErr;
///// Copy fileName to log->fileName
strncpy(log->fileName, fileName, MAX_STRLEN_FILENAME);
log->prefix[MAX_STRLEN_PREFIX-1] = '\0';
///// Copy prefixMessage to log->prefix
strncpy(log->prefix, prefixMessage, MAX_STRLEN_PREFIX);
log->prefix[MAX_STRLEN_PREFIX-1] = '\0';
///// Open log file, attribute it to log->fd
ret = open(fileName, O_RDWR | O_APPEND | O_CREAT,
S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
if (ret == -1)
return IOErr;
else
log->log_fd = ret;
return NoneErr;
}
int closeLog(struct Log *log){
int ret;
// Verify passed parameters
if (log == NULL)
return NullParamErr;
///// Close log file
ret = close(log->log_fd);
if (ret == -1)
return IOErr;
return 0;
}
int writeMessage(char *message, struct Log *log){
int ret;
time_t t;
struct tm tm;
char strTime[MAX_STRLEN_TIME];
char logMessage[MAX_STRLEN_LOGMESSAGE];
// Verify passed parameters
if (message == NULL || log == NULL)
return NullParamErr;
///// Get time
// Get the time that this message will be recorded to be logged at
t = time(NULL);
tm = *localtime(&t);
ret = snprintf(strTime, MAX_STRLEN_TIME, "%02d/%02d/%02d %02d:%02d:%02d ", tm.tm_year +
1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
strTime[MAX_STRLEN_TIME-1] = '\0';
if (ret < 0)
return CLibCallErr;
///// Compile the logMessage (time + prefix + ": " + message)
ret = snprintf(logMessage, MAX_STRLEN_LOGMESSAGE, "%s %s: %s\n", strTime,
log->prefix, message);
logMessage[MAX_STRLEN_LOGMESSAGE-2] = '\n'; // Assures that even in the worst case we still
logMessage[MAX_STRLEN_LOGMESSAGE-1] = '\0'; // are safe with string manipulation
if (ret < 0)
return CLibCallErr;
///// print the logMessage to file
ret = write(log->log_fd, logMessage, strlen(logMessage));
if (ret == -1)
return IOErr;
return NoneErr;
}