Raising Alerts from Application Insights log based on percentage? - azure-application-insights

I can write a query in application insights that gives me a percentage as a scalar. I want to create alert if that percentage is > X . How can this be done using log based alerts?
Basically, I have a lot of machines that send telemetry to application insights. Sometimes they log some exceptions. I send MachineName in customDimensions for all the logs. So I can get the names of all the machines that sent logs in last 24 hours. The exceptions are also sent with MachineName in customDimensions. When a particular error is raised by more than X% machines in last 24 hours, I want to raise an alert.
The way to write alert logic is using 'Number of Results' which cannot be used for this since it automatically adds '|count' to the query. The other way is using 'Metric Measurement', which I am guessing should help me raise an alert like this but I'm unable to figure out how.
I can get the total machine count by this query:
let num_machines = traces
| summarize by tostring(customDimensions["MachineName"])
| count;
I can get the number of machines that reported an exception like this:
let num_error_machines = exceptions
| where customDimensions["Message"] contains "ExceptionXRaised"
| summarize by tostring(customDimensions["MachineName"])
| count;
finally, i can get the percentage of machines that raised the issue like this:
print toscalar(num_error_machines)*100/toscalar(num_machines)
I am not sure how to use this result to raise an alert using MetricMeasurement. This needs to be modified somehow to get AggregatedValue and use bin, I am not sure if that is possible / how that query will be.

Sorry for the late reply. I've tested in my side and met many problems indeed.
I found that alert rule doesn't support to monitor the percentage number of the result, it only supports the numbers of query result and Metric measurement. So I think you may give up the percentage and use the num_err_machine like the screenshot below
Pls note, you can't append " ; " at the end of the query or it will give an error like The request had some invalid properties

Related

Get all the action log of an instance and the flavor attached to it

I was wondering if anyone can tell me how to get the action log of the instance using openstacksdk, novaclient. And while getting the action log, I also want to get the flavor attached to it. See the attached picture please.
I actually got the action log using this novaclient module:
novaclient.v2.instance_action.InstanceAction
but it shows me very little details and without the flavor id that I needed. The following fields it shows me are the following:
action, instance_uuid, message, project_id, request_id, start_time and user_id
I hope anyone can tell me how to get it.
I don't think it is possible to get the flavor id from the action list / server event list.
Openstack does not keep a database record of what each request did, or a historic record of the instance states. So you would need to resort to trawling the logs for the request-id ... which is OK for forensics, but does not scale. (And I don't know if the flavor is in the log messages.)
Of course, you could use the APIs (novaclient, openstacksdk) to get the current flavor for the instance, given its instance id. But that isn't exactly what you want.
It is possible record historical information using Gnochi + Ceilometer or similar, but you would need to have set this up already.

tSQLt - How to output a custom failure or success message?

We are using the tSQLt framework and have the below code in the test.
IF #count>0
EXEC tsqlt.fail;
else EXEC tSQLt.AssertEquals 1,1;
I am interested to know how we can display a custom test success or failure message when this test gets executed?
tSQLt.fail takes up to 10 parameters that all get concatenated into a custom failure message.
You also do not need the call to tSQLt.AssertEquals as it, in your case, literally does nothing.
BTW, asserting a count is in almost all cases a bad idea, as it does not really tell you anything about the result. If you get the correct count back, you could still have wrong data. And if you get the incorrect count, you don't have any additional info on what went wrong.
Have a look at tSQLt.AssertEqualsTable or tSQLt.AssertEmptyTable instead.

How to create an alert to notify an user when some amount % of threshold reached DailyAsyncApex Executions

On 2 occasions in the past month, we have managed to hit our daily limit on asynchronous apex executions. Salesforce temporarily increased our limit to 425000 but it will be scaled down to 250000 in a week's time. Once we reach the limit, a lot of the SF functions will fail and this has tremendously impacted both internal staff and external customers.
So to prevent this from happening in the future, we need to create some kind of alert in Salesforce to monitor our daily asynchronous apex method executions. Our maximum daily limit is 250000. The alert will need to create a P3 helpdesk ticket and notify couple of users say USER A and USER B once it reaches 70% threshold.
Kindly advise what is possible to achieve the same
Thanks & Regards,
Harjeet
There's a promising Limits method but it doesn't seem to work currently ("reserved for future use"): System.debug(Limits.getAsyncCalls() + ' / ' + Limits.getLimitAsyncCalls());
There's an idea you can upvote: https://success.salesforce.com/ideaView?id=0873A0000003VIFQA2 ;)
You could query SELECT COUNT() FROM AsyncApexJob WHERE ... but that sounds like a bad idea ;)
I think your best course of action is to use SF REST API. There's a "limits" resource you can fetch. You could do it from SF itself (bad idea because if you'd schedule it to run every hour then well, of course it will contribute to the limit consumption too ;)) or from some external app that'd connect to your SF...
https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/dome_limits.htm
You can quickly try it out for example in workbench.developerforce.com before you decide you do want to deep dive into coding it.
Of course if you have control over your batch jobs, queuable, schedulable & #future calls you could implement some rough counter of executions in a helper object for example... won't help you much if most of the jobs are coming from managed packages though...
Got 1 more idea but it's pretty hardcore - you should be able to make a REST API call from javascript. so you could create a simple VF page (even without any apex controller), put JS callout on it, have it check every 5 mins and do something if threshold is hit... But that means IT person would have to have this page open all the time (perhaps as a home page component)... Messy :)
I was having the exact same issue so I created a simple JsForce script in NodeJS to monitor the call to the /limits endpoint.
You can connect a Free Monitoring service like UpTimerobot.com or PingDom.com and get an email when you find the Word "Warning" >50% or "Error" > 80%.
async function getSfLimits() {
try {
//Let's login into salesforce
const login = await conn.login(SF_USERNAME, SF_PASSWORD+SF_SECURITY_TOKEN);
//Call the API
const sfLimits = await conn.requestGet('/services/data/v51.0/limits');
return sfLimits;
} catch(err) {
console.log(err);
}
}
https://github.com/carlosdevia/salesforcelimits

