动态日志框架或技术

时间:2012-02-20 08:50:12

标签: c# dynamic logging

我想要一些具有特定功能的日志记录机制或框架。我已经使用

在我的应用程序(dll库)中登录了
Log.WriteLine("{0}.{1}()", System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType, System.Reflection.MethodInfo.GetCurrentMethod().Name);

其中Log是静态类,具有使用Streamwriter

写入文件的功能
public void LogWriteLine(string text, params object[] args) {
  lock (this) {
      StreamWriter log = new StreamWriter(logFile, true);
      if (log != null) {
        log.WriteLine("{0:yyyy-MM-dd HH:mm:ss} {1}", DateTime.Now, String.Format(text, args));
        log.Flush();
        log.Close();
      }
  }
}

我的问题是,我的应用程序中没有Log.WriteLine调用,只是在应用程序的特定部分,因为它会创建非常大的文件。但现在,我构建我的应用程序,并将其发布给开发人员,他们已经工作了几天。之后他们发给我错误,但在我的版本中,错误已不再存在(应用程序上的开发仍在继续,因此可以修复)。

所以我想在应用程序中有一些设置文件,告诉应用程序我需要更多日志,并能够运行测试版的应用程序,而无需使用不同的记录器设置重建它。

简而言之:我如何告诉应用程序形成一些设置文件,仅记录特定的内容,例如只有一个类或一个方法?

4 个答案:

答案 0 :(得分:2)

您可以查看.NET跟踪。这是一篇非常简短的介绍(1页):

http://www.codeguru.com/csharp/.net/net_debugging/tracing/article.php/c5919

答案 1 :(得分:2)

我会看看Log4Net。 Log4Net提供日志级别的App.Config配置,重定向到多个输出,允许同步或异步(缓冲)日志记录。

这里有一篇好文章:http://www.codeproject.com/Articles/14819/How-to-use-log4net

我写了一篇文章,介绍如何使用Regex查找和替换来整改应用程序中的日志记录以使用其他语法。请参阅this previous answerthis blog article

答案 2 :(得分:1)

您可以使用log4net 记录器过滤器。见introduction article

答案 3 :(得分:1)

我需要做类似的事情。这就是我做到的。

我创建了一个类别类,并在初始化日志记录对象时将其用作参数。

/// <summary>
/// Category object for logging
/// </summary>
public class Category
{
    #region Private Members
    private bool    m_active;
    private string  m_name;
    private bool    m_excludeFromLogFile = false;
    #endregion

    /// <summary>
    /// Create a category and add it to the Logging category list
    /// </summary>
    /// <param name="name">The Name of the category</param>
    /// <param name="active">The active state of the category</param>
    /// <param name="exclude">If true any messages for this category will not be written to the log file</param>
    /// <param name="addedToList">If true then the new category will be added to the logging category list</param>
    public Category(string name, bool active, bool exclude, bool addedToList)
    {
        m_name = name;
        m_active = active;
        m_excludeFromLogFile = exclude;

        if(addedToList)
        {
            Log.GetInstance().AddCategory(this);
        }
    }

    #region Public Accessor Methods
        // .. Add accessors as required 
    #endregion
}

正如你可以通过“Log.GetInstance()。AddCategory(this);”这一行看到的那样,我的日志对象是一个单例。

单身人士,有一些添加和删除类别的方法

/// <summary>
/// Add a new category to the list of available categories
/// </summary>
/// <param name="newCat">The category object to add</param>
public void AddCategory( Category newCat )
{
    // Ensure that the category doesn't already exist in the list
    if( this.m_CategoryList.Contains( newCat ) == false )
    {
        // Add the new category to the list
        this.m_CategoryList.Add( newCat );
    }
}

