You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

117 lines
3.5 KiB

using System;
using System.IO;
using System.Reflection;
namespace Monitor.LogService
{
public enum LogType
{
Information,
Debug,
Run,
Failure,
Warning,
Error
}
public class Log
{
#region 实例化
/// <summary>
/// log文件锁
/// </summary>
private static object logLock;
/// <summary>
/// Log实例
/// </summary>
private static Log logInstance;
/// <summary>
/// 日志文件名
/// </summary>
private static string logFileName;
private Log() { }
/// <summary>
/// Log实例
/// </summary>
public static Log LogInstance
{
get
{
if (logInstance == null)
{
logInstance = new Log();
logLock = new object();
logFileName = Guid.NewGuid() + ".log";
}
return logInstance;
}
}
#endregion
/// <summary>
/// 写日志到日志文件
/// </summary>
/// <param name="logContent">Log内容</param>
/// <param name="logType">Log类型</param>
public void WriteLog(string logContent,LogType logType = LogType.Information,string fileName = null)
{
try
{
string basePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
basePath = @"D:\TruckSwappingLog\";
if (!Directory.Exists(basePath))
{
Directory.CreateDirectory(basePath);
}
string strData = DateTime.Now.ToString("yyyy-MM-dd");
if (!Directory.Exists(basePath + strData))
{
Directory.CreateDirectory(basePath + strData);
}
string[] logText = new string[] { DateTime.Now.ToString("HH:mm:ss.fff") + ": " + logType.ToString() + ": " + logContent };
if (!string.IsNullOrEmpty(fileName))
{
fileName = fileName + "_" + DateTime.Now.Hour.ToString();
}
else
{
fileName = logFileName;
}
lock (logLock)
{
File.AppendAllLines(basePath + strData + "\\" + fileName + ".log", logText);
}
}
catch (Exception) { }
}
/// <summary>
/// 写异常日志到文件中
/// </summary>
/// <param name="exception">异常类型</param>
public void WriteExceptionInfo(Exception exception,string specText = null)
{
if (exception != null)
{
Type exceptionType = exception.GetType();
string text = string.Empty;
if (!string.IsNullOrEmpty(specText))
{
text = text + specText + 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);
}
}
}
}