0
EL6 로깅을 통해 기록되는 로그 파일을 삭제/지우기/지우기/덮어 쓰는 방법은 무엇입니까? 내 프로그램이 연속 루프에서 실행될 때마다주기마다 덮어 써야하는 로그 파일에 로그 작성기 인스턴스를 사용하고 있습니다. 나는 새로운 가치가 올 때 값을 쓰고 덮어 쓰게 될 것입니다.엔터프라이즈 라이브러리 지우기 로그 파일 로깅
EL6 로깅을 통해 기록되는 로그 파일을 삭제/지우기/지우기/덮어 쓰는 방법은 무엇입니까? 내 프로그램이 연속 루프에서 실행될 때마다주기마다 덮어 써야하는 로그 파일에 로그 작성기 인스턴스를 사용하고 있습니다. 나는 새로운 가치가 올 때 값을 쓰고 덮어 쓰게 될 것입니다.엔터프라이즈 라이브러리 지우기 로그 파일 로깅
다른 공격 방법이나 더 좋은 방법이있을 수 있지만 일시적인 파일에 정적 LogWriter를 임시로 재촉하고 간단한 파일 I/O로 로그를 지운 다음 원본을 다시 연결하여 로그 파일을 지울 수있었습니다 LogWriter.
나는 간단한 C# Console App을 작성하여 시범을 보였습니다. 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>