I have a C# function app which runs a very long operation, and a pipeline which invokes it with the AzureFunction@1 task. The way to use this task is to start the function actual work in a new thread, immediately returning a response to the pipeline that the function has started working, which then start the pipeline countdown.
The first implementation of the function used a single thread and then everything worked as expected, at least log wise. After converting the function to do its job in a new thread (using Task.Run(()=> ... )
, what happens is that at first I see some logs from the new thread in app insights (logged with an ILogger
), but after 3 or 4 entries, it just stops and I have no idea if the function is running or not (The pipeline itself keeps running, waiting for a response).
Is there something needed to be changed with logging when writing in a new thread? Something else that you think can affect it?
EDIT: Seems like using Console.Writeline DOES work. Don't know if it helps identifying the issue
A pseudo code of my code to demonstrate what I'm doing:
public MyWorkingClass(ILogger log) { _logger = log; }
public string Run()
{
//this is not blocking so the return would be called immediately
Task.Run(() =>
{
_logger.LogInformation("starting");
... do more stuff ..
}
return "Starting task";
}
What I eventually did was creating my own ILogger
inside the new thread, using the same configurations as in my host.json
file using this method:
internal static ILogger GetILogger(string loggerName)
{
var configuration = new ConfigurationBuilder()
.AddJsonFile("host.json", optional: true, reloadOnChange: true)
.Build();
using var loggerFactory = LoggerFactory.Create(builder =>
{
builder.AddConfiguration(configuration.GetSection("logging"));
builder.AddConsole();
});
var logger = loggerFactory.CreateLogger(loggerName);
return logger;
}
This method is call at the beginning of the Task.Run
scope and the returned logger works perfectly, including logging to app insight.