SQL Server管理オブジェクト 略して
SMOを使って、
SQLServerからイベントログ出力を行う処理を見張っているプログラムを作ってみた。
SMOを使うために、最低限以下のDLLをソリューションで参照するようにしてくださいまし。
(SQL Server 2008の場合 2005の場合は100を90に読み替えてください。)
C:\Program Files\Microsoft SQL Server\100\SDK\Assemblies\Microsoft.SqlServer.ConnectionInfo.dll
C:\Program Files\Microsoft SQL Server\100\SDK\Assemblies\Microsoft.SqlServer.Management.Sdk.Sfc.dll
C:\Program Files\Microsoft SQL Server\100\SDK\Assemblies\Microsoft.SqlServer.Smo.dll
C:\Program Files\Microsoft SQL Server\100\SDK\Assemblies\Microsoft.SqlServer.SqlEnum.dll
またImportも忘れずにね♪
ちなみに、SQLServerのTransact-SQLでイベントログ書き込みを発生させるのに使ったのは
xp_logevent (Transact-SQL)でっす。
超個人的、気分的な要因で、VB.NETになりました。
また、ただのクラスで作りましたが、Windowsサービスに入れることを視野に入れたつくりになっています。
イベントを発生させた モノの情報と、
SQLServerにキャッシュされたクエリ プランの集計パフォーマンス統計およびSQL文を
ファイルに出力するようになっています。
Imports Microsoft.SqlServer.Management.Smo
Imports Microsoft.SqlServer.Management.Common
Public Class SQLServerErrorWatcher
Const LOG_FILE As String = "C:\test.log"
Dim srv As Server
Dim file As System.IO.StreamWriter
Protected Sub OnStart(ByVal args() As String)
srv = New Server
Try
Dim serverEventHandler As ServerEventHandler = New ServerEventHandler(AddressOf MyCreateEventHandler)
Dim serverEventSet As ServerTraceEventSet = New ServerTraceEventSet
serverEventSet.Eventlog = True
srv.Events.SubscribeToEvents(serverEventSet, serverEventHandler)
file = New System.IO.StreamWriter(LOG_FILE, True, System.Text.Encoding.UTF8)
srv.Events.StartEvents()
Catch ex As Exception
OnStop()
End Try
End Sub
Protected Sub OnStop()
Try
If (srv IsNot Nothing) Then
srv.Events.StopEvents()
End If
If (file IsNot Nothing) Then
file.Close()
End If
Finally
srv = Nothing
file = Nothing
End Try
End Sub
Shared Sub Main()
Dim target As SQLServerErrorWatcher = New SQLServerErrorWatcher
target.OnStart(Nothing)
While (target.srv IsNot Nothing)
End While
target.OnStop()
End Sub
Sub MyCreateEventHandler(ByVal sender As Object, ByVal e As ServerEventArgs)
Dim str As Text.StringBuilder = New Text.StringBuilder()
Dim server As Server = sender
Dim dbid As Integer = e.Properties.Item("DatabaseID").Value
str.AppendLine("----------")
str.AppendLine(e.PostTime.ToString())
str.AppendLine("----------")
str.Append("[ApplicationName]")
If (e.Properties.Item("ApplicationName") IsNot Nothing AndAlso _
e.Properties.Item("ApplicationName").Value IsNot Nothing) Then
str.Append(e.Properties.Item("ApplicationName").Value.ToString)
End If
str.AppendLine()
str.Append("[ClientProcessID]")
If (e.Properties.Item("ClientProcessID") IsNot Nothing AndAlso _
e.Properties.Item("ClientProcessID").Value IsNot Nothing) Then
str.Append(e.Properties.Item("ClientProcessID").Value.ToString)
End If
str.AppendLine()
str.Append("[ComputerName]")
If (e.Properties.Item("ComputerName") IsNot Nothing AndAlso _
e.Properties.Item("ComputerName").Value IsNot Nothing) Then
str.Append(e.Properties.Item("ComputerName").Value.ToString)
End If
str.AppendLine()
str.Append("[DatabaseName]")
If (e.Properties.Item("DatabaseName") IsNot Nothing AndAlso _
e.Properties.Item("DatabaseName").Value IsNot Nothing) Then
str.Append(e.Properties.Item("DatabaseName").Value.ToString)
End If
str.AppendLine()
str.Append("[Error]")
If (e.Properties.Item("Error") IsNot Nothing AndAlso _
e.Properties.Item("Error").Value IsNot Nothing) Then
str.Append(e.Properties.Item("Error").Value.ToString)
End If
str.AppendLine()
str.Append("[HostName]")
If (e.Properties.Item("HostName") IsNot Nothing AndAlso _
e.Properties.Item("HostName").Value IsNot Nothing) Then
str.Append(e.Properties.Item("HostName").Value.ToString)
End If
str.AppendLine()
str.Append("[LoginName]")
If (e.Properties.Item("LoginName") IsNot Nothing AndAlso _
e.Properties.Item("LoginName").Value IsNot Nothing) Then
str.Append(e.Properties.Item("LoginName").Value.ToString)
End If
str.AppendLine()
str.Append("[RequestID]")
If (e.Properties.Item("RequestID") IsNot Nothing AndAlso _
e.Properties.Item("RequestID").Value IsNot Nothing) Then
str.Append(e.Properties.Item("RequestID").Value.ToString)
End If
str.AppendLine()
str.Append("[SessionLoginName]")
If (e.Properties.Item("SessionLoginName") IsNot Nothing AndAlso _
e.Properties.Item("SessionLoginName").Value IsNot Nothing) Then
str.Append(e.Properties.Item("SessionLoginName").Value.ToString)
End If
str.AppendLine()
str.Append("[StartTime]")
If (e.Properties.Item("StartTime") IsNot Nothing AndAlso _
e.Properties.Item("StartTime").Value IsNot Nothing) Then
str.Append(e.Properties.Item("StartTime").Value.ToString)
End If
str.AppendLine()
str.Append("[TextData]")
If (e.Properties.Item("TextData") IsNot Nothing AndAlso _
e.Properties.Item("TextData").Value IsNot Nothing) Then
str.Append(e.Properties.Item("TextData").Value.ToString)
End If
str.AppendLine()
str.Append("[TransactionID]")
If (e.Properties.Item("TransactionID") IsNot Nothing AndAlso _
e.Properties.Item("TransactionID").Value IsNot Nothing) Then
str.Append(e.Properties.Item("TransactionID").Value.ToString)
End If
str.AppendLine()
str.Append("[EventSpID]").AppendLine(e.Spid.ToString)
str.Append("[LogReuseWait]").AppendLine(server.Databases("Footprints").LogReuseWaitStatus)
Dim sql As String = "SELECT " _
+ " last_execution_time, " _
+ " execution_count, " _
+ " total_worker_time, " _
+ " last_worker_time, " _
+ " min_worker_time, " _
+ " max_worker_time, " _
+ " total_logical_reads, " _
+ " last_logical_reads, " _
+ " min_logical_reads, " _
+ " max_logical_reads, " _
+ " total_logical_writes, " _
+ " last_logical_writes, " _
+ " min_logical_writes, " _
+ " max_logical_writes, " _
+ " total_physical_reads, " _
+ " last_physical_reads, " _
+ " min_physical_reads, " _
+ " max_physical_reads, " _
+ " total_logical_writes, " _
+ " last_logical_writes, " _
+ " min_logical_writes, " _
+ " max_logical_writes, " _
+ " total_elapsed_time, " _
+ " last_elapsed_time, " _
+ " min_elapsed_time, " _
+ " max_elapsed_time, " _
+ " [text].text " _
+ "FROM " _
+ " sys.dm_exec_query_stats req " _
+ " cross apply " _
+ " sys.dm_exec_sql_text (req.plan_handle) [text] " _
+ "where dbid is null or dbid = DB_ID('Footprints') "
Dim ret As Data.DataSet = (server.Databases("master").ExecuteWithResults(sql))
Dim i As Integer = 0
Dim j As Integer = 0
For i = 0 To ret.Tables(0).Rows.Count - 1
Dim row As Data.DataRow
row = ret.Tables(0).Rows(i)
For j = 0 To ret.Tables(0).Columns.Count - 1
str.Append(ret.Tables(0).Columns(j).ColumnName)
str.Append(",")
Next
str.AppendLine()
str.Append(i)
Console.WriteLine(":")
For j = 0 To ret.Tables(0).Columns.Count - 1
str.Append("""")
str.Append(row.Item(j))
str.Append("""")
str.Append(",")
Next
file.Write(str.ToString())
file.Flush()
Next
End Sub
End Class
結果としてこんな感じの情報が出力されます。
[ApplicationName]Microsoft SQL Server Management Studio - クエリ
[ClientProcessID]7224
[ComputerName]MIMAGAWA-DELL
[DatabaseName]master
[Error]50001
[HostName]MIMAGAWA-DELL
[LoginName]MIMAGAWA-DELL\みまがわ
[RequestID]0
[SessionLoginName]MIMAGAWA-DELL\みまがわ
[StartTime]20100107135536.000983+000
[TextData]Error: 50001 Severity: 16 State: 1 message
[TransactionID]0
[EventSpID]52
[LogReuseWait]0
last_execution_time,execution_count,total_worker_time,last_worker_time,min_worker_time,max_worker_time,total_logical_reads,last_logical_reads,min_logical_reads,max_logical_reads,total_logical_writes,last_logical_writes,min_logical_writes,max_logical_writes,total_physical_reads,last_physical_reads,min_physical_reads,max_physical_reads,total_logical_writes1,last_logical_writes1,min_logical_writes1,max_logical_writes1,total_elapsed_time,last_elapsed_time,min_elapsed_time,max_elapsed_time,text,
0"2010/01/07 13:55:38","2","0","0","0","0","4","2","2","2","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","(@_msparam_0 nvarchar(4000))SELECT
dtb.name AS [Name]
FROM
master.sys.databases AS dtb
WHERE
(dtb.name=@_msparam_0)",last_execution_time,execution_count,total_worker_time,last_worker_time,min_worker_time,max_worker_time,total_logical_reads,last_logical_reads,min_logical_reads,max_logical_reads,total_logical_writes,last_logical_writes,min_logical_writes,max_logical_writes,total_physical_reads,last_physical_reads,min_physical_reads,max_physical_reads,total_logical_writes1,last_logical_writes1,min_logical_writes1,max_logical_writes1,total_elapsed_time,last_elapsed_time,min_elapsed_time,max_elapsed_time,text,1"2010/01/07 13:55:38","2","1953","0","0","1953","8","4","4","4","0","0","0","0","0","0","0","0","0","0","0","0","1953","0","0","1953","(@_msparam_0 nvarchar(4000))SELECT
dtb.compatibility_level AS [CompatibilityLevel],
dtb.name AS [DatabaseName2]
FROM
master.sys.databases AS dtb
WHERE
(dtb.name=@_msparam_0)",last_execution_time,execution_count,total_worker_time,last_worker_time,min_worker_time,max_worker_time,total_logical_reads,last_logical_reads,min_logical_reads,max_logical_reads,total_logical_writes,last_logical_writes,min_logical_writes,max_logical_writes,total_physical_reads,last_physical_reads,min_physical_reads,max_physical_reads,total_logical_writes1,last_logical_writes1,min_logical_writes1,max_logical_writes1,total_elapsed_time,last_elapsed_time,min_elapsed_time,max_elapsed_time,text,