I have one daemon written in C. I am logging the events in a log file, but now I want to add date and time while writing event to log file. How can I achieve that?
Current log file:-
Event one occurred: result:
Event two occurred: result:
I want the log file to look like:-
Sep 14 11:35:55 Event one occurred: result:
Sep 14 11:35:55 Event two occurred: result:
My environment is C and Linux.
You need to look into using
dateand eithergmtimeorlocaltimeto get the actual date and time.Then
strftimecan format it for you.Sample program follows:
This outputs:
I prefer the use of UTC rather than local time since it allows you to tie together events from geographically separated machine without worrying about timezone differences. In other words, use
gmtimerather thanlocaltimeunless you’re very certain you won’t be crossing timezones.I also tend to prefer the
YYYY-MM-DD HH:MM:SSformat since it’s easier to sort than month names, vital for extraction and manipulation tools.If you have an implementation that provides the optional bounds-checking functions (as per Appendix K of C11), you can probably use
gmtime_sin preference. It allows you to specify your own buffer for receiving the result and is thus safer in re-entrant and/or threaded code.To use that, you need to change your code to something like:
Although you should be aware that the folks at Microsoft have somehow managed to get the arguments for
gmtime_saround the wrong way. You’ll need to take that into account.POSIX (and Linux) also provides a
gmtime_rfunction which performs in the same way as the standardgmtime_sfunction (with the arguments in the correct order).