Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Azure Functions Logging Provider
public static class AzureFunctionsLoggerBuilderExtensions
{
public static void AddAzureFunctions(this ILoggingBuilder logging, TraceWriter writer)
{
logging.Services.AddSingleton(writer);
logging.Services.AddSingleton<ILoggerProvider, AzureFunctionsLoggerProvider>();
}
}
public class AzureFunctionsLoggerProvider : ILoggerProvider
{
private readonly TraceWriter _traceWriter;
public AzureFunctionsLoggerProvider(TraceWriter traceWriter)
{
_traceWriter = traceWriter;
}
public ILogger CreateLogger(string categoryName)
{
return new AzureFunctionsLogger(categoryName, _traceWriter);
}
public void Dispose()
{
}
private class AzureFunctionsLogger : ILogger, ISupportExternalScope
{
private readonly string _categoryName;
private readonly TraceWriter _traceWriter;
private IExternalScopeProvider _scopeProvider;
public AzureFunctionsLogger(string categoryName, TraceWriter traceWriter)
{
_categoryName = categoryName;
_traceWriter = traceWriter;
}
public IDisposable BeginScope<TState>(TState state)
{
return null;
}
public bool IsEnabled(LogLevel logLevel)
{
return true;
}
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
{
var logLevelString = GetLogLevelString(logLevel);
var builder = new StringBuilder();
builder.AppendLine($"{logLevelString}: {_categoryName}[{eventId.Id}]");
builder.Append($" {formatter(state, exception)}");
switch (logLevel)
{
case LogLevel.Trace:
case LogLevel.Debug:
_traceWriter.Verbose(builder.ToString(), source: _categoryName);
break;
case LogLevel.Warning:
_traceWriter.Warning(builder.ToString(), source: _categoryName);
break;
case LogLevel.Error:
case LogLevel.Critical:
_traceWriter.Error(builder.ToString(), source: _categoryName);
break;
default:
_traceWriter.Info(builder.ToString(), source: _categoryName);
break;
}
}
public void SetScopeProvider(IExternalScopeProvider scopeProvider)
{
_scopeProvider = scopeProvider;
}
}
private static string GetLogLevelString(LogLevel logLevel)
{
switch (logLevel)
{
case LogLevel.Trace:
return "trce";
case LogLevel.Debug:
return "dbug";
case LogLevel.Information:
return "info";
case LogLevel.Warning:
return "warn";
case LogLevel.Error:
return "fail";
case LogLevel.Critical:
return "crit";
default:
throw new ArgumentOutOfRangeException(nameof(logLevel));
}
}
}
public static async Task<HttpResponseMessage> Run(..., TraceWriter log)
{
var connection = new HubConnectionBuilder()
.WithUrl("https://signalr-samples.azurewebsites.net/default")
.ConfigureLogging(logging =>
{
// Register the logger provider using the AddAzureFunctions extension method,
// passing in the TraceWriter instance.
logging.AddAzureFunctions(log);
})
.Build();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.