All pastes #837776 Raw Edit

Miscellany

public text v1 · immutable
#837776 ·published 2007-12-29 22:16 UTC
rendered paste body
using System;
using System.Globalization;
using System.IO;

namespace Chief
{
    public delegate void LogEvent(string message);

    public class Log
    {
        public event LogEvent Written;

        public string Directory = System.IO.Directory.GetCurrentDirectory() + "\\Log\\";
        public string FileName
        {
            get
            {
                if (m_FileName != null)
                    return m_FileName;

                return this.Directory + DateTime.Now.ToString("yyyy-MM-dd") + ".log";
            }

            set
            {
                this.m_FileName = value;
            }
        }

        public bool Enabled = true;

        private string m_FileName;

        public Log(string fileName)
        {
            this.FileName = fileName;
        }

        public void Append(string message)
        {
            lock (this)
            {
                if (this.Enabled)
                {
                    if (!System.IO.Directory.Exists(this.Directory))
                    {
                        DirectoryInfo info = System.IO.Directory.CreateDirectory(this.Directory);
                    }

                    if (!File.Exists(this.Directory + this.FileName))
                    {
                        FileStream fs = File.Create(this.Directory + this.FileName);
                        fs.Close();
                    }

                    for (; ; )
                    {
                        try
                        {
                            StreamWriter sw = File.AppendText(this.Directory + this.FileName);
                            sw.WriteLine(DateTime.Now.ToString("hh:mm:ss") + " | " + message);
                            sw.Flush();
                            sw.Close();

                            // If successful, exit loop
                            break;
                        }
                        catch (Exception)
                        {
                            // If unsuccessful, try again and again
                            System.Threading.Thread.Sleep(10);
                        }
                    }

                    if (Written != null)
                        Written(DateTime.Now.ToString("hh:mm:ss") + " | " + message);
                }
            }
        }
    }
}