验证中...
Languages: C#
Categories: 常用工具包
Latest update 2019-06-12 20:56
gistfile1.txt
Raw Copy
public static class LogHelper
{
static LogHelper()
{
Thread t = new Thread(new ThreadStart(WriteLog));
t.IsBackground = false;
t.Start();
}
public static void LogFullError(this Exception exception)
{
EnqueueMessage(exception.ExtractAllStackTrace());
// WriteTextLog(exception.ExtractAllStackTrace());
}
/// <summary>
/// 提取异常及其内部异常堆栈跟踪
/// </summary>
/// <param name="exception">提取的例外</param>
/// <param name="lastStackTrace">最后提取的堆栈跟踪(对于递归), String.Empty or null</param>
/// <param name="exCount">提取的堆栈数(对于递归)</param>
/// <returns>Syste.String</returns>
private static string ExtractAllStackTrace(this Exception exception, string lastStackTrace = null, int exCount = 1)
{
var ex = exception;
const string entryFormat = "#{0}: {1}\r\n{2}";
//修复最后一个堆栈跟踪参数
lastStackTrace = lastStackTrace ?? string.Empty;
//添加异常的堆栈跟踪
lastStackTrace += string.Format(entryFormat, exCount, ex.Message, ex.StackTrace);
if (exception.Data.Count > 0)
{
lastStackTrace += "\r\n Data: ";
foreach (var item in exception.Data)
{
var entry = (DictionaryEntry)item;
lastStackTrace += string.Format("\r\n\t{0}: {1}", entry.Key, exception.Data[entry.Key]);
}
}
//递归添加内部异常
if ((ex = ex.InnerException) != null)
return ex.ExtractAllStackTrace(string.Format("{0}\r\n\r\n", lastStackTrace), ++exCount);
return lastStackTrace;
}
/// <summary>
/// 写入日志到文本文件
/// </summary>
/// <param name="strMessage">日志内容</param>
private static void WriteTextLog(string strMessage)
{
try
{
string path = AppDomain.CurrentDomain.BaseDirectory + @"Log\";
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
DateTime time = DateTime.Now;
string fileFullPath = path + time.ToString("yyyy-MM-dd") + ".log";
using (FileStream fs = new FileStream(fileFullPath, FileMode.Append, FileAccess.Write))
{
using (StreamWriter sw = new StreamWriter(fs))
{
string value = string.Format(@"【{0}】 {1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), System.Environment.NewLine + strMessage + System.Environment.NewLine);
sw.WriteLine(value);
sw.Flush();
}
fs.Close();
}
}
catch (Exception ex)
{
}
}
public static void Info(string msg)
{
EnqueueMessage(msg);
// WriteTextLog(msg);
}
/// <summary>
/// 记录消息Queue
/// </summary>
private static readonly ConcurrentQueue<string> _que = new ConcurrentQueue<string>();
/// <summary>
/// 信号
/// </summary>
private static readonly ManualResetEvent _mre = new ManualResetEvent(false);
/// <summary>
/// 从队列中写日志至磁盘
/// </summary>
private static void WriteLog()
{
while (true)
{
// 等待信号通知
_mre.WaitOne();
string msg;
// 判断是否有内容需要如磁盘 从列队中获取内容,并删除列队中的内容
while (_que.Count > 0 && _que.TryDequeue(out msg))
{
// 判断日志等级,然后写日志
WriteTextLog(msg);
}
// 重新设置信号
_mre.Reset();
Thread.Sleep(1);
}
}
public static void EnqueueMessage(string message)
{
_que.Enqueue(message);
// 通知线程往磁盘中写日志
_mre.Set();
}
}

Comment list( 0 )

You need to Sign in for post a comment

Help Search

Gitee_you_jiang_zheng_wen Zheng_wen_close