Solved

Logging function with timestamp in C

Posted on 2010-09-14
24
532 Views
Last Modified: 2012-05-10
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
Comment
Question by:PMembrey
  • 7
  • 7
  • 6
  • +2
24 Comments
 
LVL 5

Expert Comment

by:xdomains
ID: 33678744
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
 

Author Comment

by:PMembrey
ID: 33678754
I was hoping there would be a standard one - but I'll take a custom one too ;-)
0
 
LVL 32

Expert Comment

by:phoffric
ID: 33678762
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
 
LVL 5

Expert Comment

by:xdomains
ID: 33678794
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
 
LVL 32

Expert Comment

by:phoffric
ID: 33678903
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
 
LVL 32

Expert Comment

by:phoffric
ID: 33678947
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
 
LVL 32

Expert Comment

by:phoffric
ID: 33678950
Then just tag onto the HH:MM:SS the tv_usec from the call to gettimeofday().
0
 

Author Comment

by:PMembrey
ID: 33678954
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
 
LVL 32

Expert Comment

by:phoffric
ID: 33678965
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
 
LVL 5

Expert Comment

by:xdomains
ID: 33679257
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
 

Author Comment

by:PMembrey
ID: 33679278
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
 
LVL 5

Expert Comment

by:xdomains
ID: 33679283
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
Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

 
LVL 5

Expert Comment

by:xdomains
ID: 33679386
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
 
LVL 53

Expert Comment

by:Infinity08
ID: 33679510
Why re-invent the wheel ?

        http://log4c.sourceforge.net/
0
 
LVL 33

Expert Comment

by:pgnatyuk
ID: 33679588
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
 

Author Comment

by:PMembrey
ID: 33679622
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
 
LVL 32

Expert Comment

by:phoffric
ID: 33679633
Sorry about our other solutions. Next time, I'll be sure to write a complete function for you.
0
 
LVL 5

Expert Comment

by:xdomains
ID: 33679642
Its fine.. Seems like the suggestion ID: 33679386 wasnt good enough...:(
0
 
LVL 32

Expert Comment

by:phoffric
ID: 33679649
>> 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
 

Author Comment

by:PMembrey
ID: 33679661
Next time I will be more clear - but :

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

0
 
LVL 5

Expert Comment

by:xdomains
ID: 33679676
Only after a couple of queries i thought that could be the expectation and gave the idea ID: 33679386.
0
 
LVL 53

Expert Comment

by:Infinity08
ID: 33679974
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
 
LVL 33

Accepted Solution

by:
pgnatyuk earned 500 total points
ID: 33685564
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
 

Author Closing Comment

by:PMembrey
ID: 33688116
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

Featured Post

Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

Join & Write a Comment

An Outlet in Cocoa is a persistent reference to a GUI control; it connects a property (a variable) to a control.  For example, it is common to create an Outlet for the text field GUI control and change the text that appears in this field via that Ou…
This is a short and sweet, but (hopefully) to the point article. There seems to be some fundamental misunderstanding about the function prototype for the "main" function in C and C++, more specifically what type this function should return. I see so…
The goal of this video is to provide viewers with basic examples to understand recursion in the C programming language.
The goal of this video is to provide viewers with basic examples to understand opening and reading files in the C programming language.

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now