如何在日志文件中引入日期和时间

Tha*_*raj 9 c linux logging datetime

我有一个用C编写的守护进程.我将事件记录在日志文件中,但现在我想在将事件写入日志文件时添加日期和时间.我怎样才能做到这一点?

当前日志文件: -

Event one occurred: result:
Event two occurred: result:
Run Code Online (Sandbox Code Playgroud)

我希望日志文件看起来像: -

Sep 14 11:35:55 Event one occurred: result:
Sep 14 11:35:55 Event two occurred: result:
Run Code Online (Sandbox Code Playgroud)

我的环境是C和Linux.

pax*_*blo 13

您需要查看使用dategmtimelocaltime获取实际日期和时间.

然后strftime可以为您格式化.

示例程序如下:

#include <stdio.h>
#include <time.h>

int main (void) {
    char buff[20];
    struct tm *sTm;

    time_t now = time (0);
    sTm = gmtime (&now);

    strftime (buff, sizeof(buff), "%Y-%m-%d %H:%M:%S", sTm);
    printf ("%s %s\n", buff, "Event occurred now");

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

这输出:

2011-09-14 04:52:11 Event occurred now
Run Code Online (Sandbox Code Playgroud)

我更喜欢使用UTC而不是本地时间,因为它允许您将来自地理位置分离的机器的事件联系在一起,而不必担心时区差异.换句话说,使用gmtime而不是localtime除非你非常肯定你不会越过时区.

我也倾向于喜欢这种YYYY-MM-DD HH:MM:SS格式,因为它比月份名称更容易排序,这对于提取和操作工具至关重要.


如果您有一个提供可选边界检查功能的实现(根据C11的附录K),您可以gmtime_s优先使用.它允许您指定自己的缓冲区以接收结果,因此在重入和/或线程代码中更安全.

要使用它,您需要将代码更改为:

#include <stdio.h>
#define __STDC_WANT_LIB_EXT1__ 1
#include <time.h>

int main (void) {
    char buff[20];
    struct tm sTm;

    time_t now = time (0);
    gmtime_s (&now, &sTm);

    strftime (buff, sizeof(buff), "%Y-%m-%d %H:%M:%S", &sTm);
    printf ("%s %s\n", buff, "Event occurred now");

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

虽然你应该知道微软的人们已经设法以gmtime_s错误的方式得到了论据.你需要考虑到这一点.

POSIX(和Linux)还提供了一个gmtime_r函数,它以与标准gmtime_s函数相同的方式执行(参数的顺序正确).


ino*_*sco 8

根据@paxdiablo的回答添加我的日志功能.使用本地时间,但可以通过修改getFormattedTime()来使用gmt

COMMON.H

// Returns the local date/time formatted as 2014-03-19 11:11:52
char* getFormattedTime(void);

// Remove path from filename
#define __SHORT_FILE__ (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : __FILE__)

// Main log macro
#define __LOG__(format, loglevel, ...) printf("%s %-5s [%s] [%s:%d] " format "\n", getFormattedTime(), loglevel, __func__, __SHORT_FILE__, __LINE__, ## __VA_ARGS__)

// Specific log macros with 
#define LOGDEBUG(format, ...) __LOG__(format, "DEBUG", ## __VA_ARGS__)
#define LOGWARN(format, ...) __LOG__(format, "WARN", ## __VA_ARGS__)
#define LOGERROR(format, ...) __LOG__(format, "ERROR", ## __VA_ARGS__)
#define LOGINFO(format, ...) __LOG__(format, "INFO", ## __VA_ARGS__)
Run Code Online (Sandbox Code Playgroud)

common.c中

#include <time.h> // time_t, tm, time, localtime, strftime

// Returns the local date/time formatted as 2014-03-19 11:11:52
char* getFormattedTime(void) {

    time_t rawtime;
    struct tm* timeinfo;

    time(&rawtime);
    timeinfo = localtime(&rawtime);

    // Must be static, otherwise won't work
    static char _retval[20];
    strftime(_retval, sizeof(_retval), "%Y-%m-%d %H:%M:%S", timeinfo);

    return _retval;
}
Run Code Online (Sandbox Code Playgroud)

您可以像这样使用它们:

 LOGDEBUG("This is a log");
 LOGDEBUG("This is a log with params %d", 42);
Run Code Online (Sandbox Code Playgroud)

产生输出:

2014-03-19 13:22:14 DEBUG [main] [main.c:54] This is a log
2014-03-19 13:22:14 DEBUG [main] [main.c:55] This is a log with params 42
Run Code Online (Sandbox Code Playgroud)


oco*_*odo 5

要获取当前时间,您可以使用time.h例如...

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(void)
{
  time_t now;
  time(&now);

  printf("%s", ctime(&now)); // use ctime to format time to a string.

  return EXIT_SUCCESS;
}
Run Code Online (Sandbox Code Playgroud)

您还可以strftime按照 paxdiablo 的建议使用以获取更多时间/日期格式的可能性。

当然,对于您的情况,结果ctime(&now)将进入您的日志条目字符数组/字符串而不是printf.