1717
1818#include <errno.h>
1919#include <fcntl.h>
20+ #include <inttypes.h>
21+ #include <stdint.h>
2022#include <stdio.h>
2123#include <stdlib.h>
2224#include <string.h>
@@ -47,26 +49,15 @@ static const char *rc_service_state_name(RC_SERVICE state)
4749}
4850
4951/*
50- * Format the current time as an ISO 8601 timestamp with milliseconds.
51- * Returns a dynamically allocated string that must be freed by the caller.
52+ * Get the current monotonic time in milliseconds.
5253 */
53- static char * format_timestamp (void )
54+ static int64_t tm_now (void )
5455{
55- time_t now ;
56- struct tm * tm ;
57- char timebuf [32 ];
58- char * result ;
59- int ms ;
56+ struct timespec tv ;
57+ int64_t sec_to_ms = 1000 , round_up = 500000 , ns_to_ms = 1000000 ;
6058
61- clock_gettime (CLOCK_REALTIME , & ts );
62- tm = localtime (& ts .tv_sec );
63- ms = (int )(ts .tv_nsec / 1000000 );
64-
65- strftime (timebuf , sizeof (timebuf ), "%Y-%m-%dT%H:%M:%S" , tm );
66- xasprintf (& result , "%s.%03d%+03ld%02ld" , timebuf , ms ,
67- tm -> tm_gmtoff / 3600 , (labs (tm -> tm_gmtoff ) % 3600 ) / 60 );
68-
69- return result ;
59+ clock_gettime (CLOCK_MONOTONIC , & tv );
60+ return (tv .tv_sec * sec_to_ms ) + ((tv .tv_nsec + round_up ) / ns_to_ms );
7061}
7162
7263/*
@@ -96,7 +87,6 @@ void rc_eventlog_service(const char *service, RC_SERVICE state)
9687{
9788 int svcfd ;
9889 int eventsfd ;
99- char * timestamp ;
10090 FILE * fp ;
10191 const char * state_name ;
10292
@@ -116,21 +106,16 @@ void rc_eventlog_service(const char *service, RC_SERVICE state)
116106
117107 service = basename_c (service );
118108
119- timestamp = format_timestamp ();
120-
121109 state_name = rc_service_state_name (state );
122110
123111 fp = do_fopenat (eventsfd , service , O_WRONLY | O_CREAT | O_APPEND );
124112 close (eventsfd );
125113
126- if (!fp ) {
127- free (timestamp );
114+ if (!fp )
128115 return ;
129- }
130116
131- fprintf (fp , "%s %s\n" , timestamp , state_name );
117+ fprintf (fp , "%" PRId64 " %s\n" , tm_now () , state_name );
132118 fclose (fp );
133- free (timestamp );
134119}
135120
136121/*
@@ -139,7 +124,6 @@ void rc_eventlog_service(const char *service, RC_SERVICE state)
139124void rc_eventlog_global (const char * event_type , const char * message )
140125{
141126 int svcfd ;
142- char * timestamp ;
143127 FILE * fp ;
144128
145129 if (!event_type || !message )
@@ -152,15 +136,10 @@ void rc_eventlog_global(const char *event_type, const char *message)
152136 if (rc_eventlog_init () != 0 )
153137 return ;
154138
155- timestamp = format_timestamp ();
156-
157139 fp = do_fopenat (svcfd , RC_EVENTLOG_GLOBAL , O_WRONLY | O_CREAT | O_APPEND );
158- if (!fp ) {
159- free (timestamp );
140+ if (!fp )
160141 return ;
161- }
162142
163- fprintf (fp , "%s %s %s\n" , timestamp , event_type , message );
143+ fprintf (fp , "%" PRId64 " %s %s\n" , tm_now () , event_type , message );
164144 fclose (fp );
165- free (timestamp );
166145}
0 commit comments