繁体   English   中英

清除企业库记录日志文件

[英]Clearing an Enterprise Library Logging log file

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

可能有其他/更好的方法来进行攻击,但是我能够通过临时将静态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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM