internal/loggingProviders/sql.provider.ps1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 |
$FunctionDefinitions = { function Get-DatabaseConnection { [CmdletBinding()] param () if (-not $script:connections) { $script:connections = @{ } } # Connection already established if ($script:cfgServer.ConnectionContext) { $server = $script:cfgServer } elseif ($script:connections[$script:cfgServer]) { $server = $script:connections[$script:cfgServer] } else { $param = @{ SqlInstance = $script:cfgServer } $credential = Get-ConfigValue -Name 'Credential' if ($credential) { $param.SqlCredential = $Credential } try { $server = Connect-DbaInstance @param -ErrorAction Stop } catch { throw } $script:connections[$script:cfgServer] = $server } if (-not $server.ConnectionContext.IsOpen) { try { $server.ConnectionContext.Connect() } catch { throw } } $server } function Export-DataToSql { <# .SYNOPSIS Function to send logging data to a Sql database .DESCRIPTION This function is the main function that takes a PSFMessage object to log in a Sql database. .PARAMETER ObjectToProcess This is a PSFMessage object that will be converted and serialized then injected to a Sql database. .EXAMPLE Export-DataToAzure $objectToProcess .NOTES How to register this provider ----------------------------- Set-PSFLoggingProvider -Name sql -InstanceName sqlloginstance -Enabled $true #> [cmdletbinding()] param ( [parameter(Mandatory = $True)] $ObjectToProcess ) process { $queryParameters = @($script:converter.Process($ObjectToProcess))[0] $insertQuery = Get-Query -Parameters $queryParameters try { $sqlInstance = Get-DatabaseConnection Invoke-DbaQuery -SqlInstance $sqlInstance -Database $script:cfgDatabase -Query $insertQuery -SqlParameters $queryParameters -EnableException } catch { throw } } } function Get-Query { [CmdletBinding()] param ( [hashtable] $Parameters ) if ($script:insertQuery) { return $script:insertQuery } $properties = $Parameters.Keys $propSquared = foreach ($property in $properties) { "[$property]" } $propAdd = foreach ($property in $properties) { "@$property" } $script:insertQuery = @" INSERT INTO [$script:cfgDatabase].[$script:cfgSchema].[$script:cfgTable]($($propSquared -join ',')) VALUES ($($propAdd -join ',')) "@ $script:insertQuery } function New-DefaultSqlDatabaseAndTable { <# .SYNOPSIS This function will create a default sql database object .DESCRIPTION This function will create the default sql default logging database .EXAMPLE None #> [cmdletbinding()] param ( ) # need to use dba tools to create the database and credentials for connecting. begin { # set instance and database name variables $SqlTable = Get-ConfigValue -Name 'Table' $SqlDatabaseName = Get-ConfigValue -Name 'Database' $SqlSchema = Get-ConfigValue -Name 'Schema' if (-not $SqlSchema) { $SqlSchema = 'dbo' } } process { try { $dbaconnection = Get-DatabaseConnection if (-NOT (Get-DbaDatabase -SqlInstance $dbaconnection | Where-Object Name -eq $SqlDatabaseName)) { $database = New-DbaDatabase -SqlInstance $dbaconnection -Name $SqlDatabaseName } if (-NOT ($database.Tables | Where-Object Name -eq $SqlTable)) { $createtable = "CREATE TABLE $SqlSchema.$SqlTable (Message VARCHAR(max), Level VARCHAR(max), TimeStamp [DATETIME], FunctionName VARCHAR(max), ModuleName VARCHAR(max), Tags VARCHAR(max), Runspace VARCHAR(36), ComputerName VARCHAR(max), Username VARCHAR(max), TargetObject VARCHAR(max), [File] VARCHAR(max), Line BIGINT, ErrorRecord VARCHAR(max), CallStack VARCHAR(max), [Data] VARCHAR(max))" Invoke-dbaquery -SQLInstance $dbaconnection -Database $SqlDatabaseName -Query $createtable } } catch { throw } } } } #region Installation $installationParameters = { $results = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary $attributesCollection = New-Object System.Collections.ObjectModel.Collection[System.Attribute] $parameterAttribute = New-Object System.Management.Automation.ParameterAttribute $parameterAttribute.ParameterSetName = '__AllParameterSets' $attributesCollection.Add($parameterAttribute) $validateSetAttribute = New-Object System.Management.Automation.ValidateSetAttribute('CurrentUser', 'AllUsers') $attributesCollection.Add($validateSetAttribute) $RuntimeParam = New-Object System.Management.Automation.RuntimeDefinedParameter("Scope", [string], $attributesCollection) $results.Add("Scope", $RuntimeParam) $results } $installation_script = { param ( $BoundParameters ) $paramInstallModule = @{ Name = 'dbatools' } if ($BoundParameters.Scope) { $paramInstallModule['Scope'] = $BoundParameters.Scope } elseif (-not (Test-PSFPowerShell -Elevated)) { $paramInstallModule['Scope'] = 'CurrentUser' } Install-Module @paramInstallModule } $isInstalled_script = { (Get-Module dbatools -ListAvailable) -as [bool] } #endregion Installation #region Events $begin_event = { $script:cfgServer = Get-ConfigValue -Name 'SqlServer' New-DefaultSqlDatabaseAndTable } $start_event = { $changePending = $false if ($script:cfgHeaders -ne (Get-ConfigValue -Name 'Headers')) { $script:cfgHeaders = Get-ConfigValue -Name 'Headers' $changePending = $true } if ($script:cfgServer -ne (Get-ConfigValue -Name 'SqlServer')) { $script:cfgServer = Get-ConfigValue -Name 'SqlServer' $changePending = $true } if ($script:cfgDatabase -ne (Get-ConfigValue -Name 'Database')) { $script:cfgDatabase = Get-ConfigValue -Name 'Database' $changePending = $true } if ($script:cfgSchema -ne (Get-ConfigValue -Name 'Schema')) { $script:cfgSchema = Get-ConfigValue -Name 'Schema' if (-not $script:cfgSchema) { $script:cfgSchema = 'dbo' } $changePending = $true } if ($script:cfgTable -ne (Get-ConfigValue -Name 'Table')) { $script:cfgTable = Get-ConfigValue -Name 'Table' $changePending = $true } if (-not $changePending) { return } $script:sql_headers = switch ($script:cfgHeaders) { 'Tags' { @{ Name = 'Tags' Expression = { ($_.Tags -join ",") -as [string] } } } 'Message' { @{ Name = 'Message'; Expression = { $_.LogMessage } } } 'Level' { @{ Name = 'Level'; Expression = { $_.Level -as [string] } } } 'Runspace' { @{ Name = 'Runspace'; Expression = { $_.Runspace -as [string] } } } 'TargetObject' { @{ Name = 'TargetObject'; Expression = { $_.TargetObject -as [string] } } } 'ErrorRecord' { @{ Name = 'ErrorRecord'; Expression = { $_.ErrorRecord -as [string] } } } 'CallStack' { @{ Name = 'CallStack'; Expression = { $_.CallStack -as [string] } } } 'Timestamp' { @{ Name = 'Timestamp' Expression = { $_.Timestamp.ToUniversalTime() } } } 'Data' { @{ Name = 'Data' Expression = { if (-not $_.Data) { return 'null' } $_.Data | ConvertTo-Json -Compress } } } default { $_ } } if ($script:converter) { $null = $script:converter.End() $script:converter = $null } # Cache the conversion logic once as a steppable pipeline to avoid having to do it $script:converter = { Microsoft.PowerShell.Utility\Select-Object $script:sql_headers | PSFramework\ConvertTo-PSFHashtable }.GetSteppablePipeline() $script:converter.Begin($true) $script:insertQuery = '' } $message_event = { param ( $Message ) Export-DataToSql -ObjectToProcess $Message } $end_event = { if ($script:converter) { $null = $script:converter.End() $script:converter = $null } } # Action that is performed when stopping the logging script. $final_event = { } #endregion Events # Configuration values for the logging provider $configuration_Settings = { Set-PSFConfig -Module PSFramework -Name 'Logging.Sql.Credential' -Initialize -Validation 'credential' -Description "Credentials used for connecting to the SQL server." Set-PSFConfig -Module PSFramework -Name 'Logging.Sql.Database' -Value "LoggingDatabase" -Initialize -Validation 'string' -Description "SQL server database." Set-PSFConfig -Module PSFramework -Name 'Logging.Sql.Table' -Value "LoggingTable" -Initialize -Validation 'string' -Description "SQL server database table." Set-PSFConfig -Module PSFramework -Name 'Logging.Sql.SqlServer' -Value "" -Initialize -Description "SQL server hosting logs." Set-PSFConfig -Module PSFramework -Name 'Logging.Sql.Schema' -Value "dbo" -Initialize -Description "SQL server schema." } # Registered parameters for the logging provider. # ConfigurationDefaultValues are used for all instances of the sql log provider $paramRegisterPSFSqlProvider = @{ Name = "Sql" Version2 = $true ConfigurationRoot = 'PSFramework.Logging.Sql' InstanceProperties = 'Database', 'Schema', 'Table', 'SqlServer', 'Credential', 'Headers' MessageEvent = $message_Event BeginEvent = $begin_event StartEvent = $start_event EndEvent = $end_event FinalEvent = $final_event IsInstalledScript = $isInstalled_script InstallationScript = $installation_script ConfigurationSettings = $configuration_Settings InstallationParameters = $installationParameters FunctionDefinitions = $functionDefinitions ConfigurationDefaultValues = @{ 'Database' = "LoggingDatabase" 'Table' = "LoggingTable" 'Schema' = 'dbo' Headers = 'Message', 'Timestamp', 'Level', 'Tags', 'Data', 'ComputerName', 'Runspace', 'UserName', 'ModuleName', 'FunctionName', 'File', 'CallStack', 'TargetObject', 'ErrorRecord' } } # Register the Azure logging provider Register-PSFLoggingProvider @paramRegisterPSFSqlProvider |