using System;
using System.IO;
using System.Net;
namespace Utils
{
public class LogWritter
{
// 禁止创建同时存在多个对象
private LogWritter(){}
private static LogWritter m_logger = null;
public static LogWritter CreateInstance()
{
if (m_logger == null)
{
m_logger = new LogWritter();
}
return m_logger;
}
//设置保存文件位置
private string m_filePath = string.Empty;
public void SetFilePath(string fileName)
{
if (!m_filePath.Equals(fileName))
{
m_filePath = fileName;
}
}
/**//// <summary>
/// 写日志,时间,机器名,日志内容
/// </summary>
/// <param name="content"></param>
public void WriteLog(string content)
{
string hostName = Dns.GetHostName();
if (!File.Exists(m_filePath))
{
FileStream fStream = new FileStream(m_filePath, FileMode.CreateNew);
fStream.Flush();
fStream.Close();
fStream = null;
}
StreamWriter sWriter = new StreamWriter(m_filePath, true, System.Text.Encoding.Default);
string txtTime = " \n" + "时间 : " + DateTime.Now.ToString();
string txtHost = " \n" + "机器名 : " + hostName;
string txtError = " \n" + "错误信息 : " + content;
string textWrite = txtTime + txtHost + txtError;
sWriter.WriteLine(textWrite);
sWriter.Flush();
sWriter.Close();
sWriter = null;
}
}
}
使用的时候呢,在需要记录的类里面新建一个全局变量,然后初始化,然后设置文件位置.之后就可以记录日志了.
例如:
{
private Utils.LogWritter m_logger = null;
public Test()
{
m_logger = Utils.LogWritter.CreateInstance();
m_logger.SetFilePath(@"C:\TestLog.txt");
}
static void Main()
{
try
{
string str = "a";
str.Substring(0, 2);
}
catch(Exception ee)
{
m_logger.WriteLog(ee.ToString());
}
}
}