interface ILog

...{
bool Write(string message);
bool Write(Exception ex);
}

class TextFileLog:ILog


...{

public bool Write(string message)


...{

string fileDir = ConfigurationManager.APPSettings["LogTarget"].ToString();

using (StreamWriter w = File.AppendText(fileDir))


...{

// w.Write(" Log Entry : ");

w.WriteLine("發生時間{0}", DateTime.Now.ToLocalTime().ToString());

w.WriteLine("日志內容為:{0}", message);

w.WriteLine("-------------------------------");

// Update the underlying file.

w.Flush();

w.Close();

}

return true;

}

public bool Write(Exception ex)


...{


Write(ex.Message);

return true;

}

}

class XMLFileLog:ILog


...{

public bool Write(string message)


...{

string XMLFilePath = ConfigurationManager.APPSettings["LogTarget"].ToString();

if (File.Exists(XMLFilePath))


...{

XmlDocument doc = new XMLDocument();

doc.Load(XMLFilePath);

XMLDocumentFragment docFrag = doc.CreateDocumentFragment();

XMLNode nod = doc.SelectSingleNode("Logs");

docFrag.InnerXML = "<Log><Time>"+DateTime.Now.ToLocalTime().ToString()

+"</Time><Message>"+message+"</Message></Log>";

nod.AppendChild(docFrag);


doc.Save(XMLFilePath);

return true;

}

else


...{

XmlWriterSettings settings = new XMLWriterSettings();

settings.Indent = true; //設置縮進

settings.ConformanceLevel = ConformanceLevel.Auto;

settings.IndentChars = " ";

settings.OmitXMLDeclaration = false;

using (XmlWriter writer = XmlWriter.Create(XMLFilePath, settings))


...{

//Start writing the XML document

writer.WriteStartDocument(false);

//Start with the root element

writer.WriteStartElement("Logs");

writer.WriteStartElement("Log");

writer.WriteStartElement("Time");

writer.WriteString(DateTime.Now.ToLocalTime().ToString());

writer.WriteEndElement();

writer.WriteStartElement("Message");

writer.WriteString(message);

writer.WriteEndElement();

writer.WriteEndElement();

writer.WriteEndDocument();

//Flush the object and write the XML data to the file

writer.Flush();

return true;

}


}

}

public bool Write(Exception ex)


...{

Write(ex.Message);

return true;


}

}
測試

class Program


...{

static void Main(string[] args)


...{

System.Type type = System.Type.GetType(ConfigurationManager.APPSettings["LogType"].ToString());

ILog log = (ILog)Activator.CreateInstance(type);

log.Write(new Exception("異常測試"));

}

}
config配置為:
<?XML version="1.0" encoding="utf-8" ?>
<configuration>
<aPPSettings>
<add key="LogType" value="XMLFileLog"/>
<!-- XMLFileLog TextFileLog-->
<add key="LogTarget" value="c:\log.XML"/>
</aPPSettings>
</configuration>
數據庫實現的話繼承Ilog接口即可