master
ZGGSONG 3 years ago
parent dcf52cead7
commit 14c5b0a807

@ -0,0 +1,94 @@
using System;
using System.IO;
using System.Reflection;
using TRI_TCP_Client.Log;
namespace TRI_TCP_Client
{
public class Logger
{
#region Instance
private static object logLock;
private static string dataString = DateTime.Now.ToString("yyyyMMdd_HHmm");
private static Logger _instance;
private static string logFileName;
private Logger() { }
/// <summary>
/// Logger instance
/// </summary>
public static Logger Instance
{
get
{
if (_instance == null)
{
_instance = new Logger();
logLock = new object();
logFileName = "TRI_Log_" + dataString + ".txt";
}
return _instance;
}
}
#endregion
/// <summary>
/// 写Log
/// </summary>
/// <param name="logContent">Log content</param>
/// <param name="logType">information</param>
public void WriteLog(string logContent, LogType logType = LogType.Information, string fileName = null)
{
try
{
string basePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
basePath = @"D:\Log";
if (!Directory.Exists(basePath))
{
Directory.CreateDirectory(basePath);
}
string[] logText = new string[] { DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff") + " " + logType.ToString() + ": " + logContent };
if (!string.IsNullOrEmpty(fileName))
{
fileName = fileName + "_" + logFileName;
}
else
{
fileName = logFileName;
}
lock (logLock)
{
File.AppendAllLines(basePath + "\\" + fileName, logText);
}
}
catch (Exception) { }
}
/// <summary>
/// Write exception to log file
/// </summary>
/// <param name="exception">Exception</param>
public void WriteException(Exception exception, string specialText = null)
{
if (exception != null)
{
Type exceptionType = exception.GetType();
string text = string.Empty;
if (!string.IsNullOrEmpty(specialText))
{
text = text + specialText + Environment.NewLine;
}
text = "Exception: " + exceptionType.Name + Environment.NewLine;
text += " " + "Message: " + exception.Message + Environment.NewLine;
text += " " + "Source: " + exception.Source + Environment.NewLine;
text += " " + "StackTrace: " + exception.StackTrace + Environment.NewLine;
WriteLog(text, LogType.Error);
}
}
}
}
Loading…
Cancel
Save