Improve company productivity with a Business Account.Sign Up

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 571
  • Last Modified:

Logging function with timestamp in C

Hi,

For the points I'm looking for a standalone C function that works like printf but prepends each line with a timestamp formatted in HH:MM:SS.microseconds.

Any takers? :-)
0
PMembrey
Asked:
PMembrey
  • 7
  • 7
  • 6
  • +2
1 Solution
 
xdomainsCommented:
There arent any C functions (from the standard C library) which does this, from whatever I know.

Are you looking at a custom written function in C?
0
 
PMembreyAuthor Commented:
I was hoping there would be a standard one - but I'll take a custom one too ;-)
0
 
phoffricCommented:
I assume you have a function that can print out HH:MM:SS.us, say printTime(). Below is a simple macro that works with the proviso that if used in an if statement, then the body of the if be blocked as in {...}.

So the following will not give desired results:

if( event_occurred )
    LOG_FORMAT("event # = %d\n", event_num);

If event_occurred is false, then the printTime() will be skipped (good), but the printf still is executed.

But the following fixes this:

if( event_occurred ) {
    LOG_FORMAT("event # = %d\n", event_num);
}

#define LOG_FORMAT printTime(); printf

Open in new window

0
What Kind of Coding Program is Right for You?

There are many ways to learn to code these days. From coding bootcamps like Flatiron School to online courses to totally free beginner resources. The best way to learn to code depends on many factors, but the most important one is you. See what course is best for you.

 
xdomainsCommented:
You might already know, here is a function to log the time. Just add a format string to this function, and add to the printf() inside the function to log with timestamp.

int timestamp()  
{  
time_t ltime;  
struct tm *Tm;  
ltime=time(NULL);  
Tm=localtime(&ltime);  
printf("[%d] %d %d %d, %d:%d:%d",  
Tm->tm_wday, /* Mon - Sun */
 Tm->tm_mday,  
 Tm->tm_mon,  
 Tm->tm_year,  
Tm->tm_hour,  
Tm->tm_min,  
Tm->tm_sec);  
}
0
 
phoffricCommented:
For the microseconds, you should look at this link:
     http://www.cs.utah.edu/dept/old/texinfo/glibc-manual-0.02/library_19.html

In it, see the following under the topic "High-Resolution Calendar":
    Data Type: struct timeval
       Notice that tv_sec "represents the number of seconds since the epoch. It is equivalent to a normal time_t value."

    gettimeofday()  (NOTE: not part of standard C library)
0
 
phoffricCommented:
If, for example, you are interested in the HH:MM:SS elapsed in the last 24 hours, you can see this for the code:
    http://www.experts-exchange.com/Programming/Languages/C/Q_20916969.html#a10583273
0
 
phoffricCommented:
Then just tag onto the HH:MM:SS the tv_usec from the call to gettimeofday().
0
 
PMembreyAuthor Commented:
What I need is something like this:

int i = 10;

log("The value of i is %d\n",i);

which prints:

11:33:19.349356  The value of i is 10
0
 
phoffricCommented:
The above comments shows various approaches on how to make your log function. If you wish to create a buffer that is created with a printf like function, you can use sprintf.
      http://www.cplusplus.com/reference/clibrary/cstdio/sprintf/

Then you can pass this formatted string into a log function, and then first call your printTime() function followed by the printf function.

0
 
xdomainsCommented:
int printfwithtime(char *logstring)  
{  
time_t ltime;  
struct tm *Tm;  
ltime=time(NULL);  
Tm=localtime(&ltime);  
printf("[%d] %d %d %d, %d:%d:%d %s",  
Tm->tm_wday, /* Mon - Sun */
 Tm->tm_mday,  
 Tm->tm_mon,  
 Tm->tm_year,  
Tm->tm_hour,  
Tm->tm_min,  
Tm->tm_sec, logstring);  
}


/******/
// Invoke like this -
char tempString[100];
sprintf(tempString, "%s\n", "test string to log");
printfwithtime(tempString);

