Add environment variable to control log header
[mono-project.git] / mono / utils / mono-log-common.c
blob90118efbc2525f6dc4ef29f8af85579ae650c144
1 /*
2 * mono-log-common.c: Platform-independent interface to the logger
4 * This module contains the POSIX syslog logger interface
6 * Author:
7 * Neale Ferguson <neale@sinenomine.net>
9 */
10 #include <config.h>
12 #ifdef HAVE_UNISTD_H
13 #include <unistd.h>
14 #endif
16 #include <stdlib.h>
17 #include <stdio.h>
18 #include <ctype.h>
19 #include <string.h>
20 #include <glib.h>
21 #include <errno.h>
22 #include <time.h>
23 #include <sys/time.h>
24 #include "mono-logger.h"
26 static FILE *logFile = NULL;
27 static void *logUserData = NULL;
29 /**
30 * mapSyslogLevel:
32 * @level - GLogLevelFlags value
33 * @returns The equivalent character identifier
35 static __inline__ char
36 mapLogFileLevel(GLogLevelFlags level)
38 if (level & G_LOG_LEVEL_ERROR)
39 return ('E');
40 if (level & G_LOG_LEVEL_CRITICAL)
41 return ('C');
42 if (level & G_LOG_LEVEL_WARNING)
43 return ('W');
44 if (level & G_LOG_LEVEL_MESSAGE)
45 return ('N');
46 if (level & G_LOG_LEVEL_INFO)
47 return ('I');
48 if (level & G_LOG_LEVEL_DEBUG)
49 return ('D');
50 return ('I');
53 /**
54 * mono_log_open_logfile
56 * Open the logfile. If the path is not specified default to stdout. If the
57 * open fails issue a warning and use stdout as the log file destination.
59 * @path - Path for log file
60 * @userData - Not used
62 void
63 mono_log_open_logfile(const char *path, void *userData)
65 if (path == NULL) {
66 logFile = stdout;
67 } else {
68 logFile = fopen(path, "w");
69 if (logFile == NULL) {
70 g_warning("opening of log file %s failed with %s - defaulting to stdout",
71 path, strerror(errno));
74 logUserData = userData;
77 /**
78 * mono_log_write_logfile
80 * Write data to the log file.
82 * @domain - Identifier string
83 * @level - Logging level flags
84 * @format - Printf format string
85 * @vargs - Variable argument list
87 void
88 mono_log_write_logfile(const char *domain, GLogLevelFlags level, mono_bool hdr, const char *format, va_list args)
90 time_t t;
91 struct tm tod;
92 char logTime[80],
93 logMessage[512];
94 pid_t pid;
95 int iLog = 0;
96 size_t nLog;
98 if (logFile == NULL)
99 logFile = stdout;
101 if (hdr) {
102 time(&t);
103 localtime_r(&t, &tod);
104 pid = getpid();
105 strftime(logTime, sizeof(logTime), "%F %T", &tod);
106 iLog = snprintf(logMessage, sizeof(logMessage), "%s level[%c] mono[%d]: ",
107 logTime,mapLogFileLevel(level),pid);
109 nLog = sizeof(logMessage) - iLog - 2;
110 iLog = vsnprintf(logMessage+iLog, nLog, format, args);
111 logMessage[iLog++] = '\n';
112 logMessage[iLog++] = '\0';
113 fputs(logMessage, logFile);
114 fflush(logFile);
116 if (level == G_LOG_FLAG_FATAL)
117 abort();
121 * mono_log_close_logfile
123 * Close the log file
125 void
126 mono_log_close_logfile()
128 if (logFile) {
129 if (logFile != stdout)
130 fclose(logFile);
131 logFile = NULL;