Lab 3: Reconfigure Logging at Runtime 实验3:在运行中重新设置日志配置
In this lab, you will dynamically change the logging configuration while the application is running. This allows you to make temporary changes to your logging configuration to collect additional information without stopping and starting your application. 在这个实验中,你将在程序运行的时候动态的改变日志的配置。这样可以让你临时的改变日志配置信息来收集额外的信息,不用停止再启动你的程序。
To begin this exercise, open the EnoughPI.sln file located in the ex03\begin folder. 打开ex03\begin文件夹里面的EnoughPI.sln文件来开始这个练习。
To create a button in the application to update the configuration 在程序中创建一个按钮来更新配置信息
To update the logging configuration 更新日志配置
using EnoughPI.Logging; using Microsoft.Practices.EnterpriseLibrary.Logging; using Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners; using Microsoft.Practices.EnterpriseLibrary.Logging.Formatters;
private int numUpdates = 0;
1 public void UpdateConfiguration() 2 { 3 numUpdates++; 4 Logger.Writer.Configure(config => 5 { 6 TextFormatter formatter = new TextFormatter(@"Timestamp: 7 {timestamp(local)}{newline}Message: 8 {message}{newline}Category: {category}{newline}Priority: 9 {priority}{newline}EventId: {eventid}{newline}ActivityId: 10 {property(ActivityId)}{newline}Severity: 11 {severity}{newline}Title:{title}{newline}"); 12 var newDest = new FlatFileTraceListener(@"C:\Temp\trace-" + 13 numUpdates + @".log", "-----------------------------------", 14 "----------------------------------------", formatter); 15 config.SpecialSources.AllEvents.Listeners.Clear(); 16 config.SpecialSources.AllEvents.AddTraceListener(newDest); 17 }); 18 }
This function reconfigures your Logger‘s LogWriter to write to a new destination: a new FlatFileTraceListener whose name reflects the number of times the configuration has been updated. First it clears the Listeners for the Trace category, then adds the new FlatFileTraceListener. 这个函数重新配置了你的Logger的LogWriter来写到新的目的地。一个新的FlatFileTraceListener,其名称反映了配置信息被更新的次数。首先该方法清空了Trace类型的监听器,然后添加了这个新的FlatFileTraceListener。
private void button1_Click(object sender, EventArgs e) { UpdateConfiguration(); }
To verify reconfiguration at run time is successful 验证运行时重新配置成功
To verify that you have completed the exercise correctly, you can use the solution provided in the ex03\end folder. 你可以打开ex03\end文件夹中提供的解决方案来验证你是否正确的完成了了练习。
原文:http://www.cnblogs.com/Arnu/p/loggingblock3.html