KQL - WorkDays Restrict - azure

i have a Question about an KQL Query.
I would like to restrict the Query only of the Work Days from Monday to Friday.
How can i build this in KQL Query?
Thanks a lot.
A short Edit:
How can i build this in a existing Query with a Timestamp "timestamp between (datetime(06:00) .. datetime(15:00))" ??
For Example here the Code:
availabilityResults
| where timestamp between (datetime(06:00) .. datetime(15:00))
| where true
| where name == "warmup" and true
| extend percentage = toint(success) * 100
| render timechart
And now i would like only have an Result when is an Work Day
Best Regards,
Phil

dayofweek()
// Sample data generation. Not part of the solution.
let t = range Date from startofday(ago(28d)) to now() step 1d;
// Solution starts here.
t
| where dayofweek(Date)/1d between (1 .. 5)
Date
2022-10-05T00:00:00Z
2022-10-06T00:00:00Z
2022-10-07T00:00:00Z
2022-10-10T00:00:00Z
2022-10-11T00:00:00Z
2022-10-12T00:00:00Z
2022-10-13T00:00:00Z
2022-10-14T00:00:00Z
2022-10-17T00:00:00Z
2022-10-18T00:00:00Z
2022-10-19T00:00:00Z
2022-10-20T00:00:00Z
2022-10-21T00:00:00Z
2022-10-24T00:00:00Z
2022-10-25T00:00:00Z
2022-10-26T00:00:00Z
2022-10-27T00:00:00Z
2022-10-28T00:00:00Z
2022-10-31T00:00:00Z
2022-11-01T00:00:00Z
2022-11-02T00:00:00Z
Fiddle

Here The Solution of my Specific Answer:
Table
| where timestamp between (datetime(06:00) .. datetime(15:00))
| where dayofweek(timestamp) != time(6.00:00:00)
| where dayofweek(timestamp) != time(0.00:00:00)
| render timechart

Related

How can I solve day problem in appinsight alert?

I have a problem with my kusto query. this kusto query is running inside the alert call. I tried to send a notification to our client via email.
Scenario :
I am trying to send messages between 7 am and 13 am on Saturday. (only Saturday) But I am getting messages also Sunday. There is nothing here below the query. I think it is related to app insight alert.
requests
| extend Customer= trim_end('/', tostring(split(customDimensions.source, '//')[1]))
| extend alarmOK=iif(datetime_diff('minute', now(), timestamp) > 20, 1, 0)
| extend issaturday=iif(dayofweek(timestamp) == 6d, 1, 0)
| extend workinghour = hourofday(timestamp)
| extend
sendnotify1=iif(workinghour >= 7 and workinghour < 13, 1, 0),
sendnotify2=iif(hourofday(now()) >= 7 and hourofday(now()) < 13, 1, 0)
| extend alarmmessage = "alert message"
| where timestamp > ago(24h) and Customer == "mycustomer"
| where issaturday == 1
| where workinghour >= 7 and workinghour < 13
| top 1 by timestamp desc
All datetimes in Kusto are stored as UTC.
Use datetime_utc_to_local to get the timestamp in your local time zone, e.g.:
let timestamp = now();
print datetime_utc_to_local(timestamp, "Australia/Melbourne")
Fiddle
print_0
2023-01-10T21:10:08.0645922Z
P.S.
Your query could be simplified significantly.
KQL supports the Boolean data type (bool).
KQL supports datetime & timespan arithmetic.
Even if for some reason you wanted to add a column named issaturday and then filter by it, it could easily be done like this:
| extend issaturday = dayofweek(timestamp) == 6d | where issaturday
// Sample data generation. Not part of the solution.
let requests = materialize(
range i from 1 to 100 step 1
| extend timestamp = ago(7d * rand())
);
// Solution starts here
requests
| where dayofweek(timestamp) == 6d
and timestamp % 1d between (7h .. 13h)
and now() - timestamp > 20m
i
timestamp
5
2023-01-07T08:37:39.3449345Z
80
2023-01-07T09:07:36.4794478Z
83
2023-01-07T10:51:19.4051319Z
Fiddle

How to write a Kusto query to get previous month logs in sentinel?

| where TimeGenerated > ago(30d)
only gives me the last 30 days logs and I'm searching for a query to get previous month logs from a table, so I can export it directly into Power BI.
Here is how you can do it below. I am showing two ways. The 'easy' way is to just hand jam the dates in for the month. The harder way requires you to use the make_datetime function.
// The Easy 'Manual' Way
AuditLogs
| where TimeGenerated >= datetime('2021-08-01') and TimeGenerated <= datetime('2021-08-31')
// Automated Way
let lastmonth = getmonth(datetime(now)) -1;
let year = getyear(datetime(now));
let monthEnd = endofmonth(datetime(now),-1);
AuditLogs
| where TimeGenerated >= make_datetime(year,lastmonth,01) and TimeGenerated <= monthEnd
https://learn.microsoft.com/en-us/azure/data-explorer/kusto/query/make-datetimefunction
Just wanted to add on to #Ken W MSFT's great query, by suggesting this for the automation
let time_start = startofmonth(datetime(now), -1);
let time_end = endofmonth(datetime(now),-1);
AuditLogs
| where TimeGenerated between (time_start .. time_end)

