Rita
Rita

Reputation: 921

Create Log file and update status dynamically in C#.NET

I want to create log file in the format (Log + datetime.Now).txt in my console application.

For the first status that i want to log, I want to create this log file. I need to keep appending this file with all the latest status messages(around 50 to 60 messages) within a timespan of 10 to 20 min.

At the same time, in this timeframe, if the user opens this file, he should be able to open it freely.

Any code sample would be appreciated.

Thanks

Upvotes: 3

Views: 12333

Answers (6)

Rita
Rita

Reputation: 921

public static Boolean CreateLogFile(String message)
        {
            try
      {
                //string location = @"C://IRPC//myfile1.txt";
                string location = System.Environment.CurrentDirectory + "\\log " + LogTime + ".txt";
                if (!File.Exists(location))
                {
                    FileStream fs;
                    using (fs = new FileStream(location, FileMode.Append, FileAccess.Write, FileShare.ReadWrite))
                    {
                    }
                    fs.Close();
                }

                Console.WriteLine(message);
                //Release the File that is created
                StreamWriter sw = new StreamWriter(location, true);
                sw.Write(message + Environment.NewLine);
                sw.Close();
                sw = null;
                return true;
      }
      catch(Exception ex)
            {
                EventLog.WriteEntry("MIDocShare", "Error in CreateLogFile" + ex.Message.ToString(), EventLogEntryType.Error, 6000);
       return false;
      }
     }

Upvotes: 0

Richard
Richard

Reputation: 109005

To rotate the file

Keep track of when the current file was opened, if it is more than a given TimeSpam (the "10-20 minutes") then close it, create a file filename and open that.

To allow others to read the file

This is all about controlling the file share options, while other methods will do the right defaults, if I need something specific I would rather be explicit. FileShare.Read has the right semantics:

Allows subsequent opening of the file for reading.

Solution

class FileLogger {
  private TimeSpan timeout;

  private DateTime openedFile;
  private Stream output;
  private StreamWriter writer;

  public Dispose() {
    if (writer != null) {
      writer.Dispose();
      writer = null;
    };
    if (output != null) {
      output.Dispose();
      output = null;
    }
  }

  public void Log(string message) {
    if (output == null
        || ((DateTime.UtcNow - openedFile) > timeout) {
      Dispose();

      string filename = MakeFileName();
      output = new FileStream(filename, FileMode.Append, FileAccess.Write, FileShare.Read);
      writer = new StreamWriter(output);
      openedFile = DateTime.UtcNow;
    }

    writer.WriteLine(writer);
  }
}

But with MakeFileName implemented and a constructor to set timeout.

Upvotes: 0

Zain Shaikh
Zain Shaikh

Reputation: 6043

You can use StreamWriter class for writing and even appending and text in the file.

I few days ago wrote a post on Logging, check out the blogpost here.

A code snippet from my blogpost

        // Open the file using stream write.
        // If file does not exist, StreamWriter will create it.
        // Use the overloaded constructor of StreamWriter and 
        // pass second parameter as true for appending text to file.
        using (StreamWriter writer = new StreamWriter(@"D://myfile.txt", true))
        {
            // write the text to writer
            writer.WriteLine("Your text here" + " - " + DateTime.Now);

            // clear all the buffer and 
            // write the buffered data to text file.
            writer.Flush();
        }

Note: I have modified the code a little from the blogpost, as to fulfill the OP's requirements.

Upvotes: 0

tobsen
tobsen

Reputation: 5398

Instead of rolling your own logging classes, use an existing logging framework. Log4Net for example is able to use a minimal locking approach, enabling other processes to read the file:

<appender name="FileAppender" type="log4net.Appender.FileAppender">
    <file value="log-file.txt" />
    <appendToFile value="true" />
    <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
    <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%message %date%newline" />
    </layout>
</appender>

If you want to change the used logging later on, you should try to use a logging abstraction (NetCommonLogging).

Upvotes: 2

Paul Michaels
Paul Michaels

Reputation: 16695

Try using the StreamWriter. Something like:

using (StreamWriter writer = new StreamWriter("log.txt"))
{
            writer.WriteLine("Text here");
}

Upvotes: 0

Austin Salonen
Austin Salonen

Reputation: 50225

Create the FileStream with FileMode.Append.
Notepad can open a text file when someone else is writing to it (though it's only current to the time it was opened).

Upvotes: 0

Related Questions