在项目里经常会遇到要写log的这种问题,log可以帮着记录程序在运行过程中的信息和可能出现的异常信息。在我所写的log服务里面,有时候是输入字符串,有的时候是需要写入对象列表。
记录字符串log信息,写入txt文本文件,代码如下:
public void LogToFile(string logText, string fileName)
{
using (StreamWriter w = File.AppendText(fileName))
{
w.WriteLine(logText);
}
using (StreamReader r=File.OpenText(fileName))
{
string line;
while ((line = r.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
}
记录对象列表log,写入txt文本文件,代码如下:(但在运行完成之后会发现log文件会出现乱码)
public void SaveLog(List cases, string fileName)
{
var serializer = new BinaryFormatter();
using (var stream = File.OpenWrite(fileName))
{
serializer.Serialize(stream, cases);
}
}
public void ReadLog(string fileName)
{
var serializer = new BinaryFormatter();
using (var stream = File.OpenRead(fileName))
{
if (stream != null && stream.Length != 0)
{
stream.Position = 0;
var cases = (List)serializer.Deserialize(stream);
}
}
}
记录对象列表log,写入xml文件,代码如下:
public void SerializeObject(List serializableObject, string fileName)
{
if (serializableObject == null) { return; }
try
{
XmlDocument xmlDocument = new XmlDocument();
XmlSerializer serializer = new XmlSerializer(serializableObject.GetType());
using (MemoryStream stream = new MemoryStream())
{
serializer.Serialize(stream, serializableObject);
stream.Position = 0;
xmlDocument.Load(stream);
xmlDocument.Save(fileName);
stream.Close();
}
}
catch (Exception ex)
{
//Log exception here
}
}
public List DeSerializeObject(string fileName)
{
if (string.IsNullOrEmpty(fileName)) { return default(List);
try
{
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load(fileName);
string xmlString = xmlDocument.OuterXml;
using (StringReader read = new StringReader(xmlString))
{
System.Type outType = typeof(List);
XmlSerializer serializer = new XmlSerializer(outType);
using (XmlReader reader = new XmlTextReader(read))
{
objectOut = (List)serializer.Deserialize(reader);
reader.Close();
}
read.Close();
}
}
catch (Exception ex)
{
//Log exception here
}
return objectOut;
}
网友评论