如何使用App.config和System.Diagnostics动态设置日志文件?

Sim*_*ton 4 c# logging app-config system.diagnostics

当我看到一篇文章时,我正在寻找一种解决方案,为我的最新项目提供日志记录(http://www.daveoncsharp.com/2009/09/create-a-logger-using-the-trace-listener-in- csharp /)谈到使用System.Diagnostics和App.config通过Trace方法进行记录.我能够成功实现类和App.config,但我真的希望能够动态分配日志文件的值/位置(在initializeData内),我不知道如何做到这一点.如果您有任何建议,请随时发布!

App.config中:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.diagnostics>
    <trace autoflush="true" indentsize="4">
      <listeners>
        <add name="myListener" 
             type="System.Diagnostics.TextWriterTraceListener" 
             initializeData="fileSizeThreshold=512, fileSizeUnit=kilobytes, 
             fileAgeThreshold=1, fileAgeUnit=months, fileNameTemplate='{0}\MyApp-{1:MMM-yy}.log'"/>
        <remove name="Default" />
      </listeners>
    </trace>
  </system.diagnostics>
</configuration>
Run Code Online (Sandbox Code Playgroud)

记录器类:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;


namespace MyCurrentProject
{
    class Logger
    {
        public void Error(string module, string message)
        {
            WriteEntry(message, "ERROR:", module);
        }

        public void Error(Exception ex, string module)
        {
            WriteEntry(ex.Message, "ERROR:", module);
        }

        public void Warning(string module, string message)
        {
            WriteEntry(message, "WARNING:", module);
        }

        public void Info(string module, string message)
        {
            WriteEntry(message, "INFO:", module);
        }

        private void WriteEntry(string message, string type, string module)
        {
            Trace.WriteLine(
                    string.Format("{0} {1} [{2}] {3}",
                                  DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                                  type,
                                  module,
                                  message));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

RE:很抱歉不清楚...为了清楚,我需要保存日志文件输出的文件路径来动态设置.我想要保存到%AppData%中的位置的路径.我对配置的问题是,一旦我设置'initializeData'的值,我就找不到改变或动态设置/重置该值的方法.说实话......在这一点上,我只想要一个有效的解决方案,并允许我管理日志文件的位置.

Mat*_*tin 6

这是一个使用Systems.Diagnostics的工作示例,它比非基类库有两个优点.始终允许(在大型组织中),始终可用,并且在开发人员熟悉基类库的情况下,下一批维护开发人员将听说过它.

using System.Diagnostics;

namespace DynamicTraceLog
{
    class Program
    {
        static void Main(string[] args)
        {
            //Use TraceSource, not Trace, they are easier to turn off
            TraceSource trace = new TraceSource("app");
            //SourceSwitches allow you to turn the tracing on and off.
            SourceSwitch level =new SourceSwitch("app");
            //I assume you want to be dynamic, so probalby some user input would be here:
            if(args.Length>0 && args[0]=="Off")
                level.Level= SourceLevels.Off;
            else
                level.Level = SourceLevels.Verbose;
            trace.Switch = level;
            //remove default listner to improve performance
            trace.Listeners.Clear();
            //Listeners implement IDisposable
            using (TextWriterTraceListener file = new TextWriterTraceListener("log.txt"))
            using (ConsoleTraceListener console = new ConsoleTraceListener())
            {
                //The file will likely be in /bin/Debug/log.txt
                trace.Listeners.Add(file);
                //So you can see the results in screen
                trace.Listeners.Add(console);
                //Now trace, the console trace appears immediately.
                trace.TraceInformation("Hello world");
                //File buffers, it flushes on Dispose or when you say so.
                file.Flush();
            }
            System.Console.ReadKey();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Re:如何格式化输出 尝试使用Systems.Diagnostics类实现模板化跟踪格式化/输出的跟踪侦听器中的任何一个:http: //essentialdiagnostics.codeplex.comhttp://ukadcdiagnostics.codeplex.com/ Systems.诊断程序不提供标准令牌的任何特定格式化或输出.