Re: Trimming the appended FileStream

Tech Tip: Click here to run a free scan for Windows Errors and optimize PC performance



Just open a file in OpenOrCreate mode and then use FileStream.Seek(0, SeekOrigin.End) to append new text to the end of log file. If you want to trim the log file, use for that FileStream.SetLength(TrimToSize) method.

PS:
In all my projects I'm using log4net which has lots of functionality: different appenders, multithreading, output formatting, filters. It's not necessary to invent the wheel each time...



-- Sergey Bogdanov [.NET CF MVP, MCSD] http://www.sergeybogdanov.com


Matijaz wrote:
Helo,
I would like to write very simple logger with cleaning capability if the log
file exceeds specified size. But 'TruncateLogFile()' function works only if
ctor parameter 'fs' is provided as 'new System.IO.FileStream(FILES_PATH +
logFileName, IO.FileMode.OpenOrCreate, IO.FileAccess.ReadWrite)'. If set as
append mode like this new System.IO.FileStream(FILES_PATH + logFileName,
IO.FileMode.Append, IO.FileAccess.Write) it throws IOException instead of
trimming the log file. How to open FileStream to append with file seek
option?

Here comes the code:


public class Log { private const string LOGGER = "LOGGER> "; private const long MAX_FILE_SIZE = 524288; private FileStream m_FileStream; private StreamWriter logFile; private bool isWriteCalled; private bool consoleOutput;

  // 2005.07.07 FileStream added to truncate log if > MAX_FILE_SIZE
  public Log(FileStream fs, bool console)
  {
   m_FileStream = fs;
   logFile = new StreamWriter(fs);
   consoleOutput = console;
   this.TruncateLogFile();
   this.AddHeader();

  }

  protected void AddHeader()
  {
   string startSession = "Log session started: " +
DateTime.Now.ToLongDateString() + " at " + DateTime.Now.ToLongTimeString();
   logFile.Write("\r\n\r\n\r\n\r\n");
   logFile.WriteLine(startSession);
   if (consoleOutput) Console.WriteLine(LOGGER + startSession);
   logFile.Write("\r\n\r\n");
  }

  public bool TruncateLogFile()
  {
   try
   {
    if ((m_FileStream.Length > MAX_FILE_SIZE))
    {
     //m_FileStream.Flush();
     m_FileStream.SetLength(0);
     return true;
    }
   }
   catch (Exception ex)
   {
    Console.WriteLine(">>>"+ex.Message);
   }
   return false;
  }

  public void Write(string str)
  {
   if (isWriteCalled)
   {
    logFile.Write(str);
    if (consoleOutput) Console.Write(str);
   }
   else
   {
    logFile.Write(DateTime.Now.ToLongTimeString() + " " + str);
    if (consoleOutput) Console.Write(str);
   }
   isWriteCalled = true;
  }

  public void WriteLine(string line)
  {
   if (isWriteCalled)
   {
    logFile.WriteLine(line);
    if (consoleOutput) Console.WriteLine(line);
   }
   else
   {
    logFile.WriteLine(DateTime.Now.ToLongTimeString() + " " + line);
    if (consoleOutput) Console.WriteLine(line);
   }
   if (this.TruncateLogFile()) this.AddHeader();
   isWriteCalled = false;
  }
 }

.



Relevant Pages

  • Re: c++ application not receiving events
    ... If I do the same thing in a VB app, ... Below are sections of the log file where they deviate. ... Private WithEvents oTAPI As TAPI3Lib.TAPI ' will hold our TAPI object ... Private oAddress As ITAddress ' will hold our selected address (you can ...
    (microsoft.public.win32.programmer.tapi)
  • c++ application not receiving events
    ... If I do the same thing in a VB app, ... Below are sections of the log file where they deviate. ... Private WithEvents oTAPI As TAPI3Lib.TAPI ' will hold our TAPI object ... Private oAddress As ITAddress ' will hold our selected address (you can hold ...
    (microsoft.public.win32.programmer.tapi)
  • Re: writing to a log reliably
    ... There's no difference in the code below for Replace and Append! ... But how do I write to a log file reliably? ... logline2 = timelogline ... Call Stream log_name, 'C', 'OPEN WRITE REPLACE' ...
    (comp.lang.rexx)
  • Re: [fw-wiz] More Syslog Questions
    ... > The only problem I have with chattr +a is that if an intruder gains ... > and the replace the append only attribute, ... > done to the log file. ...
    (Firewall-Wizards)
  • Re: Two simultaneous write accesses to a text file
    ... :> something like a log file then the log file grows one line at a time. ... :> HOWEVER that only helps with simple text files where you can append things ... If there is buffering, ... The file is opened in append mode. ...
    (comp.lang.php)