2010-05-18 4 views
0

SQL Server 2005 Express Edition에서 데이터베이스의 추적 파일을 관리해야합니다. 데이터베이스에 대해 C2 감사 로깅이 설정되어 있으며 만드는 파일이 많은 공간을 차지합니다.Sql Server 2005에서 추적 파일 관리

SQL Server 내에서이 작업을 수행 할 수 있습니까? 아니면 이러한 파일을 모니터링하고 적절한 조치를 취할 서비스를 작성해야합니까?

[master]. [sys]. [trace] 테이블에 추적 파일 속성이 있습니다. 이 테이블에있는 들판의 의미를 아는 사람이 있습니까?

답변

1

여기에 내가 그와 함께 무엇 콘솔 응용 프로그램에서 꽤 좋은 일 경우 : C2 감사 로깅을 사용할 때

static void Main(string[] args) 
    { 
     try 
     { 
      Console.WriteLine("CcmLogManager v1.0"); 
      Console.WriteLine(); 

      // How long should we keep the files around (in months) 12 is the PCI requirement? 
      var months = Convert.ToInt32(ConfigurationManager.AppSettings.Get("RemoveMonths") ?? "12"); 

      var currentFilePath = GetCurrentAuditFilePath(); 

      Console.WriteLine("Path: {0}", new FileInfo(currentFilePath).DirectoryName); 
      Console.WriteLine(); 

      Console.WriteLine("------- Removing Files --------------------"); 

      var fileInfo = new FileInfo(currentFilePath); 
      if (fileInfo.DirectoryName != null) 
      { 
       var purgeBefore = DateTime.Now.AddMonths(-months); 
       var files = Directory.GetFiles(fileInfo.DirectoryName, "audittrace*.trc.zip"); 

       foreach (var file in files) 
       { 
        try 
        { 
         var fi = new FileInfo(file); 

         if (PurgeLogFile(fi, purgeBefore)) 
         { 
          Console.WriteLine("Deleting: {0}", fi.Name); 

          try 
          { 
           fi.Delete(); 
          } 
          catch (Exception ex) 
          { 
           Console.WriteLine(ex); 
          } 
         } 
        } 
        catch (Exception ex) 
        { 
         Console.WriteLine(ex); 
        } 
       } 
      } 

      Console.WriteLine("------- Files Removed ---------------------"); 
      Console.WriteLine(); 


      Console.WriteLine("------- Compressing Files -----------------"); 

      if (fileInfo.DirectoryName != null) 
      { 
       var files = Directory.GetFiles(fileInfo.DirectoryName, "audittrace*.trc"); 

       foreach (var file in files) 
       { 
        // Don't attempt to compress the current log file. 
        if (file.ToLower() == fileInfo.FullName.ToLower()) 
         continue; 

        var zipFileName = file + ".zip"; 

        var fi = new FileInfo(file); 
        var zipEntryName = fi.Name; 

        Console.WriteLine("Zipping: \"{0}\"", fi.Name); 

        try 
        { 
         using (var fileStream = File.Create(zipFileName)) 
         { 
          var zipFile = new ZipOutputStream(fileStream); 
          zipFile.SetLevel(9); 

          var zipEntry = new ZipEntry(zipEntryName); 
          zipFile.PutNextEntry(zipEntry); 

          using (var ostream = File.OpenRead(file)) 
          { 
           int bytesRead; 
           var obuffer = new byte[2048]; 
           while ((bytesRead = ostream.Read(obuffer, 0, 2048)) > 0) 
            zipFile.Write(obuffer, 0, bytesRead); 
          } 

          zipFile.Finish(); 
          zipFile.Close(); 
         } 

         fi.Delete(); 
        } 
        catch (Exception ex) 
        { 
         Console.WriteLine(ex); 
        } 
       } 
      } 

      Console.WriteLine("------- Files Compressed ------------------"); 
      Console.WriteLine(); 
     } 
     catch (Exception ex) 
     { 
      Console.WriteLine(ex); 
     } 

     Console.WriteLine("Press any key..."); 
     Console.ReadKey(); 
    } 

    public static bool PurgeLogFile(FileInfo fi, DateTime purgeBefore) 
    { 
     try 
     { 
      var filename = fi.Name; 
      if (filename.StartsWith("audittrace")) 
      { 
       filename = filename.Substring(10, 8); 

       var year = Convert.ToInt32(filename.Substring(0, 4)); 
       var month = Convert.ToInt32(filename.Substring(4, 2)); 
       var day = Convert.ToInt32(filename.Substring(6, 2)); 

       var logDate = new DateTime(year, month, day); 

       return logDate.Date <= purgeBefore.Date; 
      } 
     } 
     catch (Exception ex) 
     { 
      Console.WriteLine(ex); 
     } 

     return false; 
    } 

    public static string GetCurrentAuditFilePath() 
    { 
     const string connStr = "Data Source=.\\SERVER;Persist Security Info=True;User ID=;Password="; 

     var dt = new DataTable(); 

     var adapter = 
      new SqlDataAdapter(
       "SELECT path FROM [master].[sys].[traces] WHERE path like '%audittrace%'", connStr); 
     try 
     { 
      adapter.Fill(dt); 

      if (dt.Rows.Count >= 1) 
      { 
       if (dt.Rows.Count > 1) 
        Console.WriteLine("More than one audit trace file defined! Count: {0}", dt.Rows.Count); 

       var path = dt.Rows[0]["path"].ToString(); 
       return path.StartsWith("\\\\?\\") ? path.Substring(4) : path; 
      } 
     } 
     catch (Exception ex) 
     { 
      Console.WriteLine(ex); 
     } 

     throw new Exception("No Audit Trace File in sys.traces!"); 
    } 
0

SQL Trace를 설정하여 SQL 테이블에 로그 할 수도 있습니다. 그런 다음 SQL Agent 작업을 설정하여 레코드를 자동자를 수 있습니다.

+0

이 어떻게 로깅 테이블을 사용하도록 SQL Server를 알 수 있습니까? 이것은 구현하기가 가장 쉽지만 Express Edition에서 작동하는지 궁금해합니다. – Sophtware

+0

프로필러 만 데이터베이스 테이블에 로그온하도록 설정할 수 있습니다. 서버 측 추적을 구성하는 경우 항상 .trc 파일에 쓰며,'sys.fn_trace_gettable()'함수를 통해 다시 읽을 수 있습니다. –

0

sys.traces에는 서버에서 시작된 모든 추적에 대한 레코드가 있습니다. SQL Express에는 에이전트가 없으므로 작업을 설정할 수 없으므로이를 모니터링하기 위해 외부 프로세스 또는 서비스가 필요합니다. 자신 만의 모든 것을 롤업해야합니다 (모니터링, 보관, 추적 보존 정책 등). C2 감사를 실시하고 있다면 감사 기간을 결정하는 정책을 가지고 있다고 가정합니다.

+0

이 경로를 피하려고하지만 PCI 준수를위한 것입니다. 고객의 컴퓨터에 추적 로그를 6 개월 보관해야하며 공간을 절약하려면 더 이상 사용되지 않는 로그를 압축해야합니다. – Sophtware