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

标签 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 内),但我不知道如何去做.如果您有任何建议,请随时发表!

应用程序配置:

<?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>

记录器类:

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));
        }
    }
}

RE: 抱歉没说清楚...只是说清楚,我需要动态设置日志文件输出保存到的文件路径。我想要保存到 %AppData% 中某个位置的路径。我在配置中遇到的问题是,一旦我设置了“initializeData”的值,我就无法找到更改或动态设置/重置该值的方法。说实话...此时我只想要一个可行的解决方案,并允许我管理日志文件的位置。

最佳答案

这是一个使用 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();
        }
    }
}

回复:如何格式化输出 对于使用 Systems.Diagnostics 类实现模板化跟踪格式化/输出的跟踪监听器,请尝试使用这两种方法之一: http://essentialdiagnostics.codeplex.comhttp://ukadcdiagnostics.codeplex.com/ Systems.Diagnostics 不提供标准 token 的任何特定格式或输出。

关于c# - 如何使用 App.config 和 System.Diagnostics 动态设置日志文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12810475/

相关文章:

c# - 自动重构代码以避免无参数构造函数

c# - 如何从 lambda 返回 LinkedList 集合?

c# - 运行时本地化

c#-4.0 - 如何在 .net 4.0 中设置 configSection

c# - 从哈希字符串中获取原始密码

c# - 在 .NET 中发送和接收 UDP 数据包

logging - 如何使用 Enterprise Library Logging 仅编写消息以调试输出?

grails - Grails审核日志记录插件

apache - 使用 apache/wsgi 时在日志中没有任何痕迹的 503

c# - 应用程序目录中所有用户的可写 .config 文件?