123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117 |
- 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;
- /// <summary>
- /// 获取单例实例
- /// </summary>
- 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();
- }
- }
- /// <summary>
- /// 追加日志内容,并写入文件
- /// </summary>
- 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();
- }
- }
- }
- /// <summary>
- /// 追加日志(异步版本)
- /// </summary>
- //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();
- // }
- // }
- //}
- /// <summary>
- /// 读取日志内容
- /// </summary>
- public string ReadLogs()
- {
- lock (_lock)
- {
- return File.ReadAllText(_logFilePath);
- }
- }
- public void Close()
- {
- lock (_lock)
- {
- _instance = null;
- }
- }
- //--------------------------------------------------
- }
- //------------------------------------------------------
- }
|