• 用TextWriterTraceListener实现log文件记录 (转载)


     

    log4net之类3方组件确实很方便,但是想写个小小的demo之类的程序,有点用不起啊。

    微软自带的TraceListener要实现一个简易的日志帮助类还是很简单的,直接上代码,自己备用,也希望对同样烦恼的哥们有用:

    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";
    
            /// <summary>
            /// 默认Trace监听
            /// </summary>
            public static TextWriterTraceListener traceListener;
    
            /// <summary>
            /// 静态实例
            /// </summary>
            private static readonly Logger instance = new Logger();
            static Logger()
            {
                if (!Directory.Exists(RootPath))
                {
                    Directory.CreateDirectory(RootPath);
                }
    
                string logFile = RootPath.TrimEnd('\') + "\" + FileFormat;
                if (!File.Exists(logFile))
                {
                    File.Create(logFile);
                }
    
                Trace.AutoFlush = true;
                traceListener = new TextWriterTraceListener(logFile);
                Trace.Listeners.Add(traceListener);
            }
    
            /// <summary>
            /// log输出
         /// 当然这里可以自己随便扩充 /// </summary> /// <param name="msg"></param> public static void Log(string msg) { Trace.WriteLine(msg); } } }
  • 相关阅读:
    lvs实现故障转移(backup)
    shell计算
    CEGUI 聊天对话框
    SetRenderState 设置渲染状态【转】
    MFC 弹出对话框
    DrawIndexedPrimitive函数的详细解释【转】
    IDirect3DDevice9::Clear 【转】
    manifest 文件错误
    D3DXMatrixLookAtLH 【转】
    D3D中的网格(Mesh)
  • 原文地址:https://www.cnblogs.com/da6wei6/p/5147552.html
Copyright © 2020-2023  润新知