日志记录帮助类

Posted Jacob Wu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了日志记录帮助类相关的知识,希望对你有一定的参考价值。

using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Common
{
    public class Log
    {
        public static string logAddress = ConfigurationManager.AppSettings["LogAddress"] + "Log";

        /// <summary>
        /// 将异常打印到LOG文件
        /// </summary>
        /// <param name="ex">异常</param>
        /// <param name="LogAddress">日志文件地址</param>
        public static void WriteLog(Exception ex, string LogAddress = "")
        {
            if (!Directory.Exists(logAddress))
            {
                Directory.CreateDirectory(logAddress);
            }
            //如果日志文件为空,则默认在Debug目录下新建 YYYY-mm-dd_Log.log文件
            if (LogAddress == "")
            {
                LogAddress = logAddress + \\ +
                    DateTime.Now.Year + - +
                    DateTime.Now.Month + - +
                    DateTime.Now.Day + "_Log.log";
            }
            //把异常信息输出到文件
            StreamWriter sw = new StreamWriter(LogAddress, true);
            sw.WriteLine("当前时间:" + DateTime.Now.ToString());
            sw.WriteLine("异常信息:" + ex.Message);
            sw.WriteLine("异常对象:" + ex.Source);
            sw.WriteLine("调用堆栈:\n" + ex.StackTrace.Trim());
            sw.WriteLine("触发方法:" + ex.TargetSite);
            sw.WriteLine();
            sw.Close();
        }
    }
}

 

以上是关于日志记录帮助类的主要内容,如果未能解决你的问题,请参考以下文章

多线程日志帮助

日志记录类(明确FileStreamDictionary等用法)

如何通过单击片段内的线性布局从片段类开始新活动?下面是我的代码,但这不起作用

改进的日志记录类

argparse 代码片段只打印部分日志

日志帮助类