C#傻瓜日志类

    最近经常做小项目,如果想代码写的靠谱点就必须用到日志,但是常用的日志框架,比如企业库或者log4net都要配置个半天,如果想自定义某个功能也比较麻烦。没办法自己实现了个傻瓜日志类,代码很土鳖,不过简单易改,无配置。

    

    public static class SBLogger
{
static SBLogger()
{
_LogDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,"Log");
if (!Directory.Exists(_LogDir))
{
Directory.CreateDirectory(_LogDir);
}
}

/// <summary>
/// 写入错误日志
/// </summary>
/// <param name="msg"></param>
/// <param name="args"></param>
public static void Error(string msg, params object[] args)
{
WriteLog("ERROR", msg, args);
}

/// <summary>
/// 写入跟踪日志
/// </summary>
/// <param name="msg"></param>
/// <param name="args"></param>
public static void Trace(string msg, params object[] args)
{
WriteLog("TRACE", msg, args);
}

public static void Debug(string msg, params object[] args)
{
WriteLog("TRACE", msg, args);
Console.WriteLine(msg, args);
}

private static void WriteLog(string type, string msg, params object[] args)
{
string log = String.Format("{0} {1} {2}" + Environment.NewLine,
DateTime.Now.ToString("yyyy-MM-dd#HH:mm:ss"),
type, String.Format(msg, args));
lock (_WriteMutex)
{
File.AppendAllText(GetLogPath(), log, Encoding.UTF8);
}
}

private static string GetLogPath()
{
string path = Path.Combine(_LogDir, DateTime.Now.ToString("yyyy-MM-dd") + ".log");
return path;
}

private static string _LogDir = "";
private static object _WriteMutex = new object();
}
posted @ 2012-03-06 15:22  李土鳖  阅读(471)  评论(0编辑  收藏  举报