1.前言
有兩個日志文件Arrive和Done,里面分別保存了程序處理一個報文的日志信息,Arrive里面保存的是報文的到達時間,Done里面保存的是報文處理完成的時間,現在想知道每個報文的處理時間是多長。如果靠人工在兩個日志文件中逐個報文對比的話需要花很長的時間,於是想到了將兩個報文的信息存儲到數據庫中,再利用數據庫的強大處理功能來獲得每個報文的處理時間。
2.實現
有了想法,立刻着手實現。
2.1定義數據庫
在數據庫中增加一個LOG_INFO的表,語法如下:
create table LOG_INFO ( FILE_NAME CHAR(15) not null, ARRIVE_TIME DATE, DEAL_TIME DATE );
2.2報文解析入庫
讀文件並寫入數據庫:
1 private void btnStart_Click(object sender, EventArgs e) 2 { 3 String line, time, filename, sql; 4 int i = 0, result = 0; 5 OracleConnection conn = new OracleConnection(connectionString); 6 conn.Open(); 7 for (i = 0; i < 8; i++) 8 { 9 switch (i) 10 { 11 case 0: 12 lblCurrFile.Text = "Arrive3.log"; 13 break; 14 case 1: 15 lblCurrFile.Text = "Arrive2.log"; 16 break; 17 case 2: 18 lblCurrFile.Text = "Arrive1.log"; 19 break; 20 case 3: 21 lblCurrFile.Text = "Arrive.log"; 22 break; 23 case 4: 24 lblCurrFile.Text = "Done3.log"; 25 break; 26 case 5: 27 lblCurrFile.Text = "Done2.log"; 28 break; 29 case 6: 30 lblCurrFile.Text = "Done1.log"; 31 break; 32 case 7: 33 lblCurrFile.Text = "Done.log"; 34 break; 35 default: 36 break; 37 } 38 if (File.Exists(tbxPath.Text + lblCurrFile.Text)) 39 { 40 try 41 { 42 using (StreamReader sr = new StreamReader(tbxPath.Text + lblCurrFile.Text)) 43 { 44 while ((line = sr.ReadLine()) != null) 45 { 46 if (lbxReportInfo.Items.Count > 100) 47 { 48 lbxReportInfo.Items.Clear(); 49 } 50 else 51 { 52 lbxReportInfo.Items.Add(line); 53 } 54 time = line.Substring(1, 19); 55 filename = line.Substring(22, 15); 56 57 if (lblCurrFile.Text.Substring(0, 4).Equals("Arri")) 58 sql = String.Format("insert into LOG_INFO(FILE_NAME,ARRIVE_TIME) values('{0}',TO_DATE('{1}','YYYY-MM-DD HH24:MI:SS'))", filename, time); 59 else 60 sql = String.Format("update LOG_INFO set DEAL_TIME=TO_DATE('{0}','YYYY-MM-DD HH24:MI:SS') where FILE_NAME='{1}'", time, filename); 61 // 入庫 62 try 63 { 64 OracleCommand cmd = new OracleCommand(sql, conn); 65 result = cmd.ExecuteNonQuery(); 66 cmd.Dispose(); 67 } 68 catch(Exception ex) 69 { 70 lblMsg.Text = ex.Message; 71 } 72 } 73 } 74 } 75 catch (Exception ex) 76 { 77 lblMsg.Text = ex.Message; 78 } 79 } 80 else 81 { 82 continue; 83 } 84 } 85 conn.Close(); 86 }
數據庫是Oracle 11g,連接字符串格式如下:
private string connectionString = "server=xxx;uid=xxx;pwd=xxx";
2.3計算報文處理時間
在PL/SQL命令窗口中輸入如下命令:
select (deal_time-arrive_time)*24*60*60 from log_info;
可以得到每個報文的處理時間。由於deal_time-arrive_time的結果單位是天,通過*24*60*60將其轉換為秒。當然也可以通過*24*60轉換為分鍾,具體看需要。
當然也可以加上一些查詢條件,比如想得到處理時間大於100秒的記錄就可以這樣寫:
select (deal_time-arrive_time)*24*60*60 from log_info where (deal_time-arrive_time)*24*60*60>100;
查詢結果如下:
SQL> select (deal_time-arrive_time)*24*60*60 from log_info where (deal_time-arrive_time)*24*60*60>100; (DEAL_TIME-ARRIVE_TIME)*24*60* ------------------------------ 285 322 124 136 124 129 261 7 rows selected SQL>
3.總結
程序在WinXP SP3+VS2010+Oracle 11g下測試通過。