using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SysLogInfo
{
public class SysLog
{
private static System.Collections.Generic.Queue<string> _logBuffer = new System.Collections.Generic.Queue<string>();
private static bool _isDispose;
private static string _logPath;
private static string _logTilte;
public SysLog(string logTilte)
{
_logPath = AppDomain.CurrentDomain.BaseDirectory.Trim() + "log";
_logTilte = "Log_"+ logTilte + "_";
}
/// <summary>
/// 同步写入日志
/// </summary>
/// <param name="title">标题</param>
/// <param name="info">信息</param>
private static void SyncWriteLog(string title, string info)
{
AddLog(DateTime.Now, title, info);
_isDispose = true;
WriteLog(null);
OnNewLog(title, info, true);
}
/// <summary>
/// 写入错误日志
/// </summary>
/// <param name="logTime">时间</param>
/// <param name="title">标题</param>
/// <param name="info">内容</param>
private static void AddLog(DateTime logTime, string title, string info)
{
if (_isDispose) return;
lock (_logPath)
{
try
{
_logBuffer.Enqueue("[" + logTime.ToString(TimeFormat) + "] " + title + " " + info + Environment.NewLine);
}
catch
{
// ignored
}
}
}
/// <summary>
/// 写入日志
/// </summary>
/// <param name="title">标题</param>
/// <param name="info">信息</param>
public void WriteLogInfo(string info, string title="")
{
_logPath = string.IsNullOrWhiteSpace(_logPath) ? AppDomain.CurrentDomain.BaseDirectory.Trim() + "log" : _logPath;
AddLog(DateTime.Now, title, info);
System.Threading.ThreadPool.QueueUserWorkItem(WriteLog);
OnNewLog(title, info, false);
}
private static bool _isAdd;
private static void WriteLog(object obj)
{
if (_isAdd) return;
_isAdd = true;
lock (_logPath)
{
string logFile = LogPath + "\\" + LogTile + DateTime.Now.ToString("yyyyMMdd") + ".log";
try
{
using (var sw = new StreamWriter(logFile, true, Encoding.Default))
{
while (_logBuffer.Count > 0)
{
try
{
sw.Write(_logBuffer.Peek());
_logBuffer.Dequeue();
}
catch
{
break;
}
}
sw.Close();
sw.Dispose();
}
}
catch
{
// ignored
}
}
_isAdd = false;
}
/// <summary>
/// 获取或设置日志文件存放路径
/// </summary>
public static string LogPath
{
get
{
if (!Directory.Exists(_logPath))
{
Directory.CreateDirectory(_logPath);
}
return _logPath;
}
set { _logPath = value; }
}
public static string LogTile
{
get
{
return _logTilte;
}
set
{
_logTilte = value;
}
}
/// <summary>
/// 时间格式
/// </summary>
public static string TimeFormat { get; set; } = "HH:mm:ss,fff";
/// <summary>
/// 有新日志产生时
/// </summary>
public static event ExceptionHandler NewLog;
/// <summary>
/// 有新日志产生是触发
/// </summary>
/// <param name="title"></param>
/// <param name="info"></param>
/// <param name="isTerminating"></param>
private static void OnNewLog(string title, string info, bool isTerminating)
{
NewLog?.Invoke(title, info, isTerminating);
}
/// <summary>
/// 异常事件
/// </summary>
public delegate void ExceptionHandler(string title, string info, bool isTerminating);
}
}