2016-08-25 11 views
0

EL6ログによって書き込まれるログファイルを削除/消去/消去/上書きする方法を教えてください。私はプログラムが連続したループで実行されるたびに、ログファイルインスタンスにログファイルに書き込み、毎回上書きする必要があります。私は値を書き、新しい値が来ると上書きします。エンタープライズライブラリのログ記録ログファイル

答えて

0

これを攻撃する方法は他にもあるかもしれませんが、静的なLogWriterを一時的に一時ファイルに置き換え、簡単なファイルI/Oでログを消去して元のファイルに再接続することでログファイルを消去できましたLogWriter。

シンプルなC#コンソールアプリを書いて書いてみました。おそらくConfigurationSourceBuilderを使用してクリーンアップすることができるApp.configのログファイル構成へのハードコーディングされた参照がいくつかありますが、うまくいけばこれを開始することができます。

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> 
関連する問題