Azure Web App Trace logs not appearing in log - c#

I am using Azure Web App Application Logging, and I followed the online tutorial, and made the following setup:
I get an exception and in my catch block I have the following code:
Trace.TraceError("abc");
Trace.TraceInformation("abc");
Trace.TraceWarning("abc");
Trace.WriteLine("abc");
Console.WriteLine("abc");
In the logs I get this:
2017-02-13 03:30:14 ~1ENGINEMAILERAPI GET /api/vfs/site/wwwroot/
_=1486950157594&X-ARR-LOG-ID=149fee3f-8da3-460e-816e-10e7a4b95f1d 443 - 121.121.23.217 Mozilla/5.0+(Windows+NT+6.3;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/56.0.2924.87+Safari/537.36
- https://web1.appsvcux.ext.azure.com/websites/WebsitesContent/WebsitesIndex?cacheability=3&defaultCloudName=azure&extensionName=WebsitesExtension&shellVersion=5.0.302.608%20(production%233ec7ddd.170201-1022)&traceStr=&region=southeastasia&flight=0&defaultCacheEvictionDelay=105000&websitesextension_enablemonitoringgroup=true&websitesextension_newauditlogs=true&websitesextension_resourcemenu=true&websitesextension_seetemplate=true&pageVersion=5.12.32.464175.170208-1137&l=en.en-us&trustedAuthority=portal.azure.com
enginemailerapi.scm.azurewebsites.net 200 0 0 992 1923 62
How can I get my application logging to show up?

According to the log format of error message you provided, I assumed that the log file you provided is belongs to Web Server Logs ( under /LogFiles/http/RawLogs) which formatted using W3W Logging. Based on your configuration, you have both enabled file system and blob storage for Application Logging. You could retrieve your application logs as follows:
Application Logging (Filesystem)
For a simple way, you could leverage KUDU, click "Debug console > CMD" and cd LogFiles\Application, then you could retrieve your logs as follows:
Application Logging (Blob)
You could leverage Microsoft Azure Storage Explorer to retrieve your logs as follows:
UPDATE:

Related

ASMX Webservice cannot write log for source Application error - access is denied for EventLog

I'm currently working on a legacy asp.net webservice (asmx) hosted on an IIS 10 on Windows Server 2016.
In IIS the webservice is currently running with Identity ApplicationPoolIdentity. This can be changed.
I need to log Messages into the Windows Event Viewer, I use "Application Error" as the EventSource, as it apparently is an already existing event source on windows.
Therefore I refer to this post and use the following C# code:
try
{
System.Diagnostics.EventLog.WriteEntry("Application Error", "EventLog Test - Code EventLog", EventLogEntryType.Error);
}
catch (Exception ex)
{
// log error to file
}
When I run the application, I only get the following error log:
Unable to open log for source Application Error. You may not have write access.
Which settings could I adjust in IIS/registry/C# to achieve a log into my Windows Event Viewer?
Do you know how to solve this error?
This problem occurs because by default the user token of the application doesn't have the required user rights to write to the Windows event logs because of limited security access.
To provide the required permissions to the thread identity, modify the security of the event log through the below registry keys on the server machine. You should select the event log that your application is writing to:
HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\Eventlog\Application\CustomSD
HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\Eventlog\System\CustomSD
The CustomSD registry value is of type REG_SZ and contains a security descriptor in Security Descriptor Definition Language (SDDL) syntax.
More information you can refer to this link: https://learn.microsoft.com/en-us/troubleshoot/developer/webapps/aspnet/development/fail-write-event-log#resolution.

Azure: How to write and read custom log messages in ASP.NET Core application in Azure?

I want to achieve the following:
Have custom log statements in my ASP.NET Core web service application.
Deploy my application to Azure (in my case using Pulumi).
Call the webservice so it triggers the logging code.
Read the logged messages, either programmatically or via the Azure browser-based GUI.
I am targeting .NET 5.0.
In my code I do something like this:
public class MyController : ControllerBase
{
private readonly ILogger<MyController> _logger;
public MyController(ILogger<MyController> logger) => _logger = logger;
public async Task<ActionResult<something>> DoStuff()
{
_logger.LogInformation("Hello, World!");
...
}
}
My Pulumi code contains this:
var app = new AppService(
"kmsApp",
new AppServiceArgs
{
Logs = new AppServiceLogsArgs
{
ApplicationLogs = new AppServiceLogsApplicationLogsArgs { FileSystemLevel = "Error" },
DetailedErrorMessagesEnabled = true,
FailedRequestTracingEnabled = true,
HttpLogs = new AppServiceLogsHttpLogsArgs
{
FileSystem = new AppServiceLogsHttpLogsFileSystemArgs { RetentionInDays = 1, RetentionInMb = 35 }
}
}
},
...);
With the above, when I am running my application in debug mode in Visual Studio, I can see the log messages in the Output pane. So the logging code definitely gets triggered. But when I deploy my application to Azure, I don't know how to get the log messages, and I find the Azure GUI confusing.
What I am struggling with is this:
What configuration do I need to do in my code - e.g. NuGet packages or stuff in my Program and Startup classes?
What configuration do I need to do in Azure?
Where in the Azure browser-based GUI do I go to see these log messages?
How can I fetch these logs programmatically (either via Pulumi or the raw Azure API)?
I have looked for documentation, of course, but I find the documentation labyrinthine. Most of it seems to be about diagnostics such as response time. I just want to view my own custom log messages from my code...
Posts like this one give some hints, but after reading the thread it is still nebulous to me how to read the logs: ASP.NET Core trace logging on Azure with Application Insights
There probably exists good documentation and guides. Please help me find them.
Thanks in advance!
You have several options:
Use az webapp log command from PowerShell to configure your application to log to files
Use az webapp log tail command from PowerShell to see the logs in real time
Configure the application logging manually from the Azure Portal
Enable Application Insights for app service
For downloading the logs use the az webapp log download command or connect to the logs directory with FTP
I think I figured out what was missing. I did two things.
First thing was to change my error level in Pulumi from "Error" to "Verbose":
ApplicationLogs = new AppServiceLogsApplicationLogsArgs { FileSystemLevel = "Verbose" },
The other thing was to install a site extension:
Go to app service in Azure.
In the left-hand menu under Monitoring go to App Service logs.
Click the banner that says Click here to install the ASP.NET Core site extensions to enable Application Logging.
After this I was able to see logs by running az webapp log tail as suggested by Igor.
Now I just need to figure out how to do this programmatically with Pulumi.

Can't Seem to See Custom Telemetry in App Insights

I tried adding custom telemetry per the docs (https://learn.microsoft.com/en-us/azure/bot-service/bot-builder-telemetry?view=azure-bot-service-4.0).
I am missing something because I cannot find my custom event in the App Insights logs.
I tried interacting with the bot and searching the App Insights logs for "VeryImportantProperty" and "VeryImportantValue"
I wrote this class:
public class TelemetryMiddleware : TelemetryLoggerMiddleware
{
public TelemetryMiddleware(IBotTelemetryClient telemetryClient, bool logPersonalInformation)
: base(telemetryClient, logPersonalInformation)
{
}
protected override async Task OnReceiveActivityAsync(Activity activity, CancellationToken cancellation)
{
Dictionary<string, string> propertyItems = new Dictionary<string, string>
{
{"VeryImportantProperty", "VeryImportantValue" }
};
var properties = await FillReceiveEventPropertiesAsync(activity, propertyItems);
TelemetryClient.TrackEvent(TelemetryLoggerConstants.BotMsgReceiveEvent, properties);
}
}
I added it in startup.cs as a service available for injection:
services.AddSingleton<IMiddleware, TelemetryMiddleware>();
I also added all the other items named in the article required as injectable services.
I deployed the bot and interacted with it, but I cannot find my VeryImportantValue or property even after a full search of my App Insights logs.
I’m sure I am missing something, but from the docs, I cannot determine what it is.
Any ideas or pointers in the right direction?
You should be able to see these events by going to Azure Portal > All Resources > Application Insights Resource > Overview page > Logs (Analytics) which is along the top, above the details for the Application Insights resource.
Then if you enter the following for your query:
customEvents
| where name == "BotMessageReceived"
and click run (you may have to select the query text you entered before clicking run.
Your VeryImportantProperty data should show under the customDimensions column.
The getting started information is available here.
Edit
If you still cannot see the log entries then you will need to debug where the issue is. The steps I would recommend are:
Get the latest version of the Bot Framework Emulator.
Update your TelemetryMiddleware class to have a the following field private IBotTelemetryClient _telemetryClient;
Update your TelemetryMiddleware constructor to assign the value from the telemetryClient parameter to your new _telemetryClient field.
Update the call inside OnReceiveActivityAsync to use the new _telemetryClient field instead of the TelemetryClient class (you are calling TrackEvent statically currently which isn't what you want.
Run your bot locally using the Bot Framework Emulator.
Add a breakpoint on the line where you call TrackEvent
Create the scenario which should trigger OnReceiveActivityAsync (send a message to the bot).
Use F10 to step over the TrackEvent line and ensure that it is called successfully.
At this stage I would also inspect your variables to ensure they have the values that you expect.
Wait for the event to flow through to App Insights (might take up to 5 minutes).
If this still does not work I would create a new Application Insights API key and updating the following places with the new value:
For local testing:
Your appsettings.json file so that you can test locally.
For production:
The Application Insights Instrumentation key under the Settings tab of your Web App Bot in Azure.
Also check that the value for Application Insights Application Id under the Settings tab of your Web App Bot in Azure matches the Application Id value under the API Access tab of your Application Insights resource.
Follow the steps above to test locally using the emulator.
Once the logs are flowing through locally use the Test in Web Chat functionality to ensure that it is working in production.

Unable to generate log NLog internal logging file on Azure App Service

I run websites and webjobs on Azure App Service and I want to enable NLog internal debugging to troubleshoot some logging problems. In my NLog configuration code I do:
InternalLogger.LogLevel = LogLevel.Trace;
InternalLogger.LogFile = "nlog.txt";
When run locally during development, nlog.txt shows up in the application binary directory (bin). On Azure it does not show up. Assuming perhaps a file system permissions issue I changed the code to:
InternalLogger.LogLevel = LogLevel.Trace;
InternalLogger.LogFile = #"d:\logfiles\nlog.txt";
Azure App Service guarantees that the d:\logfiles\ directory is writable. Yet still no nlog.txt file.
Ideas?
Actually the LogFiles folder is under D:\home in Azure (you mentioned the file path is d:\logfiles\, so I also tried to create a LogFiles folder under D: drive directly, but an 500 internal server error occurs).
Please try to change the value to d:\home\LogFiles\nlog.txt for InternalLogger.LogFile, like InternalLogger.LogFile= #"d:\home\LogFiles\nlog.txt" .
I can see the nlog.txt generated in azure by using the following code:
InternalLogger.LogLevel = LogLevel.Trace;
InternalLogger.LogFile = #"d:\home\LogFiles\nlog.txt";
InternalLogger.Log(LogLevel.Trace, "a text message from here....");
You can refer to the pic below for test result.

Check if an Azure VM is running

I want to query an existing azure virtual machine to check whether it is fully deployed and able to be connected to remotely. Is there any way to do this using the Azure Rest API?
I've outlined my current process and why I desire such a call below.
I am using the Windows Azure management library to create a VM using ComputeManagementClient and the CreateDeploymentAsync function. This then returns a status of Succeeded, if I then do a get on the deployment it has a status of DeploymentStatus.Running.
After this has run I am trying to create a remote powershell connection so I can format the disk. I keep getting an error on this as it is unable to create the session.
WinRM cannot complete the operation. Verify that the specified computer name is valid, that the computer is accessible over the network, and that a firewall exception for the WinRM service is enabled and allows access from this computer. By default, the WinRM firewall exception for public profiles limits access to remote computers within the same local subnet. For more information, see the about_Remote_Troubleshooting Help topic.
If I go to the azure management portal the status is provisioning, I assume this is why i cannot create a session.
Process
CreateAzureVM()
CheckAzureVmCanBeConnectedTo() //I am unable to do this correctly
RunPowershellScriptOnVM() // this fails
You should be able to use Get Deployment to poll for the role's InstanceStatus (note that InstanceStatus != Status). When the InstanceStatus is ReadyRole, you should be able to log into your machine.
There's a distinction between a Deployment status and a Role InstanceStatus. Think of the role as an actual virtual machine, whereas a Deployment may describe multiple VMs.
SubscriptionCloudCredentials certificate = new CertificateCloudCredentials(subscriptionId, x509Certificate);
IComputeManagementClient ComputeManagementClient = new ComputeManagementClient(certificate);
var deployments = ComputeManagementClient.Deployments.GetBySlot(hostedServiceName, DeploymentSlot.YourDeploymentSlot);
var state = deployments.RoleInstances.First().PowerState;
I hope that this will help you.
Without seeing your code it's hard to say exactly what you need to do but I would recommend that you utilise the await keyword to wait for the completion of the call to the Azure API to create the VM. See the code samples under "Deploy a Virtual Machine" in this MSDN guide: http://msdn.microsoft.com/en-us/library/azure/dn722415.aspx#bk_createres

Categories

Resources