Errors When Calculating Distance Between Two Addresses

I have the following script which is being used in a spreadsheet to calculate the driving distance between two cities or a city and a zip code of another city. It is being run for approximately 25 locations simultaneously. To better explain, I have cell B3 in which I enter a new city every time. The script is then used in cells adjacent to my 25 plant locations to calculate the distance from each of my plants to the variable city.
It uses google sheets built in mapping api and works on 80% of the calculations but returns "TypeError: Can Not Read Property "legs" from undefined. (line 16). The plants that it fails on vary with every new city so its not like it is for certain locations. It is almost like the api times out before it completes some of them. I split it into two separate scripts with a varied name and that worked for a day but then 20% fail again.
To make things slightly more odd, I have another script that sorts the plants based on closest distance to the variable address. When you sort the plants, even the ones with errors go to their correct location based on distance. So it is like the distance script is obtaining the correct disance but displaying the error anyways.
Clear as mud? Would love any input I could get on how to correct the issue or an alternate mapping api that could solve my problems.
function distancecalcone(origin,destination) {
var directions = Maps.newDirectionFinder()
//Set the Method of Transporation. The available "modes" are WALKING, DRIVING, BICYCLING, TRANSIT.
.setMode(Maps.DirectionFinder.Mode.DRIVING)
//Set the Orgin
.setOrigin(origin)
//Set the Destination
.setDestination(destination)
//Retrieve the Distance
.getDirections();
return directions.routes[0].legs[0].distance.value/1609.34;
}
Have you tried using a try-catch block around directions.routes[0].legs[0].distance.value ?
try{
return directions.routes[0].legs[0].distance.value/1609.34;
}
catch (e){
console.log("error",e)
}
or you could try something like this
alert(directions);
alert(directions.routes[0]);
alert(directions.routes[0].legs[0]);
alert(directions.routes[0].legs[0].distance);
alert(directions.routes[0].legs[0].distance.value);
and so on...to find out which one comes up as undefined the first. That might help you to debug the issue.
Enable Direction Api
1)Go to "google cloud platform"
2)go to "Api and services"
3)search for "direction api" and enable it
The directions service is subject to a quota and a rate limit. Check the return status before parsing the result.
For lots of distances (or at least more than 10), look at the DistanceMatrix.
I'm able to run the script from the Script editor, but not from spreadsheet. The error is "unable to read property legs" when the function is called from spreadsheet. But the property is in place when called from Script editor and contain correct values.
You probably need to use WEB API and have API KEY:
Google Apps Script - How to get driving distance from Maps for two points in spreadsheet

Paypal sandbox negative testing not working

I have set up negative testing for an account then set the error code desired as the Transaction Amount Field for example 106.06 to invoke error code 10606 "Buyer cannot pay” no errors are returned the order is processed.
If I try another error code 10539 “This transaction cannot be processed”. An error is return and the order is not processed.
I am using the The US site error codes: http://www.paypalobjects.com/en_US/ebook/PP_APIReference/Appx-ErrorCodes_and_Messages.html and we are in Australia are these the correct error codes?
Any ideas what is causing this? Is this the correct way to use Negative Testing in the sandbox?
Thanks
I know this is late but I stumbled across the answer for me.
You didn't specify the API Name you are working with DoExpressCheckoutPayment and according to Paypal's Negative Testing Docs we are supposed to use an AMT field and
To trigger an error condition on an amount-related field, specify a error code value as a number with two digits to the right of the decimal point. For example, specify a value of 107.55 to trigger the 10755 error.
I found their information to be completely false! What I finally got working was to use PAYMENTREQUEST_0_AMT and NOT use a decimal.
So here is what I came up with
USER={yourUID}&
PWD={yourPSWD}&
SIGNATURE={yourSig}&
TOKEN={yourToken}&
METHOD=DoExpressCheckoutPayment&
VERSION=119&
PAYMENTREQUEST_0_AMT=10486
Edit:
I later found a better option specifically for the Payment Method Refused (10486) that I mentioned above. Take a look: https://developer.paypal.com/docs/classic/express-checkout/ht_ec_fundingfailure10486/#testing-saleorauth

Resources