Skip to content

Instantly share code, notes, and snippets.

@brettsam
Last active November 15, 2019 17:55
Show Gist options
  • Save brettsam/f0cb90806d7a9dff5d0aaa3068fa71bd to your computer and use it in GitHub Desktop.
Save brettsam/f0cb90806d7a9dff5d0aaa3068fa71bd to your computer and use it in GitHub Desktop.
Logging Repro
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
namespace MyNamespace
{
public class Function1
{
private Service<MyOtherClass> _service;
public Function1(Service<MyOtherClass> service)
{
_service = service;
}
[FunctionName("Function1")]
public async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
ILogger log)
{
_service.Log();
log.LogInformation("C# HTTP trigger function processed a request.");
string name = req.Query["name"];
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
dynamic data = JsonConvert.DeserializeObject(requestBody);
name = name ?? data?.name;
return name != null
? (ActionResult)new OkObjectResult($"Hello, {name}")
: new BadRequestObjectResult("Please pass a name on the query string or in the request body");
}
}
}
using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using MyNamespace;
[assembly: FunctionsStartup(typeof(Startup))]
namespace MyNamespace
{
public class Startup : FunctionsStartup
{
public override void Configure(IFunctionsHostBuilder builder)
{
RegisterService<MyOtherClass>(builder);
}
private static void RegisterService<T>(IFunctionsHostBuilder builder)
{
builder.Services.AddLogging(options =>
{
options.AddFilter(typeof(T).FullName, LogLevel.Information);
});
builder.Services.AddSingleton<Service<T>>();
}
}
public class MyOtherClass
{
}
public class Service<T>
{
private ILogger<T> _logger;
public Service(ILogger<T> logger)
{
_logger = logger;
}
public void Log()
{
_logger.LogTrace("Trace");
_logger.LogInformation("Information");
_logger.LogError("Error");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment