3

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

Rita
  • 911
  • 4
  • 16
  • 31
  • you want them to be able to open the file and edit it while the application is still logging? Or does the user just need read only access to the file while the application is logging to it? – NerdFury Dec 17 '10 at 19:53
  • User just need readonly access while logging. I noticed like even if the user opens, that file also will be updating even if the user opens. – Rita Dec 17 '10 at 19:57
  • take a look at a mature logging system to do this easily. Enterprise Library has what you're looking for and is very easy to use. – Steven Evers Dec 18 '10 at 20:49
  • duplicate of http://stackoverflow.com/q/4117647/415789 –  Dec 18 '10 at 20:51

6 Answers6

2

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).

tobsen
  • 5,328
  • 3
  • 34
  • 51
0

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).

Austin Salonen
  • 49,173
  • 15
  • 109
  • 139
0

Try using the StreamWriter. Something like:

using (StreamWriter writer = new StreamWriter("log.txt"))
{
            writer.WriteLine("Text here");
}
Paul Michaels
  • 16,185
  • 43
  • 146
  • 269
0

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.

Zain Shaikh
  • 6,013
  • 6
  • 41
  • 66
0

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.

Community
  • 1
  • 1
Richard
  • 106,783
  • 21
  • 203
  • 265
0
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;
      }
     }
Rita
  • 911
  • 4
  • 16
  • 31