自制迷你日志类

  写网站程序的时候,都要把异常写入日志吧,比较经常使用的是Log4Net,不过我要求不高,只须要把异常和信息记在网站服务器的网站目录下就能够了,因而我本身写了一个。服务器

    public static class Logger
    {
        private static readonly object Obj = new object();

        public static void Log(string title, string msg)
        {
            LogError(title, msg);
        }

        public static void Error(string title, Exception ex)
        {
            if (ex == null)
            {
                return;
            }

            var sb = new StringBuilder();
            sb.AppendLine(ex.Message).AppendLine(ex.StackTrace);

            foreach (IDictionary value in ex.Data.Values)
            {
                if (value != null)
                {
                    foreach (DictionaryEntry entry in value)
                    {
                        sb.Append("Key:").Append(entry.Key).Append(",Value:").AppendLine(entry.Value.ToString());
                    }
                }
            }

            if (ex.InnerException != null)
            {
                sb.Append("InnerMessage:")
                    .AppendLine(ex.InnerException.Message)
                    .Append("InnerStackTrace:")
                    .AppendLine(ex.InnerException.StackTrace);

                foreach (IDictionary value in ex.InnerException.Data.Values)
                {
                    if (value != null)
                    {
                        foreach (DictionaryEntry entry in value)
                        {
                            sb.Append("InnerKey:")
                                .Append(entry.Key)
                                .Append(",InnerValue:")
                                .AppendLine(entry.Value.ToString());
                        }
                    }
                }
            }

            LogError(title, sb.ToString());
        }

        private static void LogError(string title, string msg)
        {
            string filePath = Path.GetDirectoryName(HttpRuntime.AppDomainAppPath) + "\\log\\" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";

            lock (Obj)
            {
                try
                {
                    File.AppendAllText(filePath, string.Format("{0:HH:mm:ss}:{1}:{2}\r\n", DateTime.Now, title, msg));
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }
            }
        }
    }

  记录普通讯息没什么难的,记录异常的话就要选择记录哪些信息了,这里我没把Source,HelpLink和TargetSite记录下来,由于我感受他们没什么用,这里惟一难点的就是写日志加锁,为什么要加锁呢,由于同一文件同一时间只能被一个进行写入呀,把日志类搞成静态类也是出于这个考虑的。网站

相关文章
相关标签/搜索