71 lines
2.8 KiB
C#
71 lines
2.8 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.IO;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace BayonetTransfer.Common
|
|
{
|
|
internal class LoggerHelper
|
|
{
|
|
public static string path = AppDomain.CurrentDomain.BaseDirectory;
|
|
|
|
/// <summary>
|
|
/// 读写锁,锁定文件写入权限,每个线程依次等待上个写入完成
|
|
/// </summary>
|
|
private static System.Threading.ReaderWriterLockSlim LogWriteLock = new System.Threading.ReaderWriterLockSlim();
|
|
|
|
/// <summary>
|
|
/// 记录文本日志
|
|
/// </summary>
|
|
/// <param name="LogData">日志内容</param>
|
|
public static void WriteLogger(string LogData)
|
|
{
|
|
LogData = DateTime.Now.ToLongTimeString() + ":" + LogData;
|
|
LogData = LogData.Replace("\r\n", Environment.NewLine);
|
|
string LogName = "日志_Send" + DateTime.Now.Year.ToString() + "-" + DateTime.Now.Month.ToString() + "-" + DateTime.Now.Day.ToString() + ".log";
|
|
WriteLogger(LogName, LogData);
|
|
}
|
|
/// <summary>
|
|
/// 记录文本日志
|
|
/// </summary>
|
|
/// <param name="logFileName">日志文件名称</param>
|
|
/// <param name="logData">日志内容</param>
|
|
public static void WriteLogger(string logFileName, string logData)
|
|
{
|
|
try
|
|
{
|
|
//设置读写锁为写入模式独占资源
|
|
//因写入模式的进入与释放在同一个代码块内,请保证在块内进入写入模式前不会触发异常,否则会因为进入与释放次数不符从而触发异常
|
|
//请勿长时间占用读写锁否则会导致其他线程饥饿。
|
|
LogWriteLock.EnterWriteLock();
|
|
string filename = Path.Combine(path, "log", logFileName);
|
|
//不存在目录则创建
|
|
if (!Directory.Exists(Path.Combine(path, "log")))
|
|
Directory.CreateDirectory(Path.Combine(path, "log"));
|
|
//不存在文件则创建
|
|
if (!File.Exists(filename))
|
|
{
|
|
File.Create(filename).Close();
|
|
}
|
|
using (FileStream file = new FileStream(filename, FileMode.Append, FileAccess.Write))
|
|
{
|
|
using (StreamWriter sw = new StreamWriter(file))
|
|
{
|
|
sw.WriteLine(logData);
|
|
}
|
|
file.Close();
|
|
}
|
|
}
|
|
catch { }
|
|
finally
|
|
{
|
|
//退出写入模式,释放资源占用
|
|
//注意释放与进入次数相同否则会触发异常
|
|
LogWriteLock.ExitWriteLock();
|
|
}
|
|
}
|
|
}
|
|
}
|