在 Linux 中,使用 fprintf
函数可以将日志信息输出到文件或标准输出(例如控制台)
typedef enum {
LOG_LEVEL_DEBUG,
LOG_LEVEL_INFO,
LOG_LEVEL_WARNING,
LOG_LEVEL_ERROR,
LOG_LEVEL_FATAL
} LogLevel;
LogLevel current_log_level = LOG_LEVEL_DEBUG;
void set_log_level(LogLevel level) {
current_log_level = level;
}
#include <stdarg.h>
#include<stdio.h>
#include <time.h>
void log_message(LogLevel level, const char *format, ...) {
if (level< current_log_level) {
return;
}
const char *level_str[] = {"DEBUG", "INFO", "WARNING", "ERROR", "FATAL"};
time_t now;
struct tm *timeinfo;
char buffer[80];
time(&now);
timeinfo = localtime(&now);
strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", timeinfo);
printf("[%s] [%s] ", buffer, level_str[level]);
va_list args;
va_start(args, format);
vprintf(format, args);
va_end(args);
printf("\n");
}
log_message
函数输出不同级别的日志:int main() {
log_message(LOG_LEVEL_DEBUG, "This is a debug message.");
log_message(LOG_LEVEL_INFO, "This is an info message.");
log_message(LOG_LEVEL_WARNING, "This is a warning message.");
log_message(LOG_LEVEL_ERROR, "This is an error message.");
log_message(LOG_LEVEL_FATAL, "This is a fatal message.");
return 0;
}
通过这种方法,你可以根据需要调整日志级别,从而控制输出的日志信息。