using MeterVision.Config;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MeterVision.Helper
{
public sealed class RealLogger
{
private static readonly object _lock = new object();
private static RealLogger _instance;
private readonly string _logFilePath;
///
/// 获取单例实例
///
public static RealLogger GetInstance()
{
if (_instance == null)
{
lock (_lock)
{
if (_instance == null)
{
_instance = new RealLogger();
}
}
}
return _instance;
}
private RealLogger()
{
// 日志文件路径
//_logFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "app.log");
_logFilePath = CfginiItem.GetConfigItem().RealLogPath;
if (!Directory.Exists(_logFilePath))
{
Directory.CreateDirectory(_logFilePath);
}
_logFilePath = Path.Combine(_logFilePath, ThisApp.GetNowTime_yyyyMMddHHmmss() + ".txt");
// 确保日志文件存在
if (!File.Exists(_logFilePath))
{
File.Create(_logFilePath).Close();
}
}
///
/// 追加日志内容,并写入文件
///
public void Log(string message)
{
//string logEntry = $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff}] {message}";
string logEntry = message;
// 控制台输出
Console.WriteLine(logEntry);
// 写入文件(追加模式)
lock (_lock)
{
using (StreamWriter writer = new StreamWriter(_logFilePath, true, Encoding.UTF8))
{
writer.WriteLine(logEntry);
writer.Flush();
}
}
}
///
/// 追加日志(异步版本)
///
//public async void LogAsync(string message)
//{
// string logEntry = $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff}] {message}";
// // 控制台输出
// Console.WriteLine(logEntry);
// // 异步写入文件(追加模式)
// lock (_lock)
// {
// using (StreamWriter writer = new StreamWriter(_logFilePath, true, Encoding.UTF8))
// {
// writer.WriteLine(logEntry);
// writer.Flush();
// }
// }
//}
///
/// 读取日志内容
///
public string ReadLogs()
{
lock (_lock)
{
return File.ReadAllText(_logFilePath);
}
}
public void Close()
{
lock (_lock)
{
_instance = null;
}
}
//--------------------------------------------------
}
//------------------------------------------------------
}