Project

General

Profile

Statistics
| Revision:

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

History | View | Annotate | Download (2.15 KB)

1 11 emarinel
/**
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
14
Log::Log(char * filename)
15
{
16
17
  printf("Creating log object\n");
18
19
  if (!filename)
20
    {
21
      fprintf(stderr, "Provided a null filename when trying to create a log.\n");
22
      return;
23
    }
24
25
  logFile = fopen(filename, "a"); //open file for appending
26
  if (!logFile)
27
    {
28
      fprintf(stderr, "Error opening %s as log file.\n", filename);
29
      return;
30
    }
31
32
  printf("About to log start message.\n");
33
  logMessage(LOG_TYPE_START_LOG, "Starting server");
34
}
35
36
Log::~Log()
37
{
38
  if (!logFile)
39
    fclose(logFile);
40
}
41
42
struct tm Log::getCurrentTime()
43
{
44
  struct tm currTime;
45
  memset(&currTime, 0, sizeof(struct tm));
46
47
  time_t t = time(NULL);
48
  localtime_r(&t, &currTime);
49
50
  return currTime;
51
}
52
53
int Log::logMessage(int type, char * message)
54
{
55
  if (!logFile)
56
    {
57
      fprintf(stderr, "Tried to log a message but the file pointer was null.\n");
58
      return -1;
59
    }
60
  if (!message)
61
    {
62
      fprintf(stderr, "Tried to log a null message.\n");
63
      return -1;
64
    }
65
66
  static char * start_log = "Starting Log";
67
  static char * connect = "Client Connecting";
68
  static char * disconnect = "Client Disconnecting";
69
  static char * error = "Error";
70
  static char * logGenMessage = "Generic Message";
71
72
  char * messageType;
73
74
  switch(type)
75
    {
76
    case LOG_TYPE_START_LOG:
77
      messageType = start_log;
78
      break;
79
    case LOG_TYPE_CONNECT:
80
      messageType = connect;
81
      break;
82
    case LOG_TYPE_DISCONNECT:
83
      messageType = disconnect;
84
      break;
85
    case LOG_TYPE_ERROR:
86
      messageType = error;
87
      break;
88
    case LOG_TYPE_MESSAGE:
89
      messageType = logGenMessage;
90
      break;
91
    default:
92
      fprintf(stderr, "Tried to log a message with an invalid type.\n");
93
      return -1;
94
    }
95
96
  struct tm currTime = getCurrentTime();
97
98
  char buffer[LOG_MAX_TIME_LENGTH];
99
  asctime_r(&currTime, buffer);
100
  int len = strlen(buffer);
101
  buffer[len-1] = '\0'; //remove the newline that is put at the end by asctime_r
102
  fprintf(logFile, "%s %*s   %s\n", buffer, LOG_MAX_TYPE_LENGTH, messageType, message);
103
  fflush(logFile);
104
105
106
  return 0;
107
}