how to parse syslog timestamp

2019-04-09 13:55发布

问题:

http://www.syslog.cc/ietf/drafts/draft-ietf-syslog-protocol-23.txt

6.2.3.1. Examples in the above link provides examples of different timestamp formates.

How can I parse these timestamps in C?

On-the-fly, any type of message can arrive and I want to be able to parse it.

回答1:

The date format is a stricter version of RFC3339 giving a string such as '2011-08-18T23:31:42Z'

I'm not certain the strptime function can deal with the timezone specifier (Z in the time string above), so it may be easier to handle that inside your own function. It definitely can't handle fractional seconds, since struct tm doesn't handle them. You could use struct timespec to store the fractional seconds if required.

You can parse out most of the format using strptime:

struct tm tm;
time_t t
char *extra;
extra = strptime( tmstr, "%C%y-%m-%dT%H:%M:%S", &tm );
tm.tm_isdst = -1;
t = mktime( &tm );

Following this, extra will be the remainder of the input tmstr. This could include fractional seconds, and will then contain the timezone format. If extra begins with a '.' just parse the number out with the strtod function:

if( extra && extra[0] == '.' )
{
  char *endptr;
  fraction = strtod( extra, &endptr );
  extra = endptr;

  /* use timespec if fractional seconds required */
  struct timespec ts;
  ts.tv_sec = t;
  ts.tv_nsec = fraction * 1000000000;
}

Then extra will now just contain the timezone specifier. If it is 'Z' then we're done since mktime gives you UTC time anyway. Otherwise you'll have an offset e.g. +03:00, so you will need to modify your time by that number of hours/minutes.