如何删除/清除/擦除/覆盖通过EL6日志记录写入的日志文件。我正在使用一个logwriter实例写入一个日志文件,当我的程序在一个连续的循环中运行时,每个循环都需要覆盖它。当新值出现时,我将写入值然后覆盖。
答案 0 :(得分:0)
可能有其他/更好的方法来攻击它,但我能够通过暂时将静态LogWriter重新分配到临时文件来清除日志文件,使用简单的文件I / O清除日志,然后重新连接原始LogWriter
我写了一个简单的C#Console应用程序来演示。 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 & 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 & Warnings" />
</specialSources>
</loggingConfiguration>
</configuration>