/// <summary>
/// Remove a category to the list of available categories
/// </summary>
/// <param name="catName">The name of the category to be removed</param>
public void RemoveCategory( string catName )
{
    Category toRemove = null;

    // Iterate through the categories looking for a match
    foreach( Category cat in this.m_CategoryList)
    {
        // Compare the category names (case insensitive)
        if( cat.Name.ToUpper() == catName.ToUpper() )
        {
            // Assign the category to remove to a local variable and exit the loop
            toRemove = cat;
            break;
        }
    }

    // Remove the category if it's been located
    if( toRemove != null )
    {
        this.m_CategoryList.Remove( toRemove );
    }
}

处理日志事件时,现在只是检查类别的活动状态以查看是否需要该消息。

/// <summary>
/// Create a log entry in the log file and then Fire an event for the log message to be handled
/// </summary>
/// <param name="category">The category to log the message against</param>
/// <param name="args"> Message logging arguments used by the event</param>
public void WriteLine(Category category, MessageEventArgs args)
{
    // Ensure that the category specified exists in the array list
    if( this.m_CategoryList.Contains( category ) )
    {
        // Ensure the category is active 
        if(category.Active == true)
        {
            if(!category.ExcludeFromLogFile)
            {
                // Try and log the message to the log file
                this.WriteLineToFile( category, args );
            }

            // Ensure an event handler has been assigned
            if(MessageEvent != null)
            {
                // This message event is handled by the UI thread for updating screen components.
                MessageEvent(category, args);
            }
        }
    }
}

最后,如果您希望在屏幕上显示消息,则需要在UI线程中处理消息事件。以下是我的一个列表视图组件中的示例...

private void ListViewLogging_MessageEvent(Category category, MessageEventArgs args)
{
    // Ensure the event was received in the UI thread
    if(this.InvokeRequired)
    {
        if(args.Message != null)
        {
            // We aren't in the UI thread so reFire the event using the main thread
            this.BeginInvoke(new MessageReceivedDelegate(this.ListViewLogging_MessageEvent), new object[]{category,args});
        }
    }
    else
    {
        // We are currently in the main thread.
        // Lock so no other thread can be handled until event processing has been finished
        lock(this)
        {
            // Create a new ListView item for the new message 
            ListViewItem newEntry = null;;

            // Determine the category type
            switch( category.Name )
            {
                case "Serious":
                {
                    // Serious error detected
                    if( args.Message.Length > 0 )
                    {
                        newEntry = new ListViewItem( new string[]{category.Name, args.Occurred.ToLongTimeString(), args.Message} );
                        newEntry.BackColor = Color.Red;
                    }
                    break;
                }
                case "Warning":
                {
                    // Warning detected.
                    if( args.Message.Length > 0 )
                    {
                        newEntry = new ListViewItem( new string[]{category.Name, args.Occurred.ToLongTimeString(), args.Message} );
                        newEntry.BackColor = Color.Orange;
                    }
                    break;
                }
                case "Progress":
                {
                    // If a message has been specified, log it
                    if( args.Message.Length > 0 )
                    {
                        newEntry = new ListViewItem( new string[]{"", args.Occurred.ToLongTimeString(), args.Message} );
                    }
                    break;
                }
                case "Debug":
                {
                    // Just a standard Debug event so just display the text on the screen
                    if( args.Message.Length > 0 )
                    {
                        newEntry = new ListViewItem( new string[]{category.Name, args.Occurred.ToLongTimeString(), args.Message} );
                        newEntry.BackColor = Color.LightGreen;
                    }
                    break;
                }
                case "Info":
                default:
                {
                    // Just a standard event so just display the text on the screen
                    if( args.Message.Length > 0 )
                    {
                        newEntry = new ListViewItem( new string[]{category.Name, args.Occurred.ToLongTimeString(), args.Message} );
                    }
                    break;
                }
            }
            // Add the item if it's been populated
            if( newEntry != null )
            {
                this.Items.Add( newEntry );
                this.EnsureVisible( this.Items.Count-1 );
            }
        }
    }
}