因为工作需要需要在XP上运行一个C#编写的Winform插件,我就用Framework2.0,因为存在接口交互所以想保留交易过程的入参出参。
考虑到插件本身实施的因素,就没有使用Log4、NLog等成熟的日志插件。在网上搜索了一个是通过TextWriterTraceListener实现的,但是实际使用
过程中发现并没实现我想要的功能,于是乎自己重新造了个*,如果大家有需要可以参考下。
/// <summary>
/// 日志类型
/// </summary>
public enum LogType
{
Error,
Trace,
Info
} /// <summary>
/// 日志类
/// 支持同步和异步
/// </summary>
public sealed class Logger
{ #region 变量|常量 /// <summary>
/// 用于Trace的组织输出的类别名称
/// </summary>
private const string error = "\r\n***********************EXCEPTION {0}***********************"; /// <summary>
/// 跟踪
/// </summary>
private const string trace = "\r\n*************************TRACE {0}*******************************"; /// <summary>
/// 信息
/// </summary>
private const string info = "\r\n****************************INFO {0}********************************"; /// <summary>
/// 1 仅控制台输出
/// 2 仅日志输出
/// 3 控制台+日志输出
/// </summary>
private static readonly int flag = ; //可以修改成从配置文件读取 #endregion #region 委托 private delegate void AsyncLogException(Exception ex);
private delegate void AyyncLog(string msg, LogType type);
private delegate void AsyncLogSqlCommand(SqlCommand cmd);
private delegate void AsyncLogSql(string sql, params SqlParameter[] parameter); private static void BeginError(Exception ex)
{
if (null != ex)
{
string path = GetLogPath(LogType.Error);
//输出日志头
WriteLog(path, string.Format(error, DateTime.Now));
while (null != ex)
{
WriteLog(path, string.Format("{0} {1}\r\n{2}\r\nSource:{3}", ex.GetType().Name, ex.Message, ex.StackTrace, ex.Source));
ex = ex.InnerException;
}
}
} private static void BeginTrace(string msg, LogType type)
{
if (string.IsNullOrEmpty(msg)) return;
string path = GetLogPath(type);
//输出日志头
WriteLog(path, string.Format(trace, DateTime.Now));
//输出日志内容
WriteLog(path, msg);
}
#endregion #region IO操作
/// <summary>
/// 获取日志类型对应的日志存储环境
/// </summary>
/// <param name="type">日志类型</param>
/// <returns></returns>
private static string GetLogPath(LogType type)
{
DateTime time = DateTime.Now;
string subdir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "logs");
subdir = Path.Combine(subdir, type.ToString());
subdir = Path.Combine(subdir, time.ToString("yyyyMM"));
if (!Directory.Exists(subdir))
{
Directory.CreateDirectory(subdir);
}
string result = Path.Combine(subdir, time.ToString("yyyyMMdd") + ".log");
return result;
} /// <summary>
/// 写入日志
/// </summary>
/// <param name="path">日志环境</param>
/// <param name="text">写入的文本值</param>
private static void WriteLog(string path, string text)
{
string filePath = Path.GetDirectoryName(path);
if (Directory.Exists(filePath) == false)
{
Directory.CreateDirectory(filePath);
}
if (File.Exists(path))
{
using (StreamWriter sw = File.AppendText(path))
{
sw.WriteLine(text + "\n");
sw.Flush();
sw.Close();
}
}
else
{
StreamWriter sr = File.CreateText(path);
sr.WriteLine(text + "\n");
sr.Flush();
sr.Close();
}
}
#endregion #region 发布的方法
/// <summary>
/// 写入异常日志
/// </summary>
/// <param name="ex">异常对象</param>
/// <param name="isAsync">是否异步,默认异步</param>
public static void Error(Exception ex, bool isAsync = true)
{
if (isAsync)
new AsyncLogException(BeginError).BeginInvoke(ex, null, null);
else
BeginError(ex);
} /// <summary>
/// 写入错误日志
/// </summary>
/// <param name="msg">错误信息</param>
/// <param name="isAsync">是否异步,默认异步</param>
public static void Error(string msg, bool isAsync = false)
{
if (isAsync)
new AyyncLog(BeginTrace).BeginInvoke(msg, LogType.Error, null, null);
else
BeginTrace(msg, LogType.Error);
} /// <summary>
/// 异步跟踪日志
/// </summary>
/// <param name="msg"></param>
public static void Trace(string msg, bool isAsync = true)
{
if (isAsync)
new AyyncLog(BeginTrace).BeginInvoke(msg, LogType.Trace, null, null);
else
BeginTrace(msg, LogType.Trace);
} /// <summary>
/// 写入日志信息,日志类型为info
/// </summary>
/// <param name="msg">日志信息</param>
/// <param name="isAsync">是否异步,默认异步</param>
public static void Info(string msg, bool isAsync = true)
{
if (isAsync)
new AyyncLog(BeginTrace).BeginInvoke(msg, LogType.Info, null, null);
else
BeginTrace(msg, LogType.Info);
}
#endregion }
}
调用代码:
private void button1_Click_1(object sender, EventArgs e)
{
Logger.Info("测试");
}
运行效果如下: