编程语言
首页 > 编程语言> > C#中日志记录的开发

C#中日志记录的开发

作者:互联网

1、配置文件App.config中配置日志文件路径

<!-- 日志路径 -->
<add key="logPath" value="C:\TEST\TestLog" />

2、获取路径

public string logPath = ConfigurationManager.AppSettings["logPath"];//日志路径

3、记录日志的实现方法

public static void WriteLogC(string logMsg)
{
if (!Directory.Exists(logPath))
{
Directory.CreateDirectory(logPath);
}
string fileName = string.Empty;
fileName = logPath + "\\" + DateTime.Now.ToString("yyyyMMdd") + ".txt";
if (!File.Exists(fileName))
{
using (File.Create(fileName)) { };
}
try
{
using (FileStream fs = new FileStream(fileName, FileMode.Append, FileAccess.Write))
{
fs.Lock(fs.Length, 1);
StreamWriter sw = new StreamWriter(fs);
byte[] buffer = Encoding.Default.GetBytes(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ffff: ") + logMsg);
fs.Write(buffer, 0, buffer.Length);

sw.WriteLine(" ");
sw.Flush();
sw.Close();
}
}
catch (Exception e)
{
//App.MessageBox.Show($"异常信息:{e}".Translate());
}
}

标签:fs,string,记录,C#,sw,logPath,fileName,日志
来源: https://www.cnblogs.com/Cuimc/p/16523388.html