MyLog

时间:2021-03-30 23:45:44

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

namespace TestExpressionLambda
{
    public class Logger
    {
        /// <summary>
        /// 默认路径
        /// </summary>
        public static readonly string RootPath = AppDomain.CurrentDomain.BaseDirectory + "log";

/// <summary>
        /// 默认文件名格式
        /// </summary>
        public static readonly string FileFormat = DateTime.Now.ToString("yyyy-MM-dd") + ".log";

public static readonly string LogFile = RootPath.TrimEnd('\\') + "\\" + FileFormat;

/// <summary>
        /// 默认Trace监听
        /// </summary>
        public static MyTraceListener traceListener ;

/// <summary>
        /// 静态实例
        /// </summary>
        private static readonly Logger instance = new Logger();
        static Logger()
        {
            if (!Directory.Exists(RootPath))
            {
                Directory.CreateDirectory(RootPath);
            }

if (!File.Exists(LogFile))
            {
                File.Create(LogFile).Close();
            }
            traceListener = new MyTraceListener(LogFile);
            Trace.Listeners.Clear();
            Trace.Listeners.Add(traceListener);
            Trace.AutoFlush = true;
        }

/// <summary>
        /// log输出<br>     /// 当然这里可以自己随便扩充
        /// </summary>
        /// <param name="msg"></param>
        public static void Log(string msg)
        {
            traceListener.WriteLine(msg);
        }
        public static void Log(object o, string category)
        {
            traceListener.Write(o, category);
        }
    }

public class MyTraceListener : TraceListener
    {
        public string FilePath { get; private set; }

public MyTraceListener(string filepath)
        {
            FilePath = filepath;
        }
        public override void Write(string message)
        {
            File.AppendAllText(FilePath, message);
        }

public override void WriteLine(string message)
        {
            File.AppendAllText(FilePath, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss    ") + message + Environment.NewLine);
        }

public override void Write(object o, string category)
        {
            string msg = "";

if (string.IsNullOrWhiteSpace(category) == false) //category参数不为空
            {
                msg = category + " : ";
            }

if (o is Exception) //如果参数o是异常类,输出异常消息+堆栈,否则输出o.ToString()
            {
                var ex = (Exception)o;
                msg += ex.Message + Environment.NewLine;
                msg += ex.StackTrace;
            }
            else if (o != null)
            {
                msg = o.ToString();
            }

WriteLine(msg);
        }
    }
}

相关文章