如何使用的App.config和System.Diagnostics程序动态设置日志文件? [英] How to dynamically set log file using App.config and System.Diagnostics?

查看:991
本文介绍了如何使用的App.config和System.Diagnostics程序动态设置日志文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找一个解决方案,提供日志记录,以我的最新项目,当我读到一篇文章来(的 http://www.daveoncsharp.com/2009/09/create-a-logger-using-the-trace-listener-in-csharp/ )中谈到使用System.Diagnostics程序和App.config中通过跟踪方法记录。我能够成功地实现这两个类和App.config中,但我真的很想能够动态分配日志文件的值/位置(内initializeData),我没有一个线索如何做到这一点。 !如果您有任何建议,请随意张贴

I was looking for a solution to provide logging to my latest project when I came across an article ( http://www.daveoncsharp.com/2009/09/create-a-logger-using-the-trace-listener-in-csharp/ ) that talked about using System.Diagnostics and App.config to log via the Trace method. I was able to successfully implement both the class and the App.config but I'd really like to be able to dynamically assign the value/location (inside initializeData) of the log file and I don't have a clue how to do it. If you have any suggestions, please feel free to post!

App.config中:

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>



记录器类:

Logger Class:

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设置的值我无法找到一种方法来更改或动态设置/重置价值。说实话......在这一点上我只是想的作品,让我来管理日志文件的位置的解决方案。

RE: Sorry for not being clear... just to be clear, I need the file path that the log file output is save to to be dynamically set. I'd like the path to save to a location in %AppData%. The problem I had with the config was that once I set the value for 'initializeData' I couldn't find a way to change or dynamically set/reset that value. Truthfully... at this point I just want a solution that works and allows me to manage the location of the log file.

推荐答案

下面是使用Systems.Diagnostics,其中有超过非基类库两者的优点工作实例。它总是被允许(在大型组织中),始终可用,并且开发人员所熟悉的基类库的情况下,下一批的维护开发人员听说过吧。

Here is a worked example using Systems.Diagnostics, which has two advantages over non-base class libraries. It is always allowed (in large organizations), always available, and to the extent that developers are familiar with the base class library, the next batch of maintenance developers will have heard of it.

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



Re:怎么格式化输出
尝试这两种用于实现使用Systems.Diagnostics类模板跟踪格式化/输出跟踪侦听器:
http://essentialdiagnostics.codeplex.com
HTTP: //ukadcdiagnostics.codeplex.com/
Systems.Diagnostics不提供任何特定格式化或标准的令牌允许输出

Re: how to format the output Try either of these two for trace listeners that implement templated trace formating/output using Systems.Diagnostics classes: http://essentialdiagnostics.codeplex.com or http://ukadcdiagnostics.codeplex.com/ Systems.Diagnostics doesn't provide for any particular formating or outputing of standard tokens.

这篇关于如何使用的App.config和System.Diagnostics程序动态设置日志文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