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; } }} 使用的时候呢,在需要记录的类里面新建一个全局变量,然后初始化,然后设置文件位置.之后就可以记录日志了. 例如: class Test { 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()); } }} 今天在csdn上面看到有人找记录错误日志的类,可以记录机器名,时间.. 正好有空,就胡乱写了一个.但是有一点还是不太清楚,日志类的记录方法到底静态的好呢?还是普通的好呢?欢迎朋友多提宝贵意见和看法. 转载于:https://www.cnblogs.com/snowlove67/archive/2005/11/10/273040.html