Files
MetroGauges-Old/MetroGauges/Controls/LogManager.cs
2026-02-23 17:02:55 +08:00

101 lines
3.5 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace MetroGauges
{
public sealed class LogManager
{
private static string logPath = string.Empty;
private static object locker = new object();
//读写锁,当资源处于写入模式时,其他线程写入需要等待本次写入结束之后才能继续写入
private static ReaderWriterLockSlim LogWriteLock = new ReaderWriterLockSlim();
/// <summary>
/// 保存日志的文件夹
/// </summary>
public static string LogPath
{
get
{
if (logPath == string.Empty)
{
logPath = AppDomain.CurrentDomain.BaseDirectory + @"logs\";
}
return logPath;
}
set { logPath = value; }
}
private static string logFielPrefix = string.Empty;
/// <summary>
/// 日志文件前缀
/// </summary>
public static string LogFielPrefix
{
get { return logFielPrefix; }
set { logFielPrefix = value; }
}
/// <summary>
/// 写日志
/// </summary>
public static void WriteLog(string logFile, string msg)
{
try
{
//设置读写锁为写入模式独占资源,其他写入请求需要等待本次写入结束之后才能继续写入
//注意:长时间持有读线程锁或写线程锁会使其他线程发生饥饿 (starve)。 为了得到最好的性能,需要考虑重新构造应用程序以将写访问的持续时间减少到最小。
// 从性能方面考虑,请求进入写入模式应该紧跟文件操作之前,在此处进入写入模式仅是为了降低代码复杂度
// 因进入与退出写入模式应在同一个try finally语句块内所以在请求进入写入模式之前不能触发异常否则释放次数大于请求次数将会触发异常
LogWriteLock.EnterWriteLock();
if (!Directory.Exists(LogPath))
{
Directory.CreateDirectory(LogPath);
}
string path = LogPath + LogFielPrefix + logFile + "_" + DateTime.Now.ToString("yyyyMMdd") + ".Log";
System.IO.StreamWriter sw = System.IO.File.AppendText(path);
sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss: ") + msg);
sw.Close();
}
catch
{
}
finally {
//退出写入模式,释放资源占用
//注意:一次请求对应一次释放
// 若释放次数大于请求次数将会触发异常[写入锁定未经保持即被释放]
// 若请求处理完成后未释放将会触发异常[此模式不下允许以递归方式获取写入锁定]
LogWriteLock.ExitWriteLock();
}
}
/// <summary>
/// 写日志
/// </summary>
public static void WriteLog(LogFile logFile, string msg)
{
WriteLog(logFile.ToString(), msg);
}
}
/// <summary>
/// 日志类型
/// </summary>
public enum LogFile
{
Trace,
Warning,
Error,
SQL
}
}