aboutsummaryrefslogtreecommitdiff
path: root/src/logger.c
blob: 860311bf861739f94e5c4189e798ac5988959ada (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
#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"

Logger __logger;


static char *colours[5] = {
  "[\x1b[36mDebug\x1b[37m]",
  "[\x1b[32mInfo\x1b[37m]",
  "[\x1b[35mWarn\x1b[37m]",
  "[\x1b[33mError\x1b[37m]",
  "[\x1b[31mFatal\x1b[37m]",
};

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;

  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, ... )
{
  time_t currentTime;
  struct tm *m_time;


  va_list args;
  va_start(args, fmt);

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

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

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

  if( (level > LOG_INFO) && errno ) {
    dprintf( __logger.fd, ". Reason: %s", strerror(errno) );
    errno = 0;
  }
  
  dprintf( __logger.fd, ".\r\n" );

  va_end(args);
}