Get the file name of the current log file Enterprise Library 5.0

1.5k Views Asked by At

In MS Enterprise Library 5.0, Logging application block, at runtime, Can I get the name of the log file (Flat File Listener) to which the log is going to?

2

There are 2 best solutions below

0
On

Change the Config is no problem.
After Change the filename property aaa.log -> bbb.log the Logger not Write in the new Filename.
The changed config must saved/activated (?) or the Logger must new Initialized..!??

    IConfigurationSource configSource = ConfigurationSourceFactory.Create();
    var logSettings = configSource.GetSection(LoggingSettings.SectionName) as LoggingSettings;

    var rollFileTraceListener = logSettings.TraceListeners
        .FirstOrDefault(t => t is RollingFlatFileTraceListenerData && t.Name == "RollingFlatFileTraceListener")
        as RollingFlatFileTraceListenerData;

    string fileName = rollFileTraceListener.FileName;
    rollFileTraceListener.FileName = fileName.Replace("aaa", "bbb");

    LogWriterFactory f = new LogWriterFactory(configSource);
    f.Create();
    Logger.Reset();
    LogEntry logEntry = new LogEntry();
    logEntry.Message = $"{DateTime.Now} Count:{333}";
    logEntry.Categories.Clear();
    logEntry.Categories.Add("General");

    Logger.Write(logEntry);
0
On

You can get that information by using the configuration objects:

IConfigurationSource configSource = ConfigurationSourceFactory.Create();
var logSettings = configSource.GetSection(LoggingSettings.SectionName) as LoggingSettings;

var flatFileTraceListener = logSettings.TraceListeners
    .First(t => t is FlatFileTraceListenerData) as FlatFileTraceListenerData;

string fileName = flatFileTraceListener.FileName;

This assumes that you are interested in the first trace listener that is a FlatFileTraceListener. If you wanted to get the trace listener by type and name then you could do that too:

IConfigurationSource configSource = ConfigurationSourceFactory.Create();
var logSettings = configSource.GetSection(LoggingSettings.SectionName) as LoggingSettings;

var flatFileTraceListener = logSettings.TraceListeners
    .FirstOrDefault(t => t is FlatFileTraceListenerData && t.Name == "Flat File Trace Listener")
    as FlatFileTraceListenerData;

string fileName = flatFileTraceListener.FileName;