在Sql Server 2005上管理跟踪文件

时间:2010-05-18 19:15:16

标签: sql-server-2005 logging audit

我需要在Sql Server 2005 Express Edition上管理数据库的跟踪文件。为数据库打开了C2审计日志记录,它正在创建的文件占用了大量空间。

可以在Sql Server中完成,还是需要编写服务来监控这些文件并采取相应的措施?

我找到了[master]。[sys]。[trace]表,其中包含跟踪文件属性。有谁知道这张表中字段的含义?

3 个答案:

答案 0 :(得分:1)

以下是我提出的在控制台应用程序中工作得很好的内容:

    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!");
    }

答案 1 :(得分:0)

您还可以设置SQL跟踪以记录到SQL表。然后,您可以设置SQL代理任务以自动截断记录。

答案 2 :(得分:0)

sys.traces包含服务器上启动的每条跟踪的记录。由于SQL Express没有代理并且无法设置作业,因此您需要外部流程或服务来监控这些作业。您将不得不推出自己的一切(监控,存档,跟踪保留政策等)。如果您已进行C2审核,我认为您已制定政策来确定必须保留审核的持续时间。