Project

General

Profile

Statistics
| Revision:

root / trunk / code / projects / colonet / ColonetServer / Logging.cpp @ 34

History | View | Annotate | Download (2.06 KB)

1
/**
2
 *
3
 *  @author Jason Knichel
4
 *
5
 */
6

    
7
#include <time.h>
8
#include <string.h>
9
#include <stdio.h>
10

    
11
#include "includes/Logging.h"
12

    
13
Log::Log(char * filename) {
14
  printf("Creating log object\n");
15

    
16
  if (!filename) {
17
    fprintf(stderr, "Provided a null filename when trying to create a log.\n");
18
    return;
19
  }
20

    
21
  logFile = fopen(filename, "a"); //open file for appending
22
  if (!logFile) {
23
    fprintf(stderr, "Error opening %s as log file.\n", filename);
24
    return;
25
  }
26

    
27
  printf("About to log start message.\n");
28
  logMessage(LOG_TYPE_START_LOG, "Starting server");
29
}
30

    
31
Log::~Log()
32
{
33
  if (!logFile)
34
    fclose(logFile);
35
}
36

    
37
struct tm Log::getCurrentTime()
38
{
39
  struct tm currTime;
40
  memset(&currTime, 0, sizeof(struct tm));
41
  
42
  time_t t = time(NULL);
43
  localtime_r(&t, &currTime);
44
  
45
  return currTime;  
46
}
47

    
48
int Log::logMessage(int type, char * message)
49
{
50
  if (!logFile) {
51
    fprintf(stderr, "Tried to log a message but the file pointer was null.\n");
52
    return -1;
53
  }
54

    
55
  if (!message) {
56
    fprintf(stderr, "Tried to log a null message.\n");
57
    return -1;
58
  }
59
  
60
  static char * start_log = "Starting Log";
61
  static char * connect = "Client Connecting";
62
  static char * disconnect = "Client Disconnecting";
63
  static char * error = "Error";
64
  static char * logGenMessage = "Generic Message";
65

    
66
  char * messageType;
67

    
68
  switch(type) {
69
  case LOG_TYPE_START_LOG:
70
    messageType = start_log;
71
    break;
72
  case LOG_TYPE_CONNECT:
73
    messageType = connect;
74
    break;
75
  case LOG_TYPE_DISCONNECT:
76
    messageType = disconnect;
77
    break;
78
  case LOG_TYPE_ERROR:
79
    messageType = error;
80
    break;
81
  case LOG_TYPE_MESSAGE:
82
    messageType = logGenMessage;
83
    break;
84
  default:
85
    fprintf(stderr, "Tried to log a message with an invalid type.\n");
86
    return -1;
87
  }
88

    
89
  struct tm currTime = getCurrentTime();
90
  
91
  char buffer[LOG_MAX_TIME_LENGTH];
92
  asctime_r(&currTime, buffer);
93
  int len = strlen(buffer);
94
  buffer[len-1] = '\0'; //remove the newline that is put at the end by asctime_r
95
  fprintf(logFile, "%s %*s   %s\n", buffer, LOG_MAX_TYPE_LENGTH, messageType, message);
96
  fflush(logFile);
97

    
98
  return 0;
99
}