Introduction
It's a common problem. You need a log file, but you need to make sure it never gets too big. A common solution is to write two log files and switch between them, deleting the old one when the newer one reaches a maximum length. Another way is to have 7 log files, one for each day of the week and overwrite them as each day changes.
This is a twist on filling this requirement. If the log file is smaller than the maximum size [iMaxLogLength
], this just appends the message to be logged to the log file. If the log file is larger than that, it grabs [iTrimmedLogLength
] number of bytes from the end of the existing log file and holds on to them, opens the file log file empty, writes the bytes it held onto from the original file and then appends the new message that was supposed to be logged.
Now the log file can go over the maximum size if the message to be logged is large enough, but there should be no harm done and anyway, it is probably the wrong tool for the job then.
Background
This is just written because I never found it written elsewhere. I use it for logging what is needed from a dashboard application. I need to know what it is doing and need to know about errors, but the users are never going to maintain any log.
Using the Code
private void buttonLog_Click(object sender, EventArgs e)
{
c_Log.writeToFile(textBoxMessages.Text, "../../log.log", 1);
}
public static class c_Log
{
static int iMaxLogLength = 15000;
static int iTrimmedLogLength = -1000;
static public void writeToFile(string strNewLogMessage, string strFile, int iLogLevel)
{
try
{
FileInfo fi = new FileInfo(strFile);
Byte[] bytesSavedFromEndOfOldLog = null;
if (fi.Length > iMaxLogLength) {
using (BinaryReader br = new BinaryReader
(File.Open(strFile, FileMode.Open)))
{
br.BaseStream.Seek(iTrimmedLogLength, SeekOrigin.End);
bytesSavedFromEndOfOldLog = br.ReadBytes((-1 * iTrimmedLogLength));
}
}
byte[] newLine = System.Text.ASCIIEncoding.ASCII.GetBytes(Environment.NewLine);
FileStream fs = null;
if (fi.Length < iMaxLogLength)
fs = new FileStream
(strFile, FileMode.Append, FileAccess.Write, FileShare.Read);
else fs = new FileStream
(strFile, FileMode.Create, FileAccess.Write, FileShare.Read);
using (fs)
{
if (bytesSavedFromEndOfOldLog != null)
{
Byte[] lineBreak = Encoding.ASCII.GetBytes
("### " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") +
" *** *** *** Old Log Start Position *** *** *** *** ###");
fs.Write(newLine, 0, newLine.Length);
fs.Write(newLine, 0, newLine.Length);
fs.Write(lineBreak, 0, lineBreak.Length);
fs.Write(newLine, 0, newLine.Length);
fs.Write(bytesSavedFromEndOfOldLog, 0, bytesSavedFromEndOfOldLog.Length);
fs.Write(newLine, 0, newLine.Length);
}
Byte[] sendBytes = Encoding.ASCII.GetBytes(strNewLogMessage);
fs.Write(sendBytes, 0, sendBytes.Length);
fs.Write(newLine, 0, newLine.Length);
}
}
catch (Exception ex)
{
; }
}
}
History