ASP.NET记录错误日志

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq389216533/article/details/51995580
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Text;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;

namespace ERPSite.UniversalLog
{
    public class ExceptionLog
    {
        /// <summary>
        /// 写入日志到文本文件 
        /// </summary>
        /// <param name="action">动作</param>
        /// <param name="e">异常</param>
        /// <param name="Pars">参数</param>
        /// <param name="Name">用户名</param>
        public static void WriteTextLog(string action = "123",Exception e=null,string Pars="",string Name="")
        {
            DateTime time = DateTime.Now;
            string path = AppDomain.CurrentDomain.BaseDirectory + @"\Log\";
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            string fileFullPath = path + time.ToString("yyyy-MM-dd") + ".txt";
            StringBuilder str = new StringBuilder();<span style="font-family: Arial, Helvetica, sans-serif;">//要写入的信息</span>
            str.Append("【Time】:    " + time.ToString() + "\r\n");
            str.Append("【Action】:  " + action + "\r\n");
            str.Append("【Parameters】:  " + Pars + "\r\n");
            str.Append("【Message】: " + e.Message  + "\r\n");
            str.Append("【Source】:"+ e.Source  + "\r\n");
            str.Append("【StackTrace】: " + e.StackTrace + "\r\n");
            str.Append("【操作人】: " + Name + "\r\n");
            str.Append("============================================================\r\n\r\n");
            try
            {
                using (FileStream fs = new FileStream(fileFullPath, !File.Exists(fileFullPath) == true ? FileMode.Create : FileMode.Append))
                {
                    using (StreamWriter sw = new StreamWriter(fs, Encoding.Default))
                    {
                        //声明数据流文件写入方法  
                        sw.WriteLine();
                        sw.Write(str.ToString());
                        sw.Flush();
                        sw.Close();
                        sw.Dispose();
                    }
                }
            }
            catch { }
        }  
    }
}

猜你喜欢

转载自blog.csdn.net/qq389216533/article/details/51995580