Skip to content

Instantly share code, notes, and snippets.

@aaronhoffman
Last active April 26, 2018 12:23
Show Gist options
  • Save aaronhoffman/3e319cf519eb8bf76c8f3e4fa6f1b4ae to your computer and use it in GitHub Desktop.
Save aaronhoffman/3e319cf519eb8bf76c8f3e4fa6f1b4ae to your computer and use it in GitHub Desktop.
Custom Azure WebJob TraceWriter For SQL Server
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();
}
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