Azure Function-App is not logging to console or AppInsights - azure

I have an Azure Function with AzureFunctionVersion v3 and for some time now I don't see any logs in Application Insights or in the Rider Console that are not logged in the FunctionTrigger itself.
[FunctionName("test")]
public IActionResult Test([HttpTrigger(AuthorizationLevel.Function, "delete", Route = BasePath + "/{roomId}")] HttpRequest req,
ILogger log)
{
log.LogInformation("Log is shown");
myservice.DoIt();
}
namespace MyApp.Test.Service {
public MyService(ILoggerFactory loggerFactory)
{
_log = loggerFactory.CreateLogger(GetType().Namespace);
}
public void DoIt() {
_log.LogInformation("Log is not shown");
}
}
My host.json looks like:
"logging": {
"applicationInsights": {
"samplingExcludedTypes": "Request",
"samplingSettings": {
"isEnabled": false
}
},
"logLevel": {
"MyApp.*": "Information"
}
}

Please try to change the logLevel in one of the following ways:
"logLevel": {"MyApp": "Information"}
"logLevel": { "Default": "Information" }

Related

Azure function IConfig using dependency injection

I need some information from config file, I have this information in my local.settings.json
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"FUNCTIONS_WORKER_RUNTIME": "dotnet-isolated",
"EmailProcessConnection": "",
"SendDeveloperMails": 0,
"Email": {
"Email": "",
"Password": ""
},
},
"ConnectionStrings": {
"HumanRisksDbContext": ""
}
}
I have a service which is being called from my time trigger Azure Function. Its constructor is like this
public ControlRisksService(HumanRisksDbContext context,
ILogHandler logHandler, IConfiguration configuration)
{
this.context = context;
_logHandler = logHandler;
_config = configuration;
}
I need to get information from _config like this later on,
_config.GetValue<bool>("SendDeveloperMails")
How can I get this information?
You can get information from the local.settings.json using EnvironmentVariable:
var config = new ConfigurationBuilder().AddEnvironmentVariables().Build();
var connString = config["ConnectionStrings"];
Also, you need to put the updated local.settings.json file into the D:\MyApp\bin\Debug\net6.0\local.settings.json location, and then register the JSON in the startup file program.cs like below:
var host = new HostBuilder()
.ConfigureAppConfiguration(app =>
{
app.AddJsonFile("appsettings.json", optional: false,
reloadOnChange: true).AddEnvironmentVariables().Build();
}).Build();

Configure log level in Application Insights for Worker Service applications

