本地文件日志,LocalLog.cs
用于系统日志写入到本地文件。
C# 全选
/// <summary>
/// 本地文件日志
/// </summary>
public class LocalLog
{
private static object _obj = new object();
private const string LOG_FILE = @"log.txt";
/// <summary>
/// 添加本地日志
/// </summary>
/// <param name="log"></param>
public static void AddLog(string log)
{
Task.Run(() =>
{
lock (_obj)//避免多线程占用文件
{
log = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff") + "\r\n" + log;
FileStream fs = null;
try
{
string binPath = Assembly.GetExecutingAssembly().Location;
binPath = Path.GetDirectoryName(binPath);
string fileName = Path.Combine(binPath, LOG_FILE);
fs = File.Open(fileName, FileMode.OpenOrCreate);
if (fs.Length > 0) log = "\r\n" + log;//加断行符
byte[] bs = Encoding.UTF8.GetBytes(log);
fs.Seek(fs.Length, SeekOrigin.Begin);
fs.Write(bs, 0, bs.Length);
fs.Flush();
fs.Close();
fs.Dispose();
}
catch
{
if (fs != null)
{
fs.Close();
fs.Dispose();
}
}
}
});
}
}
版权声明:本文为开发框架文库发布内容,转载请附上原文出处连接
NewDoc C/S框架网