aboutsummaryrefslogtreecommitdiff
path: root/src/logger.c
blob: c90f364e32cd3f51ae4172396ca3be233a6e30be (plain)
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
95
96
97
98
99
100
101
102
103
#include <linux/vt.h>

#include "fcntl.h"
#include "stdarg.h"
#include "errno.h"
#include "time.h"
#include "unistd.h"
#include "stdio.h"
#include "string.h"

#include "logger.h"
#include "options.h"
#include "ui33.h"

Logger __logger;


static char *ansiColourPrefix[5] = {
  "[\x1b[36mD\x1b[37m]",
  "[\x1b[32mI\x1b[37m]",
  "[\x1b[35mW\x1b[37m]",
  "[\x1b[33mE\x1b[37m]",
  "[\x1b[31mFl\x1b[37m]",
};

static char uiColourPrefix[5][11] = {
  { 6, '[', 'D', 'e', 'b', 'u', 'g', ']', ' ', 1, '\0' },
  { 3, '[', 'I', 'n', 'f', 'o', ']', ' ', 1, '\0', ' ' },
  { 5, '[', 'W', 'a', 'r', 'n', ']', ' ', 1, '\0', ' ' },
  { 8, '[', 'E', 'r', 'r', 'o', 'r', ']', ' ', 1, '\0' },
  { 2, '[', 'F', 'a', 't', 'a', 'l', ']', ' ', 1, '\0' }
};

Size logger_init( void )
{
  String logfile[512];

  if( LOG_PATH[0] == '~' ) {
    snprintf(logfile, 512, "%s/%s", getenv("HOME"), LOG_PATH+1);
  } else {
    snprintf(logfile, 512, "%s", LOG_PATH);
  }

  __logger.fd = open(logfile,
    O_CREAT | O_TRUNC | O_WRONLY | O_NOCTTY | O_TTY_INIT,
    0644 );

  if( __logger.fd < 0 ) {
    printf( "Unable to initialize logger. Exiting." );
    return E33_EXIT_FAILURE;
  }

  __logger.func = 0;

  ui_add_message( "Welcome to Engine33" );
  dprintf( __logger.fd, "\033[3J\033[1;1HWelcome to Engine33!\r\n\r\n" );

  return E33_EXIT_SUCCESS;
}

void logger_term( void )
{
  logi( "Goodbye!" );
  close( __logger.fd );
}

void logger( Size level, const char *fmt, ... )
{
  static char uiString[256];

  time_t currentTime;
  struct tm *m_time;


  va_list args;
  va_start(args, fmt);

  time(&currentTime);
  m_time = localtime(&currentTime);

  snprintf( uiString, 256, "%s%s", uiColourPrefix[level], fmt );

  dprintf( __logger.fd, "Engine33 [%02d:%02d:%02d] -",
    m_time->tm_hour, m_time->tm_min, m_time->tm_sec );

  dprintf( __logger.fd, " %s ", ansiColourPrefix[level] );
  vdprintf(__logger.fd, fmt, args);

  if( (level > LOG_INFO) && errno )
  {
    String strerr = strerror(errno);
    dprintf( __logger.fd, ". Reason: %s", strerr );
    snprintf( uiString, 256, "%s >> %s", uiString, strerr );
    errno = 0;
  }

  dprintf( __logger.fd, ".\r\n" );

  ui_add_message( uiString, args );

  va_end(args);
}