Format the time as you wish...:)

0
 
PMembreyAuthor Commented:
that works if I just have a static string message, but if I use formatting and pass in the variables (as per my example)  it won't work :-)
0
 
xdomainsCommented:
Do this in the sprintf

sprintf(tempString, "%s, %d\n", "test string to log", 5);

Note that you are passing tempString to the printfwithtime() function.
Did you try this way?
0
 
xdomainsCommented:
If you want to have a function exactly like printf(), write a function with variable arguments.
You can have something like printLogWithTime(char*, ...); and use it as
printLogWithTime("String is %s, count is %d", somestring, 10);

Have the above time stamp printing code in the implementation of the above function.

For details see
http://publications.gbdirect.co.uk/c_book/chapter9/stdarg.html
0
 
Infinity08Commented:
Why re-invent the wheel ?

        http://log4c.sourceforge.net/
0
 
pgnatyukCommented:
I attached a small program. Here is the output:

[Switching to process 12293]
Running…
08:41:031 : Hello, World!

Debugger stopped.

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

void Tracer(char* format, ...)
{
	time_t ltime;  
	struct tm *Tm;  

	va_list args;
	va_start(args, format);
	
	ltime = time(NULL);  
	Tm = localtime(&ltime);  
	printf("%02d:%02d:%03d. ", Tm->tm_hour, Tm->tm_min, Tm->tm_sec);  	
	
	vprintf(format, args);
	printf("\n");

	va_end(args);
}

int main (int argc, const char * argv[]) 
{
    Tracer("Hello, World!");

    return 0;
}

Open in new window

0
 
PMembreyAuthor Commented:
I'm going to give pgnatyuk the points as s/he provided an actual function that does the job....

pgnatyuk, if you could update it so that it includes microseconds that would be awesome :-)
0
 
phoffricCommented:
Sorry about our other solutions. Next time, I'll be sure to write a complete function for you.
0
 
xdomainsCommented:
Its fine.. Seems like the suggestion ID: 33679386 wasnt good enough...:(
0
 
phoffricCommented:
>> Seems like the suggestion ID: 33679386 wasnt good enough
No. The author should have stated that a complete function is expected. That way, we know what is expected.
0
 
PMembreyAuthor Commented:
Next time I will be more clear - but :

For the points I'm looking for a **standalone C function** that works like printf .

0
 
xdomainsCommented:
Only after a couple of queries i thought that could be the expectation and gave the idea ID: 33679386.
0
 
Infinity08Commented:
Please do consider http:#33679510 though ... Why roll your own if you can use a tried and tested solution (with a lot more features too) ?
0
 
pgnatyukCommented:
Console:

Running…
21:02:23 430797. Hello, World!


#include <stdio.h>
#include <stdarg.h>
#include <time.h>
#include <sys/time.h>

void Tracer(char* format, ...)
{
	struct timeval tv;
	struct timezone tz;
	struct tm *tm;
	gettimeofday(&tv, &tz);
	tm = localtime(&tv.tv_sec);
	printf("%d:%02d:%02d %d. ", tm->tm_hour, tm->tm_min, tm->tm_sec, tv.tv_usec);
	
	va_list args;
	va_start(args, format);
	vprintf(format, args);
	printf("\n");
	
	va_end(args);
}

int main (int argc, const char * argv[]) 
{
    Tracer("Hello, World!");
	
    return 0;
}

Open in new window

0
 
PMembreyAuthor Commented:
Out of interest I'm going to open another question on how to do the same thing with log4c. I have a play with it and the helloworld examples, but unfortunately didn't get very far...
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

What Kind of Coding Program is Right for You?

There are many ways to learn to code these days. From coding bootcamps like Flatiron School to online courses to totally free beginner resources. The best way to learn to code depends on many factors, but the most important one is you. See what course is best for you.

  • 7
  • 7
  • 6
  • +2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now