Skip to content

Instantly share code, notes, and snippets.

@pH200
Created February 12, 2012 06:40
Show Gist options
  • Save pH200/1806807 to your computer and use it in GitHub Desktop.
Save pH200/1806807 to your computer and use it in GitHub Desktop.
Modified DailyTextLogListener
using System;
using System.Diagnostics;
using System.IO;
using System.Security.Permissions;
namespace Darkthread
{
/// <summary>
/// 會依每天日期獨立個別檔案的TextWriterTraceListener
/// </summary>
[HostProtection(SecurityAction.LinkDemand, Synchronization = true)]
public class DailyTextLogListener : TraceListener
{
private TextWriterTraceListener _textWriterTraceListener;
/// <summary>
/// 入Log路徑設定,可使用{0:yyyyMMdd}依日期動態變化
/// </summary>
public string LogPathPattern { get; set; }
/// <summary>
/// 建構式,傳入Log路徑設定,可使用{0:yyyyMMdd}依日期動態變化
/// </summary>
/// <param name="logPathPattern"></param>
public DailyTextLogListener(string logPathPattern)
{
LogPathPattern = logPathPattern;
_textWriterTraceListener = new TextWriterTraceListener(GetDailyFilePath());
}
/// <summary>
/// 由Writer取出目前使用的Log檔路徑
/// </summary>
/// <returns></returns>
private string GetCurrentFilePath()
{
if (_textWriterTraceListener.Writer == null) return null;
return ((_textWriterTraceListener.Writer as StreamWriter).BaseStream as FileStream).Name;
}
/// <summary>
/// 由當天日期及LogPathPattern設定決定當時應使用的Log檔路徑
/// </summary>
/// <returns></returns>
private string GetDailyFilePath()
{
//未指定LogPathPattern時給予預設值
if (string.IsNullOrEmpty(LogPathPattern))
LogPathPattern = ".\\{0:yyyyMMdd}.log";
return string.Format(LogPathPattern, DateTime.Now);
}
/// <summary>
/// 確認目前使用的Writer有指向正確的檔案
/// </summary>
private void EnsureDailyLogPath()
{
//檢查目前的路徑是否為正確的路徑
string dailyLogPath = GetDailyFilePath();
if (dailyLogPath != GetCurrentFilePath())
{
//取出目錄部分
string dirPath = Path.GetDirectoryName(dailyLogPath);
//先確保路徑存在,若不存在則建立之
if (!Directory.Exists(dirPath))
Directory.CreateDirectory(dirPath);
//關閉目前使用的Log檔案
_textWriterTraceListener.Dispose();
// **********************
_textWriterTraceListener = new TextWriterTraceListener(dailyLogPath);
// **********************
}
}
//覆寫Write,寫入資料前確認檔案路徑
public override void Write(string message)
{
EnsureDailyLogPath();
_textWriterTraceListener.Write(message);
}
//覆寫WriteLine,寫入資料前確認檔案路徑
public override void WriteLine(string message)
{
EnsureDailyLogPath();
_textWriterTraceListener.WriteLine(message);
}
public override void Close()
{
_textWriterTraceListener.Close();
base.Close();
}
protected override void Dispose(bool disposing)
{
if (disposing) _textWriterTraceListener.Dispose();
base.Dispose(disposing);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment