使用 Trace 将日志输入到文件中

工具没有好坏,只有适不适用。由于项目中用 Log4Net 过重,所以使用 Trace 代替了 Log4Net 输入一些简单的日志信息;

自定义监听文件

using System;
using System.Configuration;
using System.Diagnostics;
using System.IO;

namespace Iron.Common
{
    /// 
    /// 错误日志自定义监听
    /// 
    public class LogHelper : TraceListener
    {
        /// 
        /// 获取日志输出级别
        /// 
        public static TraceSwitch TraceSwitch = new TraceSwitch("TraceLevel", string.Empty);

        public LogHelper()
        {
            if (TraceSwitch.Level == TraceLevel.Off)
            {
                TraceSwitch.Level = TraceLevel.Error;
            }
        }

        /// 
        /// 如果AppConfig 里面有配置就读配置文件里面的路径,否则取当前exe目录
        /// 
        private string FilePath
        {
            get
            {
                string directPath = ConfigurationManager.AppSettings["LogFilePath"];    //获得文件夹路径
                if (string.IsNullOrEmpty(directPath))
                {
                    directPath = System.Environment.CurrentDirectory + @"\logs\";
                }
                directPath = directPath.Trim();
                if (!Directory.Exists(directPath))   //判断文件夹是否存在,如果不存在则创建
                {
                    Directory.CreateDirectory(directPath);
                }
                return string.Format(@"{0}\{1}_{2}.log", directPath, DateTime.Now.ToString("yyyy.MM.dd"), System.Diagnostics.Process.GetCurrentProcess().ProcessName);
            }
        }


        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 TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string message)
        {
            if ((int)TraceSwitch.Level + 1 >= (int)eventType)
                base.TraceEvent(eventCache, source, eventType, id, message);
        }


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

            if (string.IsNullOrEmpty(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);
        }
    }
}

测试代码

private static void Main(string[] args)
{
    //删除初始化代码,改为在配置文件中设置--【此代码只要在程序运行时初始化一次】
    Trace.Listeners.Clear();  //清除系统监听器 (就是输出到Console的那个)
    Trace.Listeners.Add(new LogHelper()); //添加 自定义Trace 实例

    
    try
    {
        int a = 10;
        int b = 0;
        var sd = a / b;
    }
    catch (Exception ex)
    {
        Trace.TraceError("{0}\r\n{1}", ex.Message, ex.StackTrace);
    }
    return;
}

输出日志为:

ODAS.exe Error: 0 : 2017-08-24 00:05:28    Attempted to divide by zero.
   at Ironfo.Test.Views.Demo01.List.ControlRefresh(Object sender, RoutedEventArgs routedEventArgs) in C:\Code\ODAS\Views\Demo01\List.xaml.cs:line 43

如果要修改日志的级别、修改日志输出目录,可修改配置文件:

<configuration>
   
  <system.diagnostics>
    <switches>
      
      <add name="TraceLevel" value="Info"/>
    switches>
  system.diagnostics>
  <appSettings> 
    
    
  appSettings>
configuration>

注意:Trace.Write() 等日志输出方法,不受等级的限制

你可能感兴趣的:(使用 Trace 将日志输入到文件中)