0

I have to develop a file that logs daily and inside of the log file it shows me a date and time of every log. I got sofar that I create a log file with this code :

Stream iStream = File.Open("C:\\TEST\\logfiles\\Test_Plugin.txt", FileMode.Append); 
StreamWriter iWriter = new StreamWriter(iStream); 

I do get a logfile but there is no date time the out put is just bunch of messages underneath each other. Also I would like to log these on daily basis. This plugin would run on the server. thanks

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Letoir
  • 395
  • 7
  • 15
  • Why can't you just write, for example, `DateTime.Now.ToString()` to your log file? Regarding your second question: look at [this question](http://stackoverflow.com/questions/3243348/how-to-call-a-method-daily-at-specific-time-in-c). I'd also advice you to have a look at specific logging frameworks like log4net. – AndreySarafanov Jul 24 '14 at 08:23

1 Answers1

4

Why not start off by writing a static method that can do the logging so the logic is encapsulated in one place like this:

public static class Logger
{
    public static void Log(string format, params object[] args)
    {
        using (var streamWriter = new StreamWriter("C:\\TEST\\logfiles\\Test_Plugin.txt", true))
        {
            streamWriter.WriteLine("{0}: {1}", DateTime.Now.ToString("dd MMM yyyy HH:mm:ss"), string.Format(format, args));
        }
    }
}

Then you can call it in your code like this:

Logger.Log("hello this is a test");

It will also support string format expressions e.g:

Logger.Log("a: {0}  b: {1} c:{2}", "a", "bb", "ccc");
Kevin Holditch
  • 5,165
  • 3
  • 19
  • 35