There is a NET5 console app that is logging from warning and above. This is the documentation followed but it is not working to log information types. It does log warnings. How to change the log level to information?
class Program
{
static async Task Main(string[] args)
{
var services = new ServiceCollection();
var startup = new Startup();
startup.ConfigureServices(services);
var serviceProvider = services.BuildServiceProvider();
var executor = serviceProvider.GetService<IExecutor>();
await executor.ExecuteTestsAsync();
}
}
public class Startup
{
public IConfiguration Configuration { get; }
public Startup()
{
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json");
Configuration = builder.Build();
}
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton(Configuration);
services.AddLogging();
services.AddApplicationInsightsTelemetryWorkerService();
services.AddSingleton<IExecutor, Executor>();
}
}
public Executor(ILogger<Executor> logger)
{
logger.LogInformation("Hello");//Not logged in AppInsights
...
appsettings.json
{
"ApplicationInsights":
{
"InstrumentationKey": "putinstrumentationkeyhere"
},
"Logging":
{
"LogLevel":
{
"Default": "Information"
}
}
}
Also tried this:
services.AddLogging(loggingBuilder => loggingBuilder.AddFilter<Microsoft.Extensions.Logging.ApplicationInsights.ApplicationInsightsLoggerProvider>("Category", LogLevel.Information));
You need to specify the log level for application insights seperately:
{
"ApplicationInsights":
{
"InstrumentationKey": "putinstrumentationkeyhere"
},
"Logging":
{
"LogLevel":
{
"Default": "Information"
},
"ApplicationInsights": {
"LogLevel": {
"Default": "Information"
}
}
}
}
(source)

uploading files - nodejs with typescript and tsoa and swagger

I build a web api with nodejs and express. I used tsoa to generate my routes and a swagger.json file.
I want to be able to upload files via the swagger landing page. I followed the instructions on this page: https://tsoa-community.github.io/docs/file-upload.html
My tsoa.json looks like this:
{
"entryFile": "src/app.ts",
"noImplicitAdditionalProperties": "throw-on-extras",
"controllerPathGlobs": [
"src/**/*.controller.ts"
],
"spec": {
"basePath" : "/",
"description": "",
"outputDirectory": "dist/api/public",
"specVersion": 3,
"specMerging": "recursive",
"paths": {
"/admin/commands/create": {
"post": {
"consumes": [
"multipart/form-data"
],
"parameters": [
{
"in": "formData",
"name": "randomFileIsHere",
"required": true,
"type": "file"
}
]
}
}
}
},
"routes": {
"routesDir": "src/api"
}
}
My controller:
#Tags("Admin Commands")
#Route("admin/commands")
export class AdminCommandController extends Controller
{
#Post('create')
public async CreateCommand(#Request() request: express.Request): Promise<void>
{
try{
await this.handleFile(request);
}
catch {
throw new Error("Error uploading file.");
}
console.log("No error");
}
private handleFile(request: express.Request): Promise<any> {
const multerSingle = multer().single("randomFileIsHere");
return new Promise((resolve, reject) => {
multerSingle(request, undefined, async (error: Error) => {
if (error) {
reject("error");
}
resolve("file will be in request.randomFileIsHere");
});
});
}
}
but when I use the tsoa swagger command to generate the the swagger.json the multipart/form-data is not added to my swagger.json. If I manually add the multipart/form-data to my swagger.json the input field on my swagger landing page is a text field instead of a file field.
"paths": {
"/admin/commands/create": {
"post": {
"operationId": "CreateCommand",
"consumes": [
"multipart/form-data"
],
"parameters": [
{
"in": "formData",
"name": "randomFileIsHere",
"required": true,
"type": "file"
}
],
"responses": {
"204": {
"description": "No content"
}
},
"tags": [
"Admin Commands"
],
"security": []
}
}
}
What am I missing or doing wrong? Furthermore, if this would work, how do i extract the file from the request. The documentation says the file will be added to the randomFileIsHere property of the request object, but if i call request.randomFileIsHere it will obviously throw an error.
I also tried to follow official documents. I was able to save the uploaded file, but codes didnt looked clean to me. Then I realised there is a #UploadedFile decorator. You can add it and read file directly.
#Post("profile-photo")
public async uploadProfilePhoto(#UploadedFile() profilePhoto) {
console.log(profilePhoto)
}
Using a HTTP testing tool ,like Postman, define a field named "profilePhoto" and select a file. You should be able to see it on server terminal.
I think that you can do something like that:
import fs from 'fs';
#Post("profile-photo")
public async uploadProfilePhoto(#UploadedFile('formInputNameForPhoto') profilePhoto) {
fs.writeFileSync('./photo', profilePhoto.buffer);
}
Here is the answer which helped me understand how can I save "ready" multer file object.

Azure Durable Functions. Changing the hubName doesn't affect storage account tables

I'm trying the specify task hub name for my durable function following the documentation.
Here are steps I've done:
host.json
{
"version": "2.0",
"extensions": {
"durableTask": {
"hubName": "%TaskHubName%"
},
// ...
}
}
settings.json
{
"Values": {
"AzureWebJobsStorage": "connection string",
"FUNCTIONS_WORKER_RUNTIME": "dotnet",
"TaskHubName": "mytaskhub"
}
// ...
}
MyFunction.cs
public async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "post", Route = "foo/bar")]
[RequestBodyType(typeof(List<QueryParams>), "Query Parameters")] HttpRequest req,
[OrchestrationClient(TaskHub = "%TaskHubName%")] DurableOrchestrationClient starter)
However I don't see any changes in my Azure Storage Account after running this function. What I'm doing wrong?
I realized that I simply didn't update the tables list...everything is working, sorry for disruption.

ASP.Net vnext api working on localhost, returns 404 on azure

I have created a very small project with ASP.NET vnext with a simple MVC controller and a simple Api controller.
On localhost, everything is working.
If I deploy to an azure website, only MVC part is working
Here is my project.json
{
"webroot": "wwwroot",
"version": "1.0.0-*",
"exclude": [
"wwwroot"
],
"packExclude": [
"node_modules",
"bower_components",
"**.kproj",
"**.user",
"**.vspscc"
],
"dependencies": {
"Microsoft.AspNet.Server.IIS": "1.0.0-beta2",
"Microsoft.AspNet.Mvc": "6.0.0-beta2"
},
"frameworks" : {
"aspnet50" : { },
"aspnetcore50" : { }
}
}
Startup.cs
using Microsoft.AspNet.Builder;
using Microsoft.Framework.DependencyInjection;
namespace Project.Web6
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}
public void Configure(IApplicationBuilder app)
{
// For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
app.UseMvc();
}
}
}
MVC Controller
public class HomeController : Controller
{
// GET: /<controller>/
public string Index()
{
return "Hello world";
}
}
API Controller
[Route("api/[controller]")]
public class MessagesController : Controller
{
// GET: api/values
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
}
The MVC controller works fine, but if I go to http://myproject.azurewebsites.net/api/Messages it returns 404
Here is how I solved the issue:
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action}/{id?}",
defaults: new { controller = "Home", action = "Index" });
});
I have no clue, why it was working locally...

Resources