Create a log file and update status dynamically in C # .NET

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

For the first state that I want to write, I want to create this log file. I need to keep adding this file with all the latest status messages (from 50 to 60 messages) for 10-20 minutes.

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

Any sample code will be appreciated.

thank

+3
source share
6 answers
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;
      }
     }
0
source

, , . Log4Net, , , :

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

, (NetCommonLogging).

+2

FileStream FileMode.Append.
, - ( ).

0

StreamWriter. - :

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

StreamWriter .

Logging, , ..

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();
        }

. blogpost, OP.

0

, , TimeSpam ( "10-20 " ), , .

, , - , . FileShare.Read :

.

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 implemented MakeFileNameand constructor set timeout.

0
source

Source: https://habr.com/ru/post/1780935/


All Articles