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)
Related
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();
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" }
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.
I want to add a dynamic attribute to a pattern I am using with log4js.
I am using some custom pattern, something like this:
"%d{} %-6p[%thread] %c [%x{context}]: %m%n%r"
Context is the dynamic value that I want to set with some unique id generated for each user on the server side.
There is a way to add dynamic value when creation log4js configuration by using "tokens" and "context" attributes.
But in this case values should be set during the log creation.
Is there a way to add some dynamic attribute that is set when the actual message is written to the log and not during the config phase?
Right now I am doing something like this:
log4js.configure(
{
appenders: { "file": { "type": "file", "filename": "service.log", "maxLogSize": 102400, "backups": 5, "category": "com.nextinsurance", "layout": { "type": "pattern", "pattern": "%d{} %-6p[%thread] %c [%x{context}]: %m%n%r", "tokens" : {context: function(logEvent){ return getContextFromData(logEvent) } } } }, "console" : {"type": "console"} },
categories: { "default": { "appenders": ["file", "console"], "level": "info" } }
}
);
But want to inject this value when writing to log, something like
logger.info(Message, {context: context_value})
You can use logEvent data property to fetch context. logEvent data property contains the array of args passed in log event.
Here is the sample code:
var log4js = require("log4js");
log4js.configure({
appenders: {
out: {
type: 'stdout',
layout: {
type: 'pattern',
pattern: '[%d] [%p] [%c] [%x{context}] - %m%n',
tokens: {
context: function(logEvent) {
let returnVal = logEvent.data[1] ? logEvent.data[1].context : undefined;
if (returnVal) {
logEvent.data.pop();
} else {
returnVal = 'null'; // set any default value if context is not passed.
}
return returnVal;
}
}
}
}
},
categories: {
default: {
appenders: ['out'],
level: 'INFO'
}
}
});
log4js.level = 'info';
let logger = log4js.getLogger();
logger.info('Hello', { context: 'context_value'}); // prints [2019-09-13T16:50:48.818] [INFO] [default] [context_value] - Hello
logger.info('Hello'); // prints [2019-09-13T16:50:48.820] [INFO] [default] [null] - Hello
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...