ShareThis

Logging using Enterprise Library - Change the log file Name and Path to the My Documents folder

When using Enterprise Library Logging Application Block as the logging tool, here is how to change the file path and the name of the trace file during run time. What I'm doing here is update the listener's "filename" (loggingConfiguration->listeners) in the App.config.


using System.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Logging.Configuration;

/// <summary>
/// Change the log file path and name.
/// </summary>
public void SetTraceLogPath()
{
// Log file path.
string logFilePath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) +
@"\MyLogs\" + DateTime.Now.ToString("yyyy-MM-dd") + ".log";

ConfigurationFileMap objConfigPath = new ConfigurationFileMap();

// App config file path.
string appPath = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
objConfigPath.MachineConfigFilename = appPath;

Configuration entLibConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

LoggingSettings loggingSettings = (LoggingSettings)entLibConfig.GetSection(LoggingSettings.SectionName);

TraceListenerData traceListenerData = loggingSettings.TraceListeners.Get("FlatFile TraceListener");
FlatFileTraceListenerData objFlatFileTraceListenerData = traceListenerData as FlatFileTraceListenerData;

objFlatFileTraceListenerData.FileName = logFilePath;

entLibConfig.Save();
}

Then I can use following method to log exceptions to the specified path. In this case log file will be created in the My Documents folder of the current user.


///<summary>
/// Log exceptions.
///</summary>
public void LogException(Exception ex)
{
string strMessage = string.Empty;
strMessage += ex.Message + "\r\n";
strMessage += ex.StackTrace;

LogEntry le = new LogEntry();
le.Categories.Add(Constants.LoggingCategory.Exception.ToString());
le.Severity = TraceEventType.Error;
le.Message = strMessage;
le.Title = ex.Message;
le.Priority = 1;

Logger.Write(le);
}

This is how my app.Config file looks. There should be a
FlatFileTraceListener configured as follows.

  <configSections>
<section name="loggingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
</configSections>
<loggingConfiguration name="Logging Application Block" tracingEnabled="true"
defaultCategory="General" logWarningsWhenNoCategoriesMatch="true">
<listeners>
<add fileName="trace.log" header="----------------------------------------"
footer="----------------------------------------" formatter=""
listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.FlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
traceOutputOptions="None" filter="All" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
name="FlatFile TraceListener" />
</listeners>
<formatters>
<add template="Timestamp: {timestamp}&#xD;&#xA;Message: {message}&#xD;&#xA;Category: {category}&#xD;&#xA;Priority: {priority}&#xD;&#xA;EventId: {eventid}&#xD;&#xA;Severity: {severity}&#xD;&#xA;Title:{title}&#xD;&#xA;Machine: {machine}&#xD;&#xA;Application Domain: {appDomain}&#xD;&#xA;Process Id: {processId}&#xD;&#xA;Process Name: {processName}&#xD;&#xA;Win32 Thread Id: {win32ThreadId}&#xD;&#xA;Thread Name: {threadName}&#xD;&#xA;Extended Properties: {dictionary({key} - {value}&#xD;&#xA;)}"
type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
name="Text Formatter" />
</formatters>
<categorySources>
<add switchValue="All" name="General">
<listeners>
<add name="FlatFile TraceListener" />
</listeners>
</add>
</categorySources>
<specialSources>
<allEvents switchValue="All" name="All Events" />
<notProcessed switchValue="All" name="Unprocessed Category" />
<errors switchValue="All" name="Logging Errors &amp; Warnings">
<listeners>
<add name="FlatFile TraceListener" />
</listeners>
</errors>
</specialSources>
</loggingConfiguration>

4 comments:

Anonymous said...

it doesn't update really at runtime the filename. the file is saved with default name, next time i'll write a log i have the new name.
how to update immediately the filename?

Anonymous said...

i have a same probleme
i traied your solution but it not work

Florin Berardi said...

in the app config, the name of <loggingConfiguration name="Logging Application Block" must be the same with the code at line 23 1st part of code of this blog.

satish dundigal said...

excellent. worked like a charm.! appreciated.