Step1:创建log类
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Configuration;
namespace Framework
{
public class Logger
{
public Logger(Type Class)
{
this.classname = Class.Name;
}
private string classname;
public string ClassName
{
get
{
return this.classname;
}
set
{
this.classname = value;
}
}
public void SystemLog(string Message, string Method) { WriteLogInTxtFile(1, Message, Method); }
public void InfoLog(string Message, string Method) { WriteLogInTxtFile(2, Message, Method); }
public void DebugLog(string Message, string Method) { WriteLogInTxtFile(3, Message, Method); }
public void ErrorLog(string Message, string Method) { WriteLogInTxtFile(4, Message, Method); }
public void WarnLog(string Message, string Method) { WriteLogInTxtFile(4, Message, Method); }
public void ErrorLog(Exception Ex, string Method)
{
string Message = String.Format("异常信息: {0}, 异常堆栈信息: {1} ", Ex.Message, Ex.StackTrace);
ErrorLog(Message, Method);
}
private void WriteLogInTxtFile(Int16 LogType, string Message, string Method)
{
string Path = AppDomain.CurrentDomain.BaseDirectory;
string LogFolder = "Logs";
if (!String.IsNullOrEmpty(ConfigurationManager.AppSettings["LogFolder"]))
{
LogFolder = ConfigurationManager.AppSettings["LogFolder"];
}
string LogPathType = String.Empty;
switch (LogType)
{
case 1:
Path += String.Format("{0}\\System\\", LogFolder);
LogPathType = "System";
break;
case 2:
Path += String.Format("{0}\\Info\\", LogFolder);
LogPathType = "Info";
break;
case 3:
Path += String.Format("{0}\\Debug\\", LogFolder);
LogPathType = "Debug";
break;
case 4:
Path += String.Format("{0}\\Error\\", LogFolder);
LogPathType = "Error";
break;
}
if (!Directory.Exists(Path))
{
Directory.CreateDirectory(Path);
}
//日志文件是以当天时间命名
string FileName = String.Format("{0}{1}", Path, "Log" + DateTime.Now.ToString("yyyyMMdd") + ".txt");
if (!File.Exists(FileName))
{
File.Create(FileName).Close();
}
//日志格式
string LogFormat = String.Format("Start 时间:{0} 日志类型:{1} 类名:{2} 方法名称:{3} 日志内容:{4} End;", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), LogPathType, ClassName, Method, Message);
using (StreamWriter writer = File.AppendText(FileName))
{
writer.WriteLine(LogFormat);
}
}
}
}
Step2:调用Log类
Logger log = new Logger(MethodBase.GetCurrentMethod().DeclaringType);
log.DebugLog("debuggerLog", MethodBase.GetCurrentMethod().Name);
<pre name="code" class="csharp"> log.ErrorLog("ErrorLog", MethodBase.GetCurrentMethod().Name);
<pre name="code" class="csharp"> log.InfoLog("InfoLog", MethodBase.GetCurrentMethod().Name);