error with user-defined function in kusto query

I tried to run below query as user-defined function in kusto but always gives me an error. can someone help me to understand what i am missing here? When i run the query seprately it works but i want to use it like a function as i want to call it separately for every month and union the results .
let availability = (starttime:datetime , endtime:datetime )
{
//let month = format_datetime(starttime,"yyyy-M-dd");
Heartbeat
//| where TimeGenerated >= startofweek(ago(21d
| where TimeGenerated > starttime and TimeGenerated < endtime
| where ResourceId !=""
| summarize heartbeat_per_hour=count() by bin_at(TimeGenerated, 1h, starttime), Computer
| extend available_per_hour=iff(heartbeat_per_hour>0, true, false)
| summarize total_available_hours=countif(available_per_hour==true) by Computer
| extend total_number_of_buckets=round((endtime-starttime)/1h)
| extend availability_rate=total_available_hours*100/total_number_of_buckets
//| extend month
};
let starttime = startofday(datetime("2020-09-01 00:00:00 AM"));
let endtime = endofday(datetime("2020-09-30 11:59:59 PM"));
availability(starttime,endtime)

Custom aggregate function on summarize

I want to calculate a statistic mode on a column during summarization of a table.
My CalculateMode function that I try is like this:
.create function CalculateMode(Action:int, Asset:string, Start:long, End:long) {
Event
| where Time between (Start .. End) and IdAction == Action and IdDevice == Device
| summarize Count = countif(isnotnull(Result) and isnotempty(Result)) by tostring(Result)
| top 1 by Count desc
| project ActionResult
}
OR
.create function CalculateMode(T:(data:dynamic)) {
T
| summarize Count = countif(isnotnull(data) and isnotempty(data)) by tostring(data)
| top 1 by Count desc
| project data
}
when i using first coding on summarizing:
Event
| summarize Result = CalculateMode(toint(IdAction), tostring(IdDevice), Start, End) by Category
Obtain this error No tabular expression statement found and
when i using second coding on summarizing:
Event
| summarize Result = CalculateMode(Result) by Category
I get this error
CalculateMode(): argument #1 must be a tabular expression
What can I do? Where am I doing something wrong?
Thanks
You can't just do summarize Result = CalculateMode(Result). You have to decide which aggregation function you want to summarize by (see the full list of aggregation functions here).

How to calculate time grain based on selected period from azure dashboard in a custom chart

While writing a kusto query to create a custom chart on my azure dashboard, I want to be able to calculate the time grain based on the period the user selected on the dashboard.
For example: last 4h => time grain 2 mins, last 24h => 10 mins
I tried the following to calculate the period because we are still unable to access it (as far as I could find on the internet).
let timeGrain = traces
| summarize min_time = min(timestamp), max_time = max(timestamp)
| extend timeWindow = max_time - min_time // days / hrs/ min / seconds
| project timeWindow
| extend timeGrain = case(timeWindow <= 4h, "2m",
timeWindow <= 12h, "5m",
timeWindow <= 24h, "10m",
"2h")
| project timeGrain;
The query returns me the time grain I want to achieve but I am unable to use this variable inside of my other query.
traces
...
| summarize percentile(DurationInMs, 50) by bin(timestamp, timeGrain), CommandType
| render areachart with (ytitle = "Duration In Ms", xtitle = "Timestamp");
(I know traces isn't the best place to store data regarding duration, we are gonna change this to metrics but it's not the scope of the question)
This gives me the following error: 'summarize' operator: Failed to resolve scalar expression named 'timeGrain'
Is there a way to fix this error or is there a better way to create a dynamic time grain?
Obviously I do not have the same fields in my traces but you should use a timespan instead of a string to define timeGrain.
Also, to use the query result timeGrain as a variable, use toscalar (docs):
let timeGrain = toscalar(traces
| summarize min_time = min(timestamp), max_time = max(timestamp)
| extend timeWindow = max_time - min_time // days / hrs/ min / seconds
| project timeWindow
| extend timeGrain = case(timeWindow <= 4h, 2m,
timeWindow <= 12h, 5m,
timeWindow <= 24h, 10m,
2h)
| project timeGrain);
traces
| summarize count() by bin(timestamp, timeGrain)
| order by timestamp desc
this works just fine.
This may not be a direct answer to the question but may be useful for others who do not want to create logic to infer time grain from time range.
Use a workbook to create chart from app insights query. Add a time range parameter and refer to the parameter in query. {TimeRange:grain} would give you granularity corresponding to time range selected. Now pin the query part to dashboard and voila! Your chart is ready to use time range selected on dashboard, auto refresh parameter.
Create workbook and pin parts to dashboard: https://learn.microsoft.com/en-us/azure/azure-monitor/visualize/workbooks-overview
Time range parameter: https://learn.microsoft.com/en-us/azure/azure-monitor/visualize/workbooks-time

Resources