创建一个类,类名为LogFile,下面是类中的代码:
public static string LogFilename = ""; //用来保存日志的文件名。
public static string writeLog(string Str)
{
try
{
LogFilename = AppDomain.CurrentDomain.BaseDirectory + @"log\" + LogFile.GetLogFilenameByDay(); ;
LogString(Str);
return "true";
}
catch (Exception e)
{
e.ToString();
return "false";
}
}
/// <summary>
/// 往日志文件中追加文本信息。成功返回空文本,失败返回错误信息。
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public static string LogString(string s)
{
string sError = "";
try
{
StreamWriter sw = new StreamWriter(LogFilename, true);
DateTime now = DateTime.Now;
s = "■" + now.ToString() + "\t[" + s + "]";
sw.WriteLine(s);
sw.Dispose();
}
catch (Exception ex)
{
sError = ex.Message;
}
return sError;
}
/// <summary>
/// 根据当前日期生成日志文件名。
/// </summary>
/// <returns></returns>
public static string GetLogFilenameByDay()
{
DateTime now = DateTime.Now;
string s = now.ToLongDateString();
s = s.Replace("/", "-");
s=s.Replace("\\","-");
s=s.Replace(":","");
return s + ".txt";
}
调用: LogFile.writeLog("日志内容");