您的位置:首页 > 其它

A Simple Log Writer And Log Searching Class

2012-04-01 14:52 246 查看
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

class clsLog
{

private StringBuilder strLog;
private string strFileName = string.Empty;

//Initialize Logging
//###############################################################################################################################
public void StartLogging(string strLogFileName)
{
strLog = new StringBuilder();
strLog.Append("Logging Started At :     [" + DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss tt") + "]" + Environment.NewLine + Environment.NewLine);
strFileName = strLogFileName;
}
//###############################################################################################################################

//Write Log Entry
//###############################################################################################################################
public void WriteLogEntry(string strEntry)
{
strLog.Append("[" + DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss tt") + "]     " + strEntry + Environment.NewLine);
}
//###############################################################################################################################

//New Line
//###############################################################################################################################
public void NewLine()
{
strLog.Append(Environment.NewLine);
}
//###############################################################################################################################

//Stop Logging
//###############################################################################################################################
public void StopLogging()
{
strLog.Append(Environment.NewLine + "Logging Stopped At :     [" + DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss tt") + "]" + Environment.NewLine);
if (System.IO.File.Exists(strFileName))
{
using (StreamWriter sw = File.AppendText(strFileName))
{
sw.Write(strLog.ToString());
sw.Close();
}
}
else
{
System.IO.File.WriteAllText(strFileName,strLog.ToString());
}
}
//###############################################################################################################################

//Search Log
//###############################################################################################################################
public string SearchLog(string strLogFileName, DateTime dtFrom, DateTime dtTo)
{
if (!File.Exists(strLogFileName)) { return null; }

string strReturnString = string.Empty;
using (StreamReader sr = new StreamReader(strLogFileName)) //strFileName
{
String line;
while ((line = sr.ReadLine()) != null)
{
DateTime strDateTime;
if (line.Length > 22)
{
DateTime.TryParse(line.Substring(0, 25).Replace('[', ' ').Replace(']', ' ').Trim(), out strDateTime);
if (strDateTime >= dtFrom && strDateTime
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: