Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Time Stamp Issue

Tags:

c#

logging

time

I am writing program events to a txt file as a log but the time stamps are not updating at each point. I have declared the following string:

string timeStamp = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss.ff");
string taskComplete = (timeStamp) + " Task Complete";

which i am calling at different points through the program:

using (StreamWriter w_Log = new StreamWriter(file_Log, true))
            {
                w_Log.WriteLine(taskComplete);
                w_Log.Close();
            }

There are several more strings declared using timeStamp though the program as well. Here is an example of the log file:

2014/02/22 10:07:26.71 Process started
2014/02/22 10:07:26.71 Task Complete
2014/02/22 10:07:26.71 Task Complete
2014/02/22 10:07:26.71 Process complete, time elapsed: 0.496 seconds

As you can see, the time seems to be static even though it has taken 49ms to complete. When the program is run again, the time has changed to the current time but the same issue, the time written is the same throughout.

Do I need to use a different method or am I using this one incorrectly?

like image 750
Pickled Egg Avatar asked Jun 16 '26 22:06

Pickled Egg


1 Answers

So, at step 1 you're defining a string as being DateTime.Now with a particular format

At each point, you're just showing the same string. The string is fixed, it's not going to invoke DateTime.Now each time you run it.

So if you want it to change - you're going to need to call DateTime.Now each time.

w_Log.WriteLine(DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss.ff") + " Task Complete ");
like image 198
Haedrian Avatar answered Jun 19 '26 11:06

Haedrian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!