【问题标题】:Clearing an Enterprise Library Logging log file清除企业库日志记录日志文件
【发布时间】:2016-08-25 18:40:36
【问题描述】:

如何删除/清除/擦除/覆盖通过 EL6 日志记录写入的日志文件。我正在使用 logwriter 实例写入日志文件,当我的程序在连续循环中运行时,每个周期都需要覆盖该日志文件。我将写入值,然后在新值出现时覆盖。

【问题讨论】:

    标签: c# logging enterprise-library-6


    【解决方案1】:

    可能有其他/更好的方法来解决这个问题,但我能够通过暂时将静态 LogWriter 重新指向临时文件,使用简单的文件 I/O 清除日志,然后重新连接原始 LogWriter 来清除日志文件.

    我编写了一个简单的 C# 控制台应用程序来演示。 App.config 中有一些对日志文件配置的硬编码引用,可能可以通过使用 ConfigurationSourceBuilder 进行清理,但希望这可以帮助您入门。

    Programs.cs:

    using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
    using Microsoft.Practices.EnterpriseLibrary.Logging;
    
    using System;
    using System.Diagnostics;
    using System.IO;
    
    namespace LogFileClearance
    {
        public static class Marker
        {
            public static LogWriter customLogWriter { get; set; }
        }
    
        class Program
        {
            private static object _syncEventId = new object();
            private static object locker = new object();
            private static int _eventId = 0;
            private const string INFO_CATEGORY = "All Events";
    
            static void Main( string [] args )
            {
                InitializeLogger();
                Console.WriteLine( "Enter some input, <Enter> or q to quit, c to clear the log file" );
                string input = Console.ReadLine().ToUpper();
                while ( ! string.IsNullOrEmpty(input) && input != "Q" )
                {
                    Console.WriteLine( "You entered {0}", input );
                    if ( input == "C" )
                    {
                        ClearLog();
                    }
                    else
                    {
                        WriteLog( input );
                    }
    
                    Console.WriteLine( "Enter some input, <Enter> or q to quit, c to clear the log file" );
                    input = Console.ReadLine().ToUpper();
                }
            }
    
            private static int GetNextEventId()
            {
                lock ( _syncEventId )
                {
                    return _eventId++;
                }
            }
    
            public static void InitializeLogger()
            {
                try
                {
                    lock ( locker )
                    {
                        if ( Marker.customLogWriter == null )
                        {
                            var writer = new LogWriterFactory().Create();
                            Logger.SetLogWriter( writer, false );
                        }
                        else
                        {
                            Logger.SetLogWriter( Marker.customLogWriter, false );
                        }
                    }
                }
                catch ( Exception ex )
                {
                    Debug.WriteLine( "An error occurred in InitializeLogger: " + ex.Message );
                }
            }
    
            static internal void WriteLog( string message )
            {
                LogEntry logEntry = new LogEntry();
                logEntry.EventId =  GetNextEventId();
                logEntry.Severity = TraceEventType.Information;
                logEntry.Priority = 2;
                logEntry.Message = message;
    
                logEntry.Categories.Add( INFO_CATEGORY );
    
                // Always attach the version and username to the log message.
                // The writeLog stored procedure will parse these fields.
                Logger.Write( logEntry );
            }
    
            static internal void ClearLog()
            {
                string originalFileName = string.Format(@"C:\Logs\LogFileClearance.log");
                string tempFileName = originalFileName.Replace( ".log", "(TEMP).log" );
                var textFormatter = new FormatterBuilder()
                    .TextFormatterNamed( "Custom Timestamped Text Formatter" )
                    .UsingTemplate("{timestamp(local:MM/dd/yy hh:mm:ss.fff tt)} tid={win32ThreadId}: {message}");
    
                #region Set the Logging LogWriter to use the temp file
                var builder = new ConfigurationSourceBuilder();
    
                builder.ConfigureLogging()
                    .LogToCategoryNamed( INFO_CATEGORY ).WithOptions.SetAsDefaultCategory()
                        .SendTo.FlatFile( "Flat File Trace Listener" )
                        .ToFile(tempFileName);
    
                using ( DictionaryConfigurationSource configSource = new DictionaryConfigurationSource() )
                {
                    builder.UpdateConfigurationWithReplace(configSource);
                    Marker.customLogWriter = new LogWriterFactory(configSource).Create();
                }
                InitializeLogger();
                #endregion
    
                #region Clear the original log file
                if ( File.Exists(originalFileName) )
                {
                    File.WriteAllText(originalFileName, string.Empty);
                }
                #endregion
    
                #region Re-connect the original file to the log writer
                builder = new ConfigurationSourceBuilder();
    
                builder.ConfigureLogging()
                    .WithOptions.DoNotRevertImpersonation()
                    .LogToCategoryNamed( INFO_CATEGORY ).WithOptions.SetAsDefaultCategory()
                        .SendTo.RollingFile("Rolling Flat File Trace Listener")
                            .RollAfterSize(1000)
                        .FormatWith(textFormatter).WithHeader("").WithFooter("")
                        .ToFile(originalFileName);
    
                using ( DictionaryConfigurationSource configSource = new DictionaryConfigurationSource() )
                {
                    builder.UpdateConfigurationWithReplace( configSource );
                    Marker.customLogWriter = new LogWriterFactory( configSource ).Create();
                }
                InitializeLogger();
                #endregion
            }
        }
    }
    

    App.config:

    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
        <configSections>
            <section name="loggingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
        </configSections>
        <startup>
            <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
        </startup>
    
        <loggingConfiguration name="Logging Application Block" tracingEnabled="true" defaultCategory="" logWarningsWhenNoCategoriesMatch="true">
            <listeners>
                <add fileName="C:\Logs\LogFileClearance.log" footer="" formatter="Timestamped Text Formatter" 
                         header="" rollFileExistsBehavior="Increment" 
                         rollInterval="None" rollSizeKB="1000" timeStampPattern="yyyy-MM-dd" 
                         listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.RollingFlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" traceOutputOptions="None" filter="All" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.RollingFlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" 
                         name="Log File Listener" />
            </listeners>
            <formatters>
                <add template="{timestamp(local:MM/dd/yy hh:mm:ss tt)} tid={win32ThreadId}: {message}" type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" name="Timestamped Text Formatter" />
            </formatters>
            <categorySources>
                <add switchValue="Information" name="All Events">
                    <listeners>
                        <add name="Log File Listener" />
                    </listeners>
                </add>
                <add switchValue="Error" name="Logging Errors &amp; Warnings">
                    <listeners>
                        <add name="Log File Listener" />
                    </listeners>
                </add>
            </categorySources>
            <specialSources>
                <allEvents switchValue="Information" name="All Events" />
                <notProcessed switchValue="All" name="Unprocessed Category" />
                <errors switchValue="All" name="Logging Errors &amp; Warnings" />
            </specialSources>
        </loggingConfiguration>
    
    </configuration>
    

    【讨论】: