C#实现简单日志记录
程序员文章站
2022-06-10 18:29:03
...
public class LogClass
{
private static LogClass mInstance = null;
private static readonly object lockAssistant = new object();
public static LogClass Instance
{
get
{
if (mInstance == null)
{
lock (lockAssistant)
{
if (mInstance == null)
{
mInstance = new LogClass();
}
}
}
return mInstance;
}
}
private LogClass()
{
}
/// <summary>
/// 写日志(追加到上次日志下一行)
/// </summary>
/// <param name="logText">日志内容</param>
public void WriteLogFile(string logText)
{
string logPath = System.Windows.Forms.Application.StartupPath;
if (!Directory.Exists(logPath))
Directory.CreateDirectory(logPath);//Directory.GetCurrentDirectory()
string fname = logPath + "\\LogFile.log";
FileInfo finfo = new FileInfo(fname);
if (!finfo.Exists)
{
FileStream fs;
fs = File.Create(fname);
fs.Close();
finfo = new FileInfo(fname);
}
if (finfo.Length > 1024 * 1024 * 10)
{
DateTime dtnow = DateTime.Now;
string newPath = System.Windows.Forms.Application.StartupPath + "\\" + dtnow.ToString("yyyyMMddHHmmss") + "之前LogFile";
if (!Directory.Exists(newPath))
Directory.CreateDirectory(newPath);
File.Move(fname, newPath + "\\LogFile.log");
}
FileStream fs2 = finfo.OpenWrite();
{
StreamWriter w = new StreamWriter(fs2);
w.BaseStream.Seek(0, SeekOrigin.End);
w.WriteLine("{0} {1}", DateTime.Now.ToLongDateString(), DateTime.Now.ToLongTimeString());
w.WriteLine(logText);
w.WriteLine("------------------------------------");
w.Flush();
w.Close();
}
fs2.Close(); fs2.Dispose(); fs2 = null;
}
}
调用时使用LogClass.Instance.WriteLogFile(ex.ToString());
上一篇: 蟹黄怎么做更好吃,有什么营养价值。
下一篇: C# 二进制 十进制 十六进制互转