日志记录对于任何语言的程序员来说都是必不可少的,对于一个要;连续工作很久很久的程序,你总不能一直调试顶着它看吧,这时候日志就是我们的眼,以此来排除各种疑难杂症,注释已经写到代码当中
using System;
using System.IO;
/*本实例提供一个简单的用于热水锅炉系统故障排除的应用程序。
* 当维修工程师检查锅炉时,锅炉的温度和压力会随着维修工程师的备注自动记录到日志文件中。*/
namespace LogWrite
{
// boiler 类
/// <summary>
/// 获取参数与输出参数
/// </summary>
class Boiler
{
private int temp; //温度
private int pressure; //压力
public Boiler(int t, int p) //构造函数
{
temp = t;
pressure = p;
}
public int getTemp()
{
return temp;
}
public int getPressure()
{
return pressure;
}
}
/***********发布器类***********/
class DelegateBoilerEvent
{
public delegate void BoilerLogHandler(string status); //声明事件的委托类型 定义委托
public event BoilerLogHandler BoilerEventLog; // 基于上面的委托定义事件 定义事件
public void LogProcess() //日志记录的方法 创建触发事件的方法 触发事件的方法
{
string remarks = "O. K"; //默认标志为成功
Boiler b = new Boiler(100, 12); //实例化并根据构造方法传参
int t = b.getTemp(); //调用对象方法获取温度值
int p = b.getPressure(); //获取压力值
DateTime dateTime = DateTime.Now; //获取当前时间
if (t > 150 || t < 80 || p < 12 || p > 15)
{
remarks = "Need Maintenance"; //不合格参数判别,标志
}
OnBoilerEventLog(dateTime+": Logging Info: "); //触发事件,必须与事件是同名方法
OnBoilerEventLog("Temparature " + t + " Pressure: " + p);
OnBoilerEventLog("Message: " + remarks+"\n");
}
protected void OnBoilerEventLog(string message) //定义委托中调用的方法 创建触发事件的方法的方法
{
if (BoilerEventLog != null)
{
BoilerEventLog(message); //触发事件,必须和事件是同名方法
}
}
}
// 该类保留写入日志文件的条款
class BoilerInfoLogger
{
FileStream fs;
StreamWriter sw;
public BoilerInfoLogger(string filename)
{
fs = new FileStream(filename, FileMode.Append, FileAccess.Write);
sw = new StreamWriter(fs);
}
public void Logger(string info)
{
sw.WriteLine(info); //写入日志当中
}
public void Close()
{
sw.Close();
fs.Close();
}
}
/***********订阅器类***********/
class Program
{
static void Logger(string info)
{
Console.WriteLine(info); //控制台输出,每条行信息
}//end of Logger
static void Main(string[] args)
{
BoilerInfoLogger filelog = new BoilerInfoLogger("d:\\boiler.txt"); //创建日志写入路径
DelegateBoilerEvent boilerEvent = new DelegateBoilerEvent(); //实例化DelegateBoilerEvent发布器类
boilerEvent.BoilerEventLog += new DelegateBoilerEvent.BoilerLogHandler(Logger);//实例化事件,使用委托指向处理方法,控制台显示处理方法
boilerEvent.BoilerEventLog += new DelegateBoilerEvent.BoilerLogHandler(filelog.Logger); //日志写入方法
boilerEvent.LogProcess(); //调用触发事件的方法
Console.ReadLine();
filelog.Close();
}//end of main
}
}