[EnterpriseLibraryfor.NETFramework2.0]自定义日志路径或日志文件名称

11/25/2015来源:ASP.NET技巧人气:908

有时候,日志输出的时候会根据时间来分类,譬如“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();
            }

测试效果:

image

image

image

希望有所帮助