Clearing an Enterprise Library Logging log file - c#

How would I delete / clear / wipe / overwrite a log file being written through EL6 logging. I am using a logwriter instance to write to a log file that needs to be overwritten every cycle as my program runs in a continuous loop. I will be writing values then overwriting as new values come through.

There may be other/better ways to attack this, but I was able to clear the log file by temporarily repointing the static LogWriter to a temp file, clearing the log with simple File I/O, and then reconnecting the original LogWriter.
I wrote up a simple C# Console App to demonstrate. There are some hard-coded references to the log file configuration in App.config that could probably be cleaned up by using the ConfigurationSourceBuilder, but hopefully this can get you started.
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>

Related

Missing entries in user.config after decryption/encryption

I like to store a username and password to the user.config in my C# .net5 program. I don't want to store the password direct and I decided to decrypt the userSettings section.
After decryption parts of the file are missing.
Orginal user.config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System.Configuration.ConfigurationManager, Version=5.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51" >
<section name="FileUploader.Properties.Settings" type="System.Configuration.ClientSettingsSection, System.Configuration.ConfigurationManager, Version=5.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51" allowLocation="true" allowDefinition="Everywhere" allowExeDefinition="MachineToLocalUser" overrideModeDefault="Allow" restartOnExternalChanges="true" requirePermission="false" />
</sectionGroup>
</configSections>
<userSettings>
<FileUploader.Properties.Settings>
<setting name="UserName" serializeAs="String">
<value>user</value>
</setting>
<setting name="Password" serializeAs="String">
<value>xyz</value>
</setting>
</FileUploader.Properties.Settings>
</userSettings>
</configuration>
After encryption:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System.Configuration.ConfigurationManager, Version=5.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51" >
<section name="FileUploader.Properties.Settings" type="System.Configuration.ClientSettingsSection, System.Configuration.ConfigurationManager, Version=5.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51" allowLocation="true" allowDefinition="Everywhere" allowExeDefinition="MachineToLocalUser" overrideModeDefault="Allow" restartOnExternalChanges="true" requirePermission="false" />
</sectionGroup>
</configSections>
<userSettings>
<FileUploader.Properties.Settings configProtectionProvider="DataProtectionConfigurationProvider">
<EncryptedData>
<CipherData>
<CipherValue>AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAA4LmAfRMCHUeURwT1gTPd8AQAAAACAAAAAAAQZgAAAAEAACAAAADnR+uFolwsH4gkWI6vd46HNUxBv7ZfrQJmHe0q/zz8jAAAAAAOgAAAAAIAACAAAABlvfcY6M7JdG2dKIXO7cUUO9ui3Nou40CjMolKyJW7zgACAAAL5H+KJFPGoyugYYFDkZsV7GjXoaO+r8/z01/OiqVYXw80dCUIKje2g0tgizNrB/rAUmSg/uDPBx1yj3TAJ5aXf+fRxJaspf1jjr+QIaSJShnpy1sEjjpbUUn9+BVCYSJH8d4Ysj2JP1wvM5mgFBlFUcCLhHO+FputK3XpihAZCXeOddjNw2xYIQu4pmenLBiW6+fRUpINmNan/exQvHOWfwXuoZvqUli1hv+29qTuh/eJuPJQoyQSKrZ1A6Ie8aG2dsgQDvnVFEkt8cChkTn/TIc2Dk1uSDrsIYj/Ah8g1T5bE3PvWAYv67vtEfKbwBrqig+3HOSltZayVWyd2Y7iDS15Qk763ipiaBM64zhs/g4koQWpH1kAkfqgW3ibYAJEsk1a/K0Dd1Q2muxo0fsk1DfNYJIhFS8eAIuABlF6NAF5AT5hYyIOWVGjaquEP/aqzepCjEwkoLgD003qMISK7W6EAugSbWCRTwcMcKxZD3tHTmNLzZk+g8C7XpaWOk0xyODi5+mVXI8zg7NIGYo34JPado8l0p0Qd0gx15PwtZNHj0k9o6rieTgWjJEqf52ng70DNySsSX3jfyW91ArslcMLqO1qpbSFuIt0LeIswSxoR/etNM+GoGUjRW7t1OKGLcV5Wi8k0QdheXhxo6Hvq2/nv9iFYJxqgwoN6v1N0kAAAAACcCtrS9KBGCutdHdYddlimN5cPb8+X/snuKEgu63fi4TE2VSei4R0WqjeC22JIFn3HqPIzWb9Kd9pPDJCWQz7</CipherValue>
</CipherData>
</EncryptedData>
</FileUploader.Properties.Settings>
</userSettings>
</configuration>
After decryption:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System.Configuration.ConfigurationManager, Version=5.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51" >
<section name="FileUploader.Properties.Settings" type="System.Configuration.ClientSettingsSection, System.Configuration.ConfigurationManager, Version=5.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51" allowLocation="true" allowDefinition="Everywhere" allowExeDefinition="MachineToLocalUser" overrideModeDefault="Allow" restartOnExternalChanges="true" requirePermission="false" />
</sectionGroup>
</configSections>
<userSettings>
<FileUploader.Properties.Settings>
<setting name="" serializeAs="String">
<value>xyz</value>
</setting>
</FileUploader.Properties.Settings>
</userSettings>
</configuration>
There is only the last entry and the name of the entry is missing. If I switch the order in the original file, I get "user" as the value.
The code to decrypt/encrypt (more or less a copy of an msdn example):
private void ProtectSettings()
{
// Get the application configuration file.
System.Configuration.Configuration config =
ConfigurationManager.OpenExeConfiguration(
ConfigurationUserLevel.PerUserRoamingAndLocal);
// Define the Rsa provider name.
string provider = "DataProtectionConfigurationProvider";
string section = "userSettings/" + System.Reflection.Assembly.GetExecutingAssembly().GetName().Name + ".Properties.Settings";
// Get the section to protect.
ConfigurationSection connStrings = config.GetSection(section);
if (connStrings != null)
{
if (!connStrings.SectionInformation.IsProtected)
{
if (!connStrings.ElementInformation.IsLocked)
{
// Protect the section.
connStrings.SectionInformation.ProtectSection(provider);
connStrings.SectionInformation.ForceSave = true;
config.Save(ConfigurationSaveMode.Full);
Debug.WriteLine("Section {0} is now protected by {1}",
connStrings.SectionInformation.Name,
connStrings.SectionInformation.ProtectionProvider.Name);
}
else
Debug.WriteLine(
"Can't protect, section {0} is locked",
connStrings.SectionInformation.Name);
}
else
Debug.WriteLine(
"Section {0} is already protected by {1}",
connStrings.SectionInformation.Name,
connStrings.SectionInformation.ProtectionProvider.Name);
}
else
Debug.WriteLine("Can't get the section {0}", section);
}
private static void UnProtectSettings()
{
// Get the application configuration file.
System.Configuration.Configuration config =
ConfigurationManager.OpenExeConfiguration(
ConfigurationUserLevel.PerUserRoamingAndLocal);
string section = "userSettings/" + System.Reflection.Assembly.GetExecutingAssembly().GetName().Name + ".Properties.Settings";
// Get the section to unprotect.
ConfigurationSection connStrings = config.GetSection(section);
if (connStrings != null)
{
if (connStrings.SectionInformation.IsProtected)
{
if (!connStrings.ElementInformation.IsLocked)
{
// Unprotect the section.
connStrings.SectionInformation.UnprotectSection();
connStrings.SectionInformation.ForceSave = true;
config.Save(ConfigurationSaveMode.Full);
Debug.WriteLine("Section {0} is now unprotected.",
connStrings.SectionInformation.Name);
}
else
Debug.WriteLine(
"Can't unprotect, section {0} is locked",
connStrings.SectionInformation.Name);
}
else
Debug.WriteLine(
"Section {0} is already unprotected.",
connStrings.SectionInformation.Name);
}
else
Debug.WriteLine("Can't get the section {0}", section);
}
After playing around with this for a while, I discovered that the issue comes from the ConfigurationSaveMode.Full option.
In both ProtectSettings() and UnProtectSettings(), instead of
connStrings.SectionInformation.ForceSave = true;
config.Save(ConfigurationSaveMode.Full);
simply use:
config.Save();
I have no idea why that option leads to unwanted behavior.

Can't register listeners to System.Diagnostics.Tracing.EventSource

I have a component that is used by different applications.
In this component we might need logging so I thought I'd use an EventSource.
The component is netstandard2.0, the application using the component is .NET Framework 4.6.1.
This is what I have so far in my component:
public class XEvents
{
public const int BeforeSendingRequest = 1;
public const int AfterSendingRequest = 2;
}
[EventSource(Name = "XEventSource")]
public class XEventSource : EventSource
{
public static XEventSource Log = new XEventSource();
[Event(XEvents.BeforeSendingRequest, Message = "Request: {0}", Level = EventLevel.Verbose, Keywords = EventKeywords.WdiDiagnostic)]
public void BeforeSendingRequest(string request) { if (IsEnabled()) WriteEvent(XEvents.BeforeSendingRequest, request); }
[Event(XEvents.AfterSendingRequestToCsam, Message = "Response: {0}", Level = EventLevel.Verbose, Keywords = EventKeywords.WdiDiagnostic)]
public void AfterSendingRequest(string response) { if (IsEnabled()) WriteEvent(XEvents.AfterSendingRequest, response); }
}
And in the application I added the following to the app.config:
<system.diagnostics>
<sources>
<source name="NamespaceOfEventSource.XEventSource" switchValue="Verbose">
<listeners>
<add name="XEventSourceListener" />
</listeners>
</source>
</sources>
<sharedListeners>
<add name="XEventSourceListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="X.log" traceOutputOptions="ProcessId, DateTime" />
</sharedListeners>
<trace autoflush="true" />
</system.diagnostics>
But when I run the application there is no X.log inside the bin folder.
When I debug to the eventsource of the component I see that Enabled() returns false.
I suspect the listeners arent beeing bound to the EventSource. But I don't really see what I'm doing wrong.
Thanks in advance for any information you can give me!
I ended up using TraceSource instead of EventSource.
https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.tracesource?view=netcore-3.1

Trace & Log to file using TraceSource

I'm working on ASP.Net MVC web app, using System.Diagnostics.TraceSource to trace and log to file. Added following to web.config
<system.diagnostics>
<trace autoflush="false" indentsize="4"></trace> // what's this for?
<sources>
<source name ="WebAppLog">
<listeners>
<add name="FileLog" type="System.Diagnostics.TextWriterTraceListener" initializeData="PartialView_WebApp.log" traceOutputOptions="DateTime,ThreadId,ProcessId,Timestamp,LogicalOperationStack,Callstack">
<filter initializeData="All" type="System.Diagnostics.EventTypeFilter"/>
</add>
<remove name="Default"/>
</listeners>
</source>
</sources>
</system.diagnostics>
Added Log.cs to application to log mesages to file.
public class Log
{
static TraceSource source = new TraceSource("WebAppLog");
public static void Message(TraceEventType traceEventType, string message)
{
short id;
switch (traceEventType)
{
case TraceEventType.Information:
id = 3;
break;
case TraceEventType.Verbose:
id = 4;
break;
default:
id = -1;
break;
}
source.TraceEvent(traceEventType, id, message);
source.Flush();
}
}
Home controller.cs
public ActionResult Index()
{
try
{
Log.Message(System.Diagnostics.TraceEventType.Information, "Index Action Start");
// Do work
Log.Message(System.Diagnostics.TraceEventType.Information, "Index Action End");
return View();
}
catch (Exception ex)
{
throw;
}
}
After executing, i'm able to generate log file but couldn't write anything, always the file size is 0 bytes. What could be the possible mistake.?
The Switch on a TraceSource determines whether any output gets generated.
By default, if it is not configured, there will be no output.
The value for the Switch matches the log levels that should appear in the output.
It can be set via code:
static TraceSource source = new TraceSource("WebAppLog");
source.Switch.Level = SourceLevels.Verbose;
Or via configuration, which is more flexible.
Your configuration will look like:
<system.diagnostics>
<trace autoflush="false" indentsize="4"></trace>
<sources>
<source name ="WebAppLog" switchName="mySwitch">
<listeners>
<add name="FileLog" type="System.Diagnostics.TextWriterTraceListener" initializeData="c:\tmp\trace.log" traceOutputOptions="DateTime,ThreadId,ProcessId,Timestamp,LogicalOperationStack,Callstack">
<filter initializeData="All" type="System.Diagnostics.EventTypeFilter"/>
</add>
<remove name="Default"/>
</listeners>
</source>
</sources>
<switches>
<add name="mySwitch" value="Verbose" />
</switches>
</system.diagnostics>
Regarding your question about
<trace autoflush="false" indentsize="4"></trace>
With autoflush=true you don't have to call source.Flush() explicitly.
The indentsize gets applied in the log output, notice the leading whitespace starting from line 2 in the output fragment below.
WebAppLog Information: 3: Index Action Start
ProcessId=7416
LogicalOperationStack=
ThreadId=1

unable to save log into windows azure table storage?

I have used following code to save trace log into table storage.
I'm using windows azure skd version 2.2
System.Diagnostics.Trace.TraceError("START Log");
also added listener in web.config
<system.diagnostics>
<trace>
<listeners>
<add type="Microsoft.WindowsAzure.Diagnostics.DiagnosticMonitorTraceListener, Microsoft.WindowsAzure.Diagnostics, Version=2.2.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" name="AzureDiagnostics">
<filter type="" />
</add>
</listeners>
</trace>
</system.diagnostics>
also added code in webrole.cs
public override bool OnStart()
{
StartDiagnostics();
return base.OnStart();
}
private void StartDiagnostics()
{
DiagnosticMonitorConfiguration dmc = DiagnosticMonitor.GetDefaultInitialConfiguration();
TimeSpan tsOneMinute = TimeSpan.FromMinutes(1);
// Transfer logs to storage every minute
dmc.Logs.ScheduledTransferPeriod = tsOneMinute;
// Transfer verbose, critical, etc. logs
dmc.Logs.ScheduledTransferLogLevelFilter = LogLevel.Information;
// Start up the diagnostic manager with the given configuration.
try
{
DiagnosticMonitor.Start("Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString", dmc);
}
catch (Exception exp)
{
}
}
Still getting error : 500 internal server error

Custom Config section in App.config C#

I'm a quite beginner with config sections in c#
I want to create a custom section in config file. What I've tried after googling is as the follows
Config file:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="MyCustomSections">
<section name="CustomSection" type="CustomSectionTest.CustomSection,CustomSection"/>
</sectionGroup>
</configSections>
<MyCustomSections>
<CustomSection key="Default"/>
</MyCustomSections>
</configuration>
CustomSection.cs
namespace CustomSectionTest
{
public class CustomSection : ConfigurationSection
{
[ConfigurationProperty("key", DefaultValue="Default", IsRequired = true)]
[StringValidator(InvalidCharacters = "~!##$%^&*()[]{}/;'\"|\\", MinLength = 1, MaxLength = 60)]
public String Key
{
get { return this["key"].ToString(); }
set { this["key"] = value; }
}
}
}
When I use this code to retrieve Section I get an error saying configuration error.
var cf = (CustomSection)System.Configuration.ConfigurationManager.GetSection("CustomSection");
What am I missing?
Thanks.
Edit
What I need ultimately is
<CustomConfigSettings>
<Setting id="1">
<add key="Name" value="N"/>
<add key="Type" value="D"/>
</Setting>
<Setting id="2">
<add key="Name" value="O"/>
<add key="Type" value="E"/>
</Setting>
<Setting id="3">
<add key="Name" value="P"/>
<add key="Type" value="F"/>
</Setting>
</CustomConfigSettings>
App.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="customAppSettingsGroup">
<section name="customAppSettings" type="System.Configuration.AppSettingsSection, System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</sectionGroup>
</configSections>
<customAppSettingsGroup>
<customAppSettings>
<add key="KeyOne" value="ValueOne"/>
<add key="KeyTwo" value="ValueTwo"/>
</customAppSettings>
</customAppSettingsGroup>
</configuration>
Usage:
NameValueCollection settings =
ConfigurationManager.GetSection("customAppSettingsGroup/customAppSettings")
as System.Collections.Specialized.NameValueCollection;
if (settings != null)
{
foreach (string key in settings.AllKeys)
{
Response.Write(key + ": " + settings[key] + "<br />");
}
}
Try using:
var cf = (CustomSection)System.Configuration.ConfigurationManager.GetSection("MyCustomSections/CustomSection");
You need both the name of the section group and the custom section.
Highlight ConfigurationSection press F1,
You will see that the implementation on the MSDN website overrides a property called "Properties" which returns a "ConfigurationPropertyCollection", as your properties have a matching attribute of that type you should be able to populate this collection with your properties if not wrap them in the same way the MS guys have.

Categories