1

在 MS Enterprise Library 5.0 中,Logging 应用程序块,在运行时,我可以获取日志要去的日志文件(平面文件侦听器)的名称吗?

4

2 回答 2

2

您可以使用配置对象获取该信息:

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;

这假设您对作为 FlatFileTraceListener 的第一个跟踪侦听器感兴趣。如果您想按类型和名称获取跟踪侦听器,那么您也可以这样做:

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;
于 2013-05-18T02:54:36.530 回答
0

更改配置没有问题。
更改文件名属性 aaa.log -> bbb.log后,Logger 未写入新文件名。
更改的配置必须保存/激活(?)或记录器必须新初始化..!??

    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);
于 2016-08-22T12:19:22.507 回答