|
| 1 | +// Copyright 2018 Serilog Contributors |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +using Serilog.Core; |
| 16 | +using Serilog.Debugging; |
| 17 | +using Serilog.Events; |
| 18 | +using System; |
| 19 | +using System.Data; |
| 20 | +using System.Data.SqlClient; |
| 21 | +using System.Linq; |
| 22 | +using System.Text; |
| 23 | + |
| 24 | +namespace Serilog.Sinks.MSSqlServer |
| 25 | +{ |
| 26 | + /// <summary> |
| 27 | + /// Writes log events as rows in a table of MSSqlServer database using Audit logic, meaning that each row is synchronously committed |
| 28 | + /// and any errors that occur are propagated to the caller. |
| 29 | + /// </summary> |
| 30 | + public class MSSqlServerAuditSink : ILogEventSink, IDisposable |
| 31 | + { |
| 32 | + private readonly MSSqlServerSinkTraits _traits; |
| 33 | + |
| 34 | + /// <summary> |
| 35 | + /// Construct a sink posting to the specified database. |
| 36 | + /// </summary> |
| 37 | + /// <param name="connectionString">Connection string to access the database.</param> |
| 38 | + /// <param name="tableName">Name of the table to store the data in.</param> |
| 39 | + /// <param name="schemaName">Name of the schema for the table to store the data in. The default is 'dbo'.</param> |
| 40 | + /// <param name="formatProvider">Supplies culture-specific formatting information, or null.</param> |
| 41 | + /// <param name="autoCreateSqlTable">Create log table with the provided name on destination sql server.</param> |
| 42 | + /// <param name="columnOptions">Options that pertain to columns</param> |
| 43 | + public MSSqlServerAuditSink( |
| 44 | + string connectionString, |
| 45 | + string tableName, |
| 46 | + IFormatProvider formatProvider, |
| 47 | + bool autoCreateSqlTable = false, |
| 48 | + ColumnOptions columnOptions = null, |
| 49 | + string schemaName = "dbo" |
| 50 | + ) |
| 51 | + { |
| 52 | + if (columnOptions != null) |
| 53 | + { |
| 54 | + if (columnOptions.DisableTriggers) |
| 55 | + throw new NotSupportedException($"The {nameof(ColumnOptions.DisableTriggers)} option is not supported for auditing."); |
| 56 | + } |
| 57 | + _traits = new MSSqlServerSinkTraits(connectionString, tableName, schemaName, columnOptions, formatProvider, autoCreateSqlTable); |
| 58 | + |
| 59 | + |
| 60 | + } |
| 61 | + |
| 62 | + /// <summary>Emit the provided log event to the sink.</summary> |
| 63 | + /// <param name="logEvent">The log event to write.</param> |
| 64 | + public void Emit(LogEvent logEvent) |
| 65 | + { |
| 66 | + try |
| 67 | + { |
| 68 | + using (SqlConnection connection = new SqlConnection(_traits.ConnectionString)) |
| 69 | + { |
| 70 | + connection.Open(); |
| 71 | + using (SqlCommand command = connection.CreateCommand()) |
| 72 | + { |
| 73 | + command.CommandType = CommandType.Text; |
| 74 | + |
| 75 | + StringBuilder fieldList = new StringBuilder($"INSERT INTO [{_traits.SchemaName}].[{_traits.TableName}] ("); |
| 76 | + StringBuilder parameterList = new StringBuilder(") VALUES ("); |
| 77 | + |
| 78 | + int index = 0; |
| 79 | + foreach (var field in _traits.GetColumnsAndValues(logEvent)) |
| 80 | + { |
| 81 | + if (index != 0) |
| 82 | + { |
| 83 | + fieldList.Append(','); |
| 84 | + parameterList.Append(','); |
| 85 | + } |
| 86 | + |
| 87 | + fieldList.Append(field.Key); |
| 88 | + parameterList.Append("@P"); |
| 89 | + parameterList.Append(index); |
| 90 | + |
| 91 | + SqlParameter parameter = new SqlParameter($"@P{index}", field.Value ?? DBNull.Value); |
| 92 | + |
| 93 | + // The default is SqlDbType.DateTime, which will truncate the DateTime value if the actual |
| 94 | + // type in the database table is datetime2. So we explicitly set it to DateTime2, which will |
| 95 | + // work both if the field in the table is datetime and datetime2, which is also consistent with |
| 96 | + // the behavior of the non-audit sink. |
| 97 | + if (field.Value is DateTime) |
| 98 | + parameter.SqlDbType = SqlDbType.DateTime2; |
| 99 | + |
| 100 | + command.Parameters.Add(parameter); |
| 101 | + |
| 102 | + index++; |
| 103 | + } |
| 104 | + |
| 105 | + parameterList.Append(')'); |
| 106 | + fieldList.Append(parameterList.ToString()); |
| 107 | + |
| 108 | + command.CommandText = fieldList.ToString(); |
| 109 | + |
| 110 | + command.ExecuteNonQuery(); |
| 111 | + } |
| 112 | + } |
| 113 | + } |
| 114 | + catch (Exception ex) |
| 115 | + { |
| 116 | + SelfLog.WriteLine("Unable to write log event to the database due to following error: {1}", ex.Message); |
| 117 | + throw; |
| 118 | + } |
| 119 | + } |
| 120 | + |
| 121 | + /// <summary> |
| 122 | + /// Releases the unmanaged resources used by the Serilog.Sinks.MSSqlServer.MSSqlServerAuditSink and optionally |
| 123 | + /// releases the managed resources. |
| 124 | + /// </summary> |
| 125 | + /// <param name="disposing">True to release both managed and unmanaged resources; false to release only unmanaged |
| 126 | + /// resources.</param> |
| 127 | + protected virtual void Dispose(bool disposing) |
| 128 | + { |
| 129 | + if (disposing) |
| 130 | + { |
| 131 | + _traits.Dispose(); |
| 132 | + } |
| 133 | + } |
| 134 | + |
| 135 | + /// <summary> |
| 136 | + /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. |
| 137 | + /// </summary> |
| 138 | + public void Dispose() |
| 139 | + { |
| 140 | + Dispose(true); |
| 141 | + GC.SuppressFinalize(this); |
| 142 | + } |
| 143 | + } |
| 144 | +} |
0 commit comments