#ifndef LOGGER_H
#define LOGGER_H
void logger(const char* tag, const char* message);
#endif /* LOG_H */
文件 logger.c
#include "logger.h"
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void logger(const char* tag, const char* message) {
time_t now;
time(&now);
printf("%s [%s]: %s\n", ctime(&now), tag, message);
}
它可能并不完美,但它确实满足了你所提出的需求。
fprintf
д»ЈжӣҝдёҠйқўзҡ„printf
пјҒ - N.R.S.Sowrabh我建议使用我自己编写的日志库 --- zlog!
在zlog中满足您需求的方法是:
$ vi /etc/zlog.conf
[formats]
simple = "%D %c %m%n"
# don't know what the tag mean in your question, so put category of zlog instead
# log level is also available here, add %V means level
[rules]
my_cat.* "xxx.log"; simple
$ vi hello.c
#include <stdio.h>
#include "zlog.h"
int main(int argc, char** argv)
{
int rc;
zlog_category_t *c;
rc = dzlog_init("/etc/zlog.conf", "my_cat");
if (rc) {
printf("init failed\n");
return -1;
}
zlog_info(c, "hello, zlog");
zlog_fini();
return 0;
}
它将在当前目录下生成 xxx.log
2012-09-30 07:22:50 my_cat hello, zlog
链接:
下载: https://github.com/HardySimpson/zlog/archive/latest-stable.tar.gz
用户指南: http://hardysimpson.github.com/zlog/UsersGuide-EN.html
Here is mine:
log.h
------
#ifndef LOG_H
#define LOG_H
void log_error(const char* message, ...); void log_info(const char* message, ...); void log_debug(const char* message, ...);
#endif
log.c
------
#include "log.h"
void log_format(const char* tag, const char* message, va_list args) { time_t now; time(&now); char * date =ctime(&now); date[strlen(date) - 1] = '\0'; printf("%s [%s] ", date, tag); vprintf(message, args); printf("\n"); }
void log_error(const char* message, ...) { va_list args; va_start(args, message); log_format("error", message, args); va_end(args); }
void log_info(const char* message, ...) { va_list args; va_start(args, message); log_format("info", message, args); va_end(args); }
void log_debug(const char* message, ...) { va_list args; va_start(args, message); log_format("debug", message, args); va_end(args); }
玩得开心!
init_slog("example", 1, 3);
打印和记录一些内容
slog(0, "Test message with level 0");
slog(2, "Test message with level 2");
slog(0, "Test message with int argument: %d", int_arg);
输出将会是这样的:
2015年04月02日56秒 - 带有0级别的测试消息
2015年04月02日56秒 - 带有2级别的测试消息
2015年04月02日56秒 - 带有整数参数69的测试消息
我也在寻找这个问题的解决方案。@ edwin-buck 的答案很简单,符合我的需求。
我对多线程和线程安全一无所知,但在使用Visual Studio编译器进行编译后(它可以提供一些警告和提示),并通过谷歌搜索,我认为进行一些修改可能会使上面的代码变得更加线程安全和更好。
// file log.c
void log(const char* tag, const char* message) {
time_t now;
struct tm _calendar_time;
char _buf[MAX_COUNT];
time(&now);
localtime_s(&_calendar_time, &now);
strftime(_buf, MAX_COUNT, "%c", &_calendar_time);
printf("%s [%s]: %s\n", _buf, tag, message);
}
如有错误请随时纠正
fprintf
包装器有什么问题呢? - Michael Mior