Last active
April 26, 2018 12:23
-
-
Save aaronhoffman/3e319cf519eb8bf76c8f3e4fa6f1b4ae to your computer and use it in GitHub Desktop.
Custom Azure WebJob TraceWriter For SQL Server
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
static void Main() | |
{ | |
var config = new JobHostConfiguration(); | |
// Log Console.Out to SQL using custom TraceWriter | |
// Note: Need to update default Microsoft.Azure.WebJobs package for config.Tracing.Tracers to be exposed/available | |
config.Tracing.Tracers.Add(new SqlTraceWriter( | |
TraceLevel.Info, | |
"{{SqlConnectionString}}", | |
"{{LogTableName}}")); | |
var host = new JobHost(config); | |
host.RunAndBlock(); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class SqlTraceWriter : TraceWriter | |
{ | |
private string SqlConnectionString { get; set; } | |
private string LogTableName { get; set; } | |
public SqlTraceWriter(TraceLevel level, string sqlConnectionString, string logTableName) | |
: base(level) | |
{ | |
this.SqlConnectionString = sqlConnectionString; | |
this.LogTableName = logTableName; | |
} | |
public override void Trace(TraceEvent traceEvent) | |
{ | |
using (var sqlConnection = this.CreateConnection()) | |
{ | |
sqlConnection.Open(); | |
using (var cmd = new SqlCommand(string.Format("insert into {0} ([Source], [Timestamp], [Level], [Message], [Exception], [Properties]) values (@Source, @Timestamp, @Level, @Message, @Exception, @Properties)", this.LogTableName), sqlConnection)) | |
{ | |
cmd.Parameters.AddWithValue("Source", traceEvent.Source ?? ""); | |
cmd.Parameters.AddWithValue("Timestamp", traceEvent.Timestamp); | |
cmd.Parameters.AddWithValue("Level", traceEvent.Level.ToString()); | |
cmd.Parameters.AddWithValue("Message", traceEvent.Message ?? ""); | |
cmd.Parameters.AddWithValue("Exception", traceEvent.Exception?.ToString() ?? ""); | |
cmd.Parameters.AddWithValue("Properties", string.Join("; ", traceEvent.Properties.Select(x => x.Key + ", " + x.Value?.ToString()).ToList()) ?? ""); | |
cmd.ExecuteNonQuery(); | |
} | |
} | |
} | |
private SqlConnection CreateConnection() | |
{ | |
return new SqlConnection(this.SqlConnectionString); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
see also
http://aaron-hoffman.blogspot.com/2016/07/write-azure-webjob-logs-to-sql.html
https://github.com/stonefinch/azureintro