In my test POST action am saving 4 different logs (Information, Warning, Error & Critical) into Windows EventLog.
I can see all four in Event viewer but one of them has wrong level. It is marker as 'Error' but it should be marked as 'critical'
Program.cs
return Host.CreateDefaultBuilder(args)
.ConfigureLogging(logger =>
{
logger.ClearProviders();
logger.AddEventLog(new EventLogSettings
{
SourceName = "Website API",
LogName = "Website API"
});
})...
appsettings.json
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
},
"EventLog": {
"LogLevel": {
"Default": "Warning"
}
}
}
Controller
public async Task<IActionResult> TestEndPoint()
{
_logger.LogInformation("LogInformation");
_logger.LogWarning("LogWarning");
_logger.LogError("LogError");
_logger.LogCritical("LogCritical");
return Ok(null);
}
Application: REST API - .NET 5.0
How to log an Event log in the Critical level?
How to create CRITICAL events for Windows Event Viewer?
The critical log level in the EventLog is reserved for system/kernel stuff. There is no same-same mapping between EventLog's critical and .Net Core's critical, it's just mapped as error. It's unfortunate that they have the same name, but different meaning in these two contexts, which maybe confusing.
Related
I'have configured EventLog in my .Net Core 5.0 app to log application events to custom event log:
public Startup (IConfiguration configuration)
{
this.configuration = configuration;
this.logger = LoggerFactory.Create(logging=>{
logging.AddConsole();
logging.AddEventLog(settings=> {
settings.LogName = configuration["EventLogName"];
settings.SourceName = configuration["EventLogSourceName"];
settings.Filter = (category, level) => level >= LogLevel.Trace;
});
}).CreateLogger("Stage server logger");
}
My logging configuration in appsettings:
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
},
"EventLog": {
"LogLevel": {
"Default": "Information"
}
}
}
Everything works just fine but some messages (especialy unhandled exceptions) are written to "Application" log instead of configuration["EventLogName"] log. Any idea how to configure the app to log all messages from the application to configuration["EventLogName"] log?
Thanks a lot
I see that you made an instance of the Logger in your startup.cs. I suppose you registered it in your DI? If yes, you don't see logs from all the sources because they are probably not using your Logger instance. You're simply configuring a specific Logger, not LoggerFactory.
Could you try something like this in the program.cs:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureLogging((hostBuilder, logBuilder) => {
logBuilder.AddConsole();
logBuilder.AddEventLog(set => {
set.LogName = hostBuilder.Configuration["EventLogName"];
set.SourceName = hostBuilder.Configuration["EventLogSource"];
set.Filter = (category, level) => level >= LogLevel.Trace;
});
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
This way, I'm configuring Logger also for the code that I'm not controlling - dependencies.
But if you want a minimal effort solution to fix just unhandled exceptions, the quick fix would be creating a middleware with try-catch and rethrow with logging exception by your specific Logger injected by DI.
We have just started using an Azure Durable Orchestration Function which is linked to application insights.
The telemetry is filling up with logs we cannot seem to stop:
Time 16:51:03 Message funcname-applease: Starting lease renewal with
token xxxxxxxxxxxxxxxxxx Category DurableTask.AzureStorage
EventId 123 ProcessId 8964
Time 16:51:03 Message funcname-applease: Lease renewal with token
xxxxxxxxxxxxxxxxxx succeeded Category DurableTask.AzureStorage
EventId 124
We are getting 100s a minute and despite our Logging settings they are not stopping:
{
"version": "2.0",
"extensions": {
"serviceBus": {
"messageHandlerOptions": {
"maxConcurrentCalls": 1
}
}
},
"functionTimeout": "00:04:59",
"logging": {
"applicationInsights": {
"samplingSettings": {
"isEnabled": true,
"maxTelemetryItemsPerSecond": 20
}
},
"logLevel": {
"default": "Information",
"Function": "Information",
"Host.Results": "Information",
"Host.Aggregator": "Information",
"Host.Triggers.DurableTask": "Error",
"DurableTask.AzureStorage": "Error",
"DurableTask.Core": "Error"
}
}
}
These messages do not appear to have a LogLevel and despite setting all of these to none through to only error they still keep coming.
Does anyone know how to stop these logs?
This message is from azure function app instead of function level.
The log level is to control the function, so it can not control the function app.
I have a .NET Core Worker service using AWS SQS to read messages off a queue. For local development I'm using a default profile with access/secret key stored in that. My appSettings.json is set up as follows:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
},
"TargetCloudWatchGroup": "/aws/insite/workers"
},
"App": {
"TaskProcessDelay": 10000,
"Environment": "NA",
"WorkerType": "INCOMING"
},
"AWS": {
"Region": "ap-southeast-2",
"Profile": "default",
"ProfilesLocation": "C:\\Users\\JMatson\\.aws\\credentials",
"AwsQueueLongPollTimeSeconds": 5,
"QueueUrl": "https://sqs.ap-southeast-2.amazonaws.com/712510509017/insite-incoming-dev"
}
}
I'm using DI to set up the services:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureServices((hostContext, services) =>
{
//var options = hostContext.Configuration.GetAWSOptions();
services.AddDefaultAWSOptions(hostContext.Configuration.GetAWSOptions());
services.AddHostedService<Worker>();
services.AddSingleton<ILogger, Logger>(); // Using my own basic wrapper around NLog for the moment, pumped to CloudWatch.
services.AddAWSService<IAmazonSQS>();
});
But when I run the program in debug, it fails to read a message off the queue within Worker.cs with the following error:
An exception of type 'Amazon.Runtime.AmazonServiceException' occurred in System.Private.CoreLib.dll but was not handled in user code: 'Unable to get IAM security credentials from EC2 Instance Metadata Service.'
On startup it seems like after a couple of tries along the credentials chain it finds my credentials?
[40m[32minfo[39m[22m[49m: AWSSDK[0]
Failed to find AWS credentials for the profile default
AWSSDK: Information: Failed to find AWS credentials for the profile default
[40m[32minfo[39m[22m[49m: AWSSDK[0]
Found credentials using the AWS SDK's default credential search
AWSSDK: Information: Found credentials using the AWS SDK's default credential search
So why is it failing? If I check the immediate window I can see it's picking up my setttings:
?hostContext.Configuration.GetAWSOptions().Profile
"default"
?hostContext.Configuration.GetAWSOptions().ProfilesLocation
"C:\\Users\\JMatson\\.aws\\credentials"
I'm giving my first steps with .Net Core
Just created a web Hello world with
dotnet new web
I can see there's some kind of logging enabled. I just want to log something to the Console.
But I don't know how to access the logger from
app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello World!!!");
});
I tried with Console.WriteLine but it obviously didn't work.
Also tried with NLog following this guide https://github.com/NLog/NLog.Web/wiki/Getting-started-with-ASP.NET-Core-(csproj---vs2017) but I don't know how to inject the logger.
I'm just trying to look around for educational purposes, not looking for a real logger, so perhaps there's a better/easier option.
I could achieve it with this:
[...]
using Microsoft.Extensions.Logging;
[...]
namespace web
{
public class Startup
{
ILogger log;
public Startup(ILoggerFactory loggerFactory)
{
log = loggerFactory.CreateLogger("Logger");
}
[...]
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole();
loggerFactory.AddDebug();
[...]
app.Run(async (context) =>
{
log.LogInformation("logging!");
await context.Response.WriteAsync("Hello World!");
});
}
}
}
also had to add an appsettings.json file to the root of the project
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
}
}
Need your help with the below problem. I'm creating a webapi in .netcore in VS2017, and I'm trying to use the new model of authentication with https://apps.dev.microsoft.com/.
I register the app, create the reply URL to https://localhost:44337/signin-oidc
In .netcore I have the below config
"Authentication": {
"AzureAd": {
"AADInstance": "https://login.microsoftonline.com/",
"Audience": "<my audience>/<Name Of The App Registered>",
"ClientId": "<Registered App ID>",
"Domain": "<Domain of AAD>",
"TenantId": "<Tenant ID of AAD>"
}
},
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
}
Now I'm testing with a Universal App, but, whenever after trying login, always send me this error:
Additional technical information:
Correlation ID: a14b452f-457a-46e6-9601-67383df6ba1a
Timestamp: 2017-05-11 09:42:56Z
AADSTS50011: The reply address 'urn:ietf:wg:oauth:2.0:oob' does not match the reply addresses configured for the application: '<My Application ID>'. More details: not specified
I already confirm the AppID in apps.dev.microsoft.com, and I have also registered the app in AAD (with different ID, I cannot control that)
This is the code of Startup.cs:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseJwtBearerAuthentication(new JwtBearerOptions
{
Authority = Configuration["Authentication: AzureAd:AADInstance"] + Configuration["Authentication: AzureAd:TenantId"],
Audience = Configuration["Authentication:AzureAd:Audience"],
TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
{
ValidIssuer = Configuration["Authentication: AzureAd:AADInstance"] + Configuration["Authentication: AzureAd:TenantId"] + "/ v2.0"
}
});
app.UseMvc();
}
Thanks in advance for your help,
Your UWP App must be registred as a native applcation with the following reply url: urn:ietf:wg:oauth:2.0:oob. Also you have to grant permission for the UWP app to call your API.
Ok, I already solve this problem. Thank you Martin for the help, the solution is similar to your recommendation.
The solution to this problem is:
On https://apps.dev.microsoft.com/ you need to register a new platform as Native and keep that values.