打赏

以c#实现轻量级的日志管理,着实简单,置一静态类记之:

    /// <summary>
    /// 日志管理
    /// </summary>
    public static class LogHelper
    {
        //超过3M则清除
        const int MAX_LOG_SIZE = 3 * 1024 * 1024;

        public static void Init(string fileName)
        {
            CheckAndCleanLogFile(fileName);

            bool firstWrite = !File.Exists(fileName);
            var traceListener = new TimeTextWriterTraceListener(fileName);
            //TraceOptions.DateTime,在以Trace.TraceError、Trace.TraceWarning等方式输出信息时,全加入日期信息
            traceListener.TraceOutputOptions |= TraceOptions.DateTime;
            Trace.Listeners.Add(traceListener);
            Trace.AutoFlush = true;

            //初始日志
            if (firstWrite)
                Trace.WriteLine(string.Format("OS Version: {0}", Environment.OSVersion.ToString()));
            Trace.WriteLine("\r\n" + new string('-', 64));
            Trace.WriteLine(string.Format("Program Start: {0} v{1}", Application.ProductName, Application.ProductVersion));
        }

        private static void CheckAndCleanLogFile(string fileName)
        {
            if (!File.Exists(fileName))
                return;

            try
            {
                var fi = new FileInfo(fileName);
                if (fi.Length > MAX_LOG_SIZE)
                    File.Delete(fileName);
            }
            catch
            {
            }
        }

        private class TimeTextWriterTraceListener : TextWriterTraceListener
        {
            public TimeTextWriterTraceListener(string fileName)
                : base(fileName)
            {
            }

            public override void WriteLine(string message)
            {
                if (string.IsNullOrEmpty(message))
                    return;

                if ((this.TraceOutputOptions & TraceOptions.DateTime) == TraceOptions.DateTime && !message.Contains("--------"))
                    base.Write(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " ");
                base.WriteLine(message);
            }
        }
    }

使用方法:

string logFile = Path.ChangeExtension(Process.GetCurrentProcess().MainModule.FileName, ".log");
LogHelper.Init(logPath);

那么,程序中所有Trace.xxx输出的信息,就都会被记录下来。

posted on 2019-01-05 11:37  楚人无衣  阅读(1442)  评论(0编辑  收藏  举报