conworlds

view src/logger.cc @ 17:c814f77d177e

moved to SDL2
author John Tsiombikas <nuclear@member.fsf.org>
date Mon, 25 Aug 2014 22:02:08 +0300
parents
children
line source
1 #include <stdio.h>
2 #include <stdarg.h>
3 #include "logger.h"
5 #if defined(unix) || defined(__unix__) || defined(__APPLE__)
6 #include <unistd.h>
7 #elif defined(WIN32)
8 #include <windows.h>
9 #endif
11 enum { LOG_INFO, LOG_WARNING, LOG_ERROR, LOG_FATAL, LOG_DEBUG };
13 static int typecolor(int type);
15 static FILE *fp = stdout;
17 static void logmsg(int type, const char *fmt, va_list ap)
18 {
19 #if defined(unix) || defined(__unix__) || (defined(__APPLE__) && !defined(TARGET_IPHONE))
20 if(isatty(fileno(fp)) && type != LOG_INFO) {
21 int c = typecolor(type);
22 fprintf(fp, "\033[%dm", c);
23 vfprintf(fp, fmt, ap);
24 fprintf(fp, "\033[0m");
25 } else
26 #endif
27 {
28 vfprintf(fp, fmt, ap);
29 }
30 if(type == LOG_ERROR || type == LOG_FATAL || type == LOG_DEBUG) {
31 fflush(fp);
32 }
34 #ifdef WIN32
35 if(type == LOG_FATAL) {
36 static char msgbuf[1024];
37 vsnprintf(msgbuf, sizeof msgbuf - 1, fmt, ap);
38 msgbuf[sizeof msgbuf - 1] = 0;
39 MessageBox(0, msgbuf, "Fatal error", MB_OK | MB_ICONSTOP);
40 }
41 #endif
42 }
44 void info_log(const char *fmt, ...)
45 {
46 va_list ap;
48 va_start(ap, fmt);
49 logmsg(LOG_INFO, fmt, ap);
50 va_end(ap);
51 }
53 void warning_log(const char *fmt, ...)
54 {
55 va_list ap;
57 va_start(ap, fmt);
58 logmsg(LOG_WARNING, fmt, ap);
59 va_end(ap);
60 }
62 void error_log(const char *fmt, ...)
63 {
64 va_list ap;
66 va_start(ap, fmt);
67 logmsg(LOG_ERROR, fmt, ap);
68 va_end(ap);
69 }
71 void fatal_log(const char *fmt, ...)
72 {
73 va_list ap;
75 va_start(ap, fmt);
76 logmsg(LOG_FATAL, fmt, ap);
77 va_end(ap);
78 }
80 void debug_log(const char *fmt, ...)
81 {
82 va_list ap;
84 va_start(ap, fmt);
85 logmsg(LOG_DEBUG, fmt, ap);
86 va_end(ap);
87 }
89 enum {
90 BLACK = 0,
91 RED,
92 GREEN,
93 YELLOW,
94 BLUE,
95 MAGENTA,
96 CYAN,
97 WHITE
98 };
100 #define ANSI_FGCOLOR(x) (30 + (x))
101 #define ANSI_BGCOLOR(x) (40 + (x))
103 static int typecolor(int type)
104 {
105 switch(type) {
106 case LOG_ERROR:
107 return ANSI_FGCOLOR(RED);
108 case LOG_FATAL:
109 return ANSI_FGCOLOR(RED); // TODO differentiate from LOG_ERROR
110 case LOG_WARNING:
111 return ANSI_FGCOLOR(YELLOW);
112 case LOG_DEBUG:
113 return ANSI_FGCOLOR(MAGENTA);
114 default:
115 break;
116 }
117 return 37;
118 }