1、目的
实现日志简单框架并测试。
2、实现
(1)、编写日志基本类
///
/// 定义日志输出目标类型
///
public enum LogTarget
{
File, //文件中
Database, //数据库中
EventLog //Windows日志中
}
///
/// 定义日志基类
///
public abstract class LogBase
{
protected readonly object lockObject = new object();
public abstract void Log(string message);
}
///
/// 输出文件日志
///
public class FileLogger : LogBase
{
private string filePath = Path.Combine(Environment.CurrentDirectory, "fileLog.txt");
public override void Log(string message)
{
lock (lockObject)
{
using (StreamWriter streamWriter = new StreamWriter(filePath,true))
{
streamWriter.WriteLine(message);
streamWriter.Close();
}
}
}
}
///
/// 输出数据库日志
///
public class DatabaseLogger : LogBase
{
string connectionString = string.Empty;
public override void Log(string message)
{
lock (lockObject)
{
//Code to log data to database
}
}
}
///
/// 输出Windows日志
///
public class EventLogger : LogBase
{
public override void Log(string message)
{
lock (lockObject)
{
EventLog eventLog = new EventLog("");
eventLog.Source = "IDGEventLog";
eventLog.WriteEntry(message);
}
}
}
(2)、编写业务封装类LogHelper
private static LogBase logger = null;
public static void Log(LogTarget target,string message)
{
switch (target)
{
case LogTarget.File:
logger = new FileLogger();
logger.Log(message);
break;
case LogTarget.Database:
logger = new DatabaseLogger();
logger.Log(message);
break;
case LogTarget.EventLog:
logger = new EventLogger();
logger.Log(message);
break;
default:
return;
}
}
(3)、在窗体程序中调用
private void button1_Click(object sender, EventArgs e)
{
LogHelper.Log(LogTarget.File, DateTime.Now + ": click Button1, textBox1.Text is:" + this.textBox1.Text);
}
private void button2_Click(object sender, EventArgs e)
{
LogHelper.Log(LogTarget.File, DateTime.Now + ": click Button2, textBox2.Text is:" + this.textBox2.Text);
}
3、运行效果