using System;
using System.IO;
using System.Threading.Tasks;

namespace Mall.ThirdCore.Commom
{
    internal class LogHelper
    {
        private static object objlock = new object();

        /// <summary>
        /// 错误日志
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="exception"></param>
        public static void Error(string msg, Exception exception)
        {
            Write(exception, msg);
        }

        /// <summary>
        /// 写日志
        /// </summary>
        /// <param name="msg"></param>
        public static void Write(string msg)
        {
            Write(null, msg);
        }

        /// <summary>
        /// 写日志
        /// </summary>
        /// <param name="exception"></param>
        /// <param name="otherMsg"></param>
        public static void Write(Exception exception, string otherMsg)
        {
            Task.Run(() => WriteLog(exception, otherMsg));
        }

        /// <summary>
        /// 写日志具体方法
        /// </summary>
        /// <param name="exception"></param>
        /// <param name="otherMsg"></param>
        private static void WriteLog(Exception exception, string otherMsg)
        {
            string str = "";
            try
            {
                str += string.Format(@"
DateTime:{0}", DateTime.Now.ToString());

                if (exception != null)
                {
                    if (exception.InnerException != null)
                    {
                        exception = exception.InnerException;
                    }
                    str += string.Format(@"
Message:{0}
StackTrace:
{1}
Source:{2}
"
 , exception.Message
 , exception.StackTrace
 , exception.Source

                    );
                }
                str += string.Format(@"
ExtMessage:{0}", otherMsg);

                string logdir = Config.LogPath;
                if (!Directory.Exists(logdir))
                    Directory.CreateDirectory(logdir);

                string filePath = Path.Combine(logdir, DateTime.Now.ToString("yyyyMMdd") + ".txt");

                lock (objlock)
                {
                    StreamWriter sw = new StreamWriter(filePath, true);
                    sw.WriteLine(str);
                    sw.Close();
                }
            }
            catch
            {

            }
        }
    }
}
