[Enterprise Library for .NET Framework 2.0]自定义日志路径或日志文件名称

有时候,日志输出的时候会根据时间来分类,譬如“20140821\trace.log”,在Enterprise Library中通过工具配置,只能定义日志文件名称,可以通过代码修改FlatFileTraceListenerData实现或Custom Trace Listener方式,

通过代码修改FlatFileTraceListenerData实现代码如下:

        public static string GetTraceLogPath(string listenersName)
        {
            string _tracePath = string.Empty;
            if (!string.IsNullOrEmpty(listenersName))
            {
                Configuration _etlConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                LoggingSettings _loggingSettings = (LoggingSettings)_etlConfig.GetSection(LoggingSettings.SectionName);
                FlatFileTraceListenerData _listeners = _loggingSettings.TraceListeners.Get(listenersName) as FlatFileTraceListenerData;
                if (_listeners != null)
                {
                    _tracePath = _listeners.FileName;
                }
            }
            return _tracePath;
        }
        public static void SetTraceLogPath(string listenersName, string fileName)
        {
            if (!string.IsNullOrEmpty(listenersName) && !string.IsNullOrEmpty(fileName))
            {
                Configuration _etlConfig = ConfigurationManager.OpenExeConfiguration(System.Configuration.ConfigurationUserLevel.None);
                LoggingSettings _loggingSettings = (LoggingSettings)_etlConfig.GetSection(LoggingSettings.SectionName);
                FlatFileTraceListenerData _listeners = _loggingSettings.TraceListeners.Get(listenersName) as FlatFileTraceListenerData;
                if (_listeners != null)
                {
                    _listeners.FileName = fileName;
                    _etlConfig.Save();
                }
            }
        }

测试代码:

            try
            {
                string _listenName = "FlatFile TraceListener";
                SetTraceLogPath(_listenName, string.Format(@"{0}/trace.log", DateTime.Now.ToString("yyyyMMdd")));
                LogEntry log = new LogEntry();
                log.Categories.Add("Warning");
                log.Title = "测试";
                log.Message = "日志日志内容";
                Logger.Write(log);

                LogEntry log2 = new LogEntry();
                log2.Categories.Add("Warning");
                log2.Title = "测试2";
                log2.Message = "日志日志内容2";
                Logger.Write(log2);

                Console.WriteLine(GetTraceLogPath(_listenName));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                Console.ReadLine();
            }

测试效果:

希望有所帮助

[Enterprise Library for .NET Framework 2.0]自定义日志路径或日志文件名称,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。