aboutsummaryrefslogtreecommitdiff
path: root/src/logger33.c
blob: d9b0d8defbaf6b655758f84691e0cdb94841859d (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
104
105
106
107
108
109
110
111
#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 "options33.h"
#include "strings33.h"
#include "logger33.h"
#include "ui33.h"


typedef struct {
  Size fd;
} Logger;

Logger logger_t;


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

static char _uiColourPrefix[5][5] = {
  { UI33_CYAN, 'D', UI33_WHITE, ':', '\0' },
  { UI33_GREEN, 'I', UI33_WHITE, ':', '\0' },
  { UI33_YELLOW, 'W', UI33_WHITE, ':', '\0' },
  { UI33_ORANGE, 'E', UI33_WHITE, ':', '\0' },
  { UI33_RED, 'F', UI33_WHITE, ':', '\0' }
};


Size logger33_init( void )
{
  String logFile[ _STRING_MAX ];

  if( E33_LOG_FILE[0] == '~' ) {
    snprintf(logFile,  _STRING_MAX , "%s/%s", getenv("HOME"), E33_LOG_FILE+1);
  } else {
    snprintf(logFile,  _STRING_MAX , "%s", E33_LOG_FILE);
  }

  logger_t.fd = open(logFile,
    O_CREAT | O_TRUNC | O_WRONLY | O_NOCTTY | O_TTY_INIT,
    0644 );

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

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

  return E33_EXIT_SUCCESS;
}

void logger33_term( void )
{
  LOGI( "Goodbye!" );
  close( logger_t.fd );
}

void _logger( Size level, String file, int line , String func, const char *fmt, ... )
{
  char uiStringTemp[ _STRING_MAX ];
  char uiString[ _STRING_MAX ];

  time_t currentTime;
  struct tm *mTime;


  va_list args;
  va_start(args, fmt);


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


  dprintf( logger_t.fd, "Engine33 [%02d:%02d:%02d] [%s:%d @%s()] -",
    mTime->tm_hour, mTime->tm_min, mTime->tm_sec, file, line, func );

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

  if( (level > _INFO) && errno )
  {
    dprintf( logger_t.fd, " [%s]", strerror(errno) );
    errno = 0;
  }
  dprintf( logger_t.fd, "\r\n" );


  snprintf( uiStringTemp,  _STRING_MAX , "%s %s", _uiColourPrefix[level], fmt );
  vsnprintf( uiString,  _STRING_MAX , uiStringTemp, args );

  ui33_add_message( uiString );


  va_end(args);
}