grafanalib package
Submodules
grafanalib.cloudwatch module
Helpers to create Cloudwatch-specific Grafana queries.
- class grafanalib.cloudwatch.CloudwatchLogsInsightsTarget(expr='', format='time_series', legendFormat='', interval='', intervalFactor=2, metric='', step=10, target='', instant=False, expression='', id='', logGroupNames=_Nothing.NOTHING, namespace='', refId='', region='default', statsGroups=_Nothing.NOTHING, hide=False, datasource=None)
Bases:
Target
Generates Cloudwatch Logs Insights target JSON structure.
Grafana docs on using Cloudwatch: https://grafana.com/docs/grafana/latest/datasources/cloudwatch/
AWS docs on Cloudwatch Logs Insights: https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/AnalyzingLogData.html
- Parameters:
expression – Cloudwatch Logs Insights expressions
id – unique id
logGroupNames – List of Cloudwatch log groups to query
namespace – Cloudwatch namespace
refId – target reference id
region – Cloudwatch region
statsGroups – Cloudwatch statsGroups
hide – controls if given metric is displayed on visualization
datasource – Grafana datasource name
- to_json_data()
- class grafanalib.cloudwatch.CloudwatchMetricsTarget(expr='', format='time_series', legendFormat='', interval='', intervalFactor=2, metric='', step=10, target='', instant=False, alias='', dimensions=_Nothing.NOTHING, expression='', id='', matchExact=True, metricName='', namespace='', period='', refId='', region='default', statistics=['Average'], statistic='Average', hide=False, datasource=None)
Bases:
Target
Generates Cloudwatch target JSON structure.
Grafana docs on using Cloudwatch: https://grafana.com/docs/grafana/latest/datasources/cloudwatch/
AWS docs on Cloudwatch metrics: https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/aws-services-cloudwatch-metrics.html
- Parameters:
alias – legend alias
dimensions – Cloudwatch dimensions dict
expression – Cloudwatch Metric math expressions
id – unique id
matchExact – Only show metrics that exactly match all defined dimension names.
metricName – Cloudwatch metric name
namespace – Cloudwatch namespace
period – Cloudwatch data period
refId – target reference id
region – Cloudwatch region
statistics – Cloudwatch mathematic statistics (to be deprecated, prefer statistic instead)
statistic – Cloudwatch mathematic statistic
hide – controls if given metric is displayed on visualization
datasource – Grafana datasource name
- to_json_data()
grafanalib.core module
Low-level functions for building Grafana dashboards.
The functions in this module don’t enforce Weaveworks policy, and only mildly encourage it by way of some defaults. Rather, they are ways of building arbitrary Grafana JSON.
- class grafanalib.core.Ae3ePlotly(dataSource=None, targets=_Nothing.NOTHING, title='', cacheTimeout=None, description=None, editable=True, error=False, height=None, gridPos=None, hideTimeOverride=False, id=None, interval=None, links=_Nothing.NOTHING, maxDataPoints=100, minSpan=None, repeat=_Nothing.NOTHING, span=None, thresholds=_Nothing.NOTHING, thresholdType='absolute', timeFrom=None, timeShift=None, transparent=False, transformations=_Nothing.NOTHING, extraJson=None, configuration=_Nothing.NOTHING, data=_Nothing.NOTHING, layout=_Nothing.NOTHING, script="console.log(data)\n var trace = {\n x: data.series[0].fields[0].values.buffer,\n y: data.series[0].fields[1].values.buffer\n };\n return {data:[trace],layout:{title:'My Chart'}};", clickScript='')
Bases:
Panel
Generates ae3e plotly panel json structure GitHub repo of the panel: https://github.com/ae3e/ae3e-plotly-panel :param configuration in json format: Plotly configuration. Docs: https://plotly.com/python/configuration-options/ :param data: Plotly data: https://plotly.com/python/figure-structure/ :param layout: Layout of the chart in json format. Plotly docs: https://plotly.com/python/reference/layout/ :param script: Script executed whenever new data is available. Must return an object with one or more of the
following properties : data, layout, config f(data, variables){…your code…}
- Parameters:
clickScript – Script executed when chart is clicked. f(data){…your code…}
- to_json_data()
- class grafanalib.core.Alert(name, message, alertConditions, executionErrorState='alerting', frequency='60s', handler=1, noDataState='no_data', notifications=_Nothing.NOTHING, gracePeriod='5m', alertRuleTags=_Nothing.NOTHING)
Bases:
object
- Parameters:
alertRuleTags – Key Value pairs to be sent with Alert notifications.
- to_json_data()
- class grafanalib.core.AlertCondition(target=None, evaluator=None, timeRange=None, operator='and', reducerType='last', useNewAlerts=False, *, type='query')
Bases:
object
A condition on an alert.
- Parameters:
target (Target) – Metric the alert condition is based on. Not required at instantiation for Grafana 8.x alerts.
evaluator (Evaluator) – How we decide whether we should alert on the metric. e.g.
GreaterThan(5)
means the metric must be greater than 5 to trigger the condition. SeeGreaterThan
,LowerThan
,WithinRange
,OutsideRange
,NoValue
.timeRange (TimeRange) – How long the condition must be true for before we alert. For Grafana 8.x alerts, this should be specified in the AlertRule instead.
operator – One of
OP_AND
orOP_OR
. How this condition combines with other conditions.reducerType – RTYPE_* Supported reducer types: RTYPE_AVG = ‘avg’ RTYPE_MIN = ‘min’ RTYPE_MAX = ‘max’ RTYPE_SUM = ‘sum’ RTYPE_COUNT = ‘count’ RTYPE_LAST = ‘last’ RTYPE_MEDIAN = ‘median’ RTYPE_DIFF = ‘diff’ RTYPE_PERCENT_DIFF = ‘percent_diff’ RTYPE_COUNT_NON_NULL = ‘count_non_null’
useNewAlerts – Whether or not the alert condition is used as part of the Grafana 8.x alerts. Defaults to False for compatibility with old Grafana alerts, but automatically overridden to true when used inside
AlertExpression
orAlertRulev8
type – CTYPE_*
- to_json_data()
- class grafanalib.core.AlertExpression(refId, expression, conditions=_Nothing.NOTHING, expressionType='classic_conditions', hide=False, intervalMs=1000, maxDataPoints=43200, reduceFunction='mean', reduceMode='strict', reduceReplaceWith=0, resampleWindow='10s', resampleDownsampler='mean', resampleUpsampler='fillna')
Bases:
object
A alert expression to be evaluated in Grafana v9.x+
- Parameters:
refId – Expression reference ID (A,B,C,D,…)
expression – Input reference ID (A,B,C,D,…) for expression to evaluate, or in the case of the Math type the expression to evaluate
conditions – list of AlertConditions
expressionType – Expression type EXP_TYPE_* Supported expression types: EXP_TYPE_CLASSIC EXP_TYPE_REDUCE EXP_TYPE_RESAMPLE EXP_TYPE_MATH
hide – Hide alert boolean
intervalMs – Expression evaluation interval
maxDataPoints – Maximum number fo data points to be evaluated
reduceFunction – Reducer function (Only used if expressionType=EXP_TYPE_REDUCE) Supported reducer functions: EXP_REDUCER_FUNC_MIN EXP_REDUCER_FUNC_MAX EXP_REDUCER_FUNC_MEAN EXP_REDUCER_FUNC_SUM EXP_REDUCER_FUNC_COUNT EXP_REDUCER_FUNC_LAST
reduceMode – Reducer mode (Only used if expressionType=EXP_TYPE_REDUCE) Supported reducer modes: EXP_REDUCER_MODE_STRICT EXP_REDUCER_FUNC_DROP_NN EXP_REDUCER_FUNC_REPLACE_NN
reduceReplaceWith – When using mode EXP_REDUCER_FUNC_REPLACE_NN number that will replace non numeric values
resampleWindow – Intervale to resample to eg. 10s, 1m, 30m, 1h
resampleDownsampler – ‘mean’, ‘min’, ‘max’, ‘sum’
resampleUpsampler – ‘fillna’ - Fill with NaN’s ‘pad’ - fill with the last known value ‘backfilling’ - fill with the next know value
- to_json_data()
- class grafanalib.core.AlertFileBasedProvisioning(groups)
Bases:
object
Used to generate JSON data valid for file based alert provisioning
param alertGroup: List of AlertGroups
- to_json_data()
- class grafanalib.core.AlertGroup(name, rules=_Nothing.NOTHING, folder='alert', evaluateInterval='1m')
Bases:
object
Create an alert group of Grafana 8.x alerts
- Parameters:
name – Alert group name
rules – List of AlertRule
folder – Folder to hold alert (Grafana 9.x)
evaluateInterval – Interval at which the group of alerts is to be evaluated
- group_rules(rules)
- to_json_data()
- class grafanalib.core.AlertList(dashboardTags=_Nothing.NOTHING, description='', gridPos=None, id=None, limit=10, links=_Nothing.NOTHING, nameFilter='', onlyAlertsOnDashboard=True, show='current', sortOrder=1, span=6, stateFilter=_Nothing.NOTHING, title='', transparent=False, alertName='')
Bases:
object
Generates the AlertList Panel.
- Parameters:
dashboardTags – A list of tags (strings) for the panel.
description – Panel description, supports markdown and links.
gridPos – describes the panel size and position in grid coordinates.
id – panel id
limit – Max number of alerts that can be displayed in the list.
nameFilter – Show only alerts that contain nameFilter in their name.
onlyAlertsOnDashboard – If true, shows only alerts from the current dashboard.
links – Additional web links to be presented in the panel. A list of instantiation of DataLink objects.
show – Show the current alert list (ALERTLIST_SHOW_CURRENT) or only the alerts that were changed (ALERTLIST_SHOW_CHANGES).
sortOrder – Defines the sorting order of the alerts. Gets one of the following values as input: SORT_ASC, SORT_DESC and SORT_IMPORTANCE.
span – Defines the number of spans that will be used for the panel.
stateFilter – Show alerts with statuses from the stateFilter list. The list can contain a subset of the following statuses: [ALERTLIST_STATE_ALERTING, ALERTLIST_STATE_OK, ALERTLIST_STATE_NO_DATA, ALERTLIST_STATE_PAUSED, ALERTLIST_STATE_EXECUTION_ERROR, ALERTLIST_STATE_PENDING]. An empty list means all alerts.
title – The panel title.
transparent – If true, display the panel without a background.
alertName – Show only alerts that contain alertName in their name.
- to_json_data()
- class grafanalib.core.AlertRulev8(title, triggers, annotations=_Nothing.NOTHING, labels=_Nothing.NOTHING, evaluateInterval='1m', evaluateFor='5m', noDataAlertState='Alerting', errorAlertState='Alerting', timeRangeFrom=300, timeRangeTo=0, uid=None, dashboard_uid='', panel_id=0, rule_group='')
Bases:
object
Create a Grafana 8.x Alert Rule
- Parameters:
title – The alert’s title, must be unique per folder
triggers – A list of Target and AlertCondition tuples, [(Target, AlertCondition)]. The Target specifies the query, and the AlertCondition specifies how this is used to alert. Several targets and conditions can be defined, alerts can fire based on all conditions being met by specifying OP_AND on all conditions, or on any single condition being met by specifying OP_OR on all conditions.
annotations – Summary and annotations
labels – Custom Labels for the metric, used to handle notifications
evaluateInterval – The frequency of evaluation. Must be a multiple of 10 seconds. For example, 30s, 1m
evaluateFor – The duration for which the condition must be true before an alert fires
noDataAlertState – Alert state if no data or all values are null Must be one of the following: [ALERTRULE_STATE_DATA_OK, ALERTRULE_STATE_DATA_ALERTING, ALERTRULE_STATE_DATA_NODATA ]
errorAlertState – Alert state if execution error or timeout Must be one of the following: [ALERTRULE_STATE_DATA_OK, ALERTRULE_STATE_DATA_ALERTING, ALERTRULE_STATE_DATA_ERROR ]
timeRangeFrom – Time range interpolation data start from
timeRangeTo – Time range interpolation data finish at
uid – Alert UID should be unique
dashboard_uid – Dashboard UID that should be use for linking on alert message
panel_id – Panel ID that should should be use for linking on alert message
- to_json_data()
- class grafanalib.core.AlertRulev9(title, triggers=_Nothing.NOTHING, annotations=_Nothing.NOTHING, labels=_Nothing.NOTHING, evaluateFor='5m', noDataAlertState='Alerting', errorAlertState='Alerting', condition='B', timeRangeFrom=300, timeRangeTo=0, uid=None, dashboard_uid='', panel_id=0)
Bases:
object
Create a Grafana 9.x+ Alert Rule
- Parameters:
title – The alert’s title, must be unique per folder
triggers – A list of Targets and AlertConditions. The Target specifies the query, and the AlertCondition specifies how this is used to alert.
annotations – Summary and annotations Dictionary with one of the following key or custom key [‘runbook_url’, ‘summary’, ‘description’, ‘__alertId__’, ‘__dashboardUid__’, ‘__panelId__’]
labels – Custom Labels for the metric, used to handle notifications
condition – Set one of the queries or expressions as the alert condition by refID (Grafana 9.x)
evaluateFor – The duration for which the condition must be true before an alert fires The Interval is set by the alert group
noDataAlertState – Alert state if no data or all values are null Must be one of the following: [ALERTRULE_STATE_DATA_OK, ALERTRULE_STATE_DATA_ALERTING, ALERTRULE_STATE_DATA_NODATA ]
errorAlertState – Alert state if execution error or timeout Must be one of the following: [ALERTRULE_STATE_DATA_OK, ALERTRULE_STATE_DATA_ALERTING, ALERTRULE_STATE_DATA_ERROR ]
timeRangeFrom – Time range interpolation data start from
timeRangeTo – Time range interpolation data finish at
uid – Alert UID should be unique
dashboard_uid – Dashboard UID that should be use for linking on alert message
panel_id – Panel ID that should should be use for linking on alert message
- to_json_data()
- class grafanalib.core.BarChart(dataSource=None, targets=_Nothing.NOTHING, title='', cacheTimeout=None, description=None, editable=True, error=False, height=None, gridPos=None, hideTimeOverride=False, id=None, interval=None, links=_Nothing.NOTHING, maxDataPoints=100, minSpan=None, repeat=_Nothing.NOTHING, span=None, thresholds=_Nothing.NOTHING, thresholdType='absolute', timeFrom=None, timeShift=None, transparent=False, transformations=_Nothing.NOTHING, extraJson=None, orientation='auto', xTickLabelRotation=0, xTickLabelSpacing=0, showValue='auto', stacking='none', groupWidth=0.7, barWidth=0.97, barRadius=0.0, tooltipMode='single', tooltipSort='none', showLegend=True, legendDisplayMode='list', legendPlacement='bottom', legendCalcs=_Nothing.NOTHING, lineWidth=1, fillOpacity=80, gradientMode='none', axisPlacement='auto', axisLabel='', axisColorMode='text', scaleDistributionType='linear', axisCenteredZero=False, hideFromTooltip=False, hideFromViz=False, hideFromLegend=False, colorMode='palette-classic', fixedColor='blue', mappings=_Nothing.NOTHING, thresholdsMode='absolute', thresholdSteps=_Nothing.NOTHING, overrides=_Nothing.NOTHING)
Bases:
Panel
Generates bar chart panel json structure Grafana docs on Bar chart panel: https://grafana.com/docs/grafana/latest/panels-visualizations/visualizations/bar-chart/
- Parameters:
orientation – Controls the orientation of the chart
xTickLabelRotation – Controls the rotation of bar labels
xTickLabelSpacing – Controls the spacing of bar labels
showValue – Controls the visibility of values
stacking – Controls the stacking of the bar chart
groupWidth – Controls the width of the group
barWidth – Controls the width of the bars
barRadius – Controls the radius of the bars
toolTipMode – Controls the style of tooltips
toolTipSort – Controls the sort order of tooltips, when toolTipMode is ‘All’
showLegend – Controls the visibility of legends
legendDisplayMode – Controls the style of legends, if they are shown.
legendPlacement – Controls the placement of legends, if they are shown
legendCalcs – Controls the calculations to show on legends
lineWidth – Controls the width of lines
fillOpacity – Contorls the opacity of bars
gradientMode – Controls the gradient style of the bars
axisPlacement – Controls the axis placement
axisLabel – Controls the axis labels
axisColorMode – Controls the axis color style
scaleDistributionType – Controls the type of distribution
axisCenteredZero – Controls the centering of the axis
hideFromTooltip – Controls the hiding of tooltips
hideFromViz – Controls the hiding of bars
hideFromLegend – Controls the hiding of legends
colorMode – Controls the color palette of the bars
fixedColor – Controls the color of the bars, when the colorMode is fixed
mappings – Controls the mapping of values
thresholdsMode – Controls the style threshold
thresholdSteps – Controls the treshold steps
overrides – Controls the overriding of certain datas base characteristics
- to_json_data()
- class grafanalib.core.BarGauge(dataSource=None, targets=_Nothing.NOTHING, title='', cacheTimeout=None, description=None, editable=True, error=False, height=None, gridPos=None, hideTimeOverride=False, id=None, interval=None, links=_Nothing.NOTHING, maxDataPoints=100, minSpan=None, repeat=_Nothing.NOTHING, span=None, thresholdType='absolute', timeFrom=None, timeShift=None, transparent=False, transformations=_Nothing.NOTHING, extraJson=None, allValues=False, calc='mean', dataLinks=_Nothing.NOTHING, decimals=None, displayMode='lcd', format='none', label=None, limit=None, max=100, min=0, orientation='horizontal', rangeMaps=_Nothing.NOTHING, thresholdLabels=False, thresholdMarkers=True, thresholds=_Nothing.NOTHING, valueMaps=_Nothing.NOTHING)
Bases:
Panel
Generates Bar Gauge panel json structure
- Parameters:
allValue – If All values should be shown or a Calculation
calc – Calculation to perform on metrics
dataLinks – list of data links hooked to datapoints on the graph
decimals – override automatic decimal precision for legend/tooltips
displayMode – style to display bar gauge in
format – defines value units
labels – option to show gauge level labels
limit – limit of number of values to show when not Calculating
max – maximum value of the gauge
min – minimum value of the gauge
orientation – orientation of the bar gauge
rangeMaps – the list of value to text mappings
thresholdLabel – label for gauge. Template Variables: “$__series_namei” “$__field_name” “$__cell_{N} / $__calc”
thresholdMarkers – option to show marker of level on gauge
thresholds – single stat thresholds
valueMaps – the list of value to text mappings
- to_json_data()
- class grafanalib.core.Column(text='Avg', value='avg')
Bases:
object
Details of an aggregation column in a table panel.
- Parameters:
text – name of column
value – aggregation function
- to_json_data()
- class grafanalib.core.ColumnStyle(alias='', pattern='', align='auto', link=False, linkOpenInNewTab=False, linkUrl='', linkTooltip='', type=_Nothing.NOTHING)
Bases:
object
- to_json_data()
- class grafanalib.core.ConstantInput(name, label, value, description='')
Bases:
object
- to_json_data()
- class grafanalib.core.Dashboard(title, annotations=_Nothing.NOTHING, description='', editable=True, gnetId=None, graphTooltip=0, hideControls=False, id=None, inputs=_Nothing.NOTHING, links=_Nothing.NOTHING, panels=_Nothing.NOTHING, refresh='10s', rows=_Nothing.NOTHING, schemaVersion=12, sharedCrosshair=False, style='dark', tags=_Nothing.NOTHING, templating=_Nothing.NOTHING, time=_Nothing.NOTHING, timePicker=_Nothing.NOTHING, timezone='utc', version=0, uid=None)
Bases:
object
- auto_panel_ids()
Give unique IDs all the panels without IDs.
Returns a new
Dashboard
that is the same as this one, except all of the panels have theirid
property set. Any panels which had anid
property set will keep that property, all others will have auto-generated IDs provided for them.
- to_json_data()
- class grafanalib.core.DashboardLink(asDropdown: bool = False, icon: Literal['bolt', 'cloud', 'dashboard', 'doc', 'external link', 'info', 'question'] = 'external link', includeVars: bool = False, keepTime: bool = True, tags: list[str] = _Nothing.NOTHING, targetBlank: bool = False, title: str = '', tooltip: str = '', type: Literal['dashboards', 'link'] = 'dashboards', uri: str = '')
Bases:
object
Create a link to other dashboards, or external resources.
Dashboard Links come in two flavours; a list of dashboards, or a direct link to an arbitrary URL. These are controlled by the
type
parameter. A dashboard list targets a given set of tags, whereas for a link you must also provide the URL.See the documentation <https://grafana.com/docs/grafana/latest/dashboards/build-dashboards/manage-dashboard-links/#dashboard-links> for more information.
- Parameters:
asDropdown – Controls if the list appears in a dropdown rather than tiling across the dashboard. Affects ‘dashboards’ type only. Defaults to False
icon – Set the icon, from a predefined list. See
grafanalib.core.DASHBOARD_LINK_ICON
for allowed values. Affects the ‘link’ type only. Defaults to ‘external link’includeVars – Controls if data variables from the current dashboard are passed as query parameters to the linked target. Defaults to False
keepTime – Controls if the current time range is passed as query parameters to the linked target. Defaults to False
tags – A list of tags used to select dashboards for the link. Affects the ‘dashboards’ type only. Defaults to an empty list
targetBlank – Controls if the link opens in a new tab. Defaults to False
tooltip – Tooltip text that appears when hovering over the link. Affects the ‘link’ type only. Defaults to an empty string
type – Controls the type of DashboardLink generated. Must be one of ‘dashboards’ or ‘link’.
uri – The url target of the external link. Affects the ‘link’ type only.
- asDropdown: bool
- icon: Literal['bolt', 'cloud', 'dashboard', 'doc', 'external link', 'info', 'question']
- includeVars: bool
- keepTime: bool
- tags: list[str]
- targetBlank: bool
- title: str
- to_json_data()
- tooltip: str
- type: Literal['dashboards', 'link']
- uri: str
- class grafanalib.core.DashboardList(dataSource=None, targets=_Nothing.NOTHING, title='', cacheTimeout=None, description=None, editable=True, error=False, height=None, gridPos=None, hideTimeOverride=False, id=None, interval=None, links=_Nothing.NOTHING, maxDataPoints=100, minSpan=None, repeat=_Nothing.NOTHING, span=None, thresholds=_Nothing.NOTHING, thresholdType='absolute', timeFrom=None, timeShift=None, transparent=False, transformations=_Nothing.NOTHING, extraJson=None, showHeadings=True, showSearch=False, showRecent=False, showStarred=True, maxItems=10, searchQuery='', searchTags=_Nothing.NOTHING, overrides=_Nothing.NOTHING)
Bases:
Panel
Generates Dashboard list panel json structure Grafana doc on Dashboard list: https://grafana.com/docs/grafana/latest/panels/visualizations/dashboard-list-panel/
- Parameters:
showHeadings – The chosen list selection (Starred, Recently viewed, Search) is shown as a heading
showSearch – Display dashboards by search query or tags. Requires you to enter at least one value in Query or Tags
showRecent – Display recently viewed dashboards in alphabetical order
showStarred – Display starred dashboards in alphabetical order
maxItems – Sets the maximum number of items to list per section
searchQuery – Enter the query you want to search by
searchTags – List of tags you want to search by
overrides – To override the base characteristics of certain data
- to_json_data()
- class grafanalib.core.DataSourceInput(name, label, pluginId, pluginName, description='')
Bases:
object
- to_json_data()
- class grafanalib.core.DateColumnStyleType(dateFormat='YYYY-MM-DD HH:mm:ss')
Bases:
object
- TYPE = 'date'
- to_json_data()
- class grafanalib.core.Discrete(dataSource=None, targets=_Nothing.NOTHING, title='', cacheTimeout=None, description=None, editable=True, error=False, height=None, gridPos=None, hideTimeOverride=False, id=None, interval=None, links=_Nothing.NOTHING, maxDataPoints=100, minSpan=None, repeat=_Nothing.NOTHING, span=None, thresholds=_Nothing.NOTHING, thresholdType='absolute', timeFrom=None, timeShift=None, transparent=False, transformations=_Nothing.NOTHING, extraJson=None, backgroundColor=RGBA(r=128, g=128, b=128, a=0.1), lineColor=RGBA(r=0, g=0, b=0, a=0.1), metricNameColor='#000000', timeTextColor='#d8d9da', valueTextColor='#000000', decimals=0, legendPercentDecimals=0, rowHeight=50, textSize=24, textSizeTime=12, units='none', legendSortBy='-ms', highlightOnMouseover=True, showLegend=True, showLegendPercent=True, showLegendNames=True, showLegendValues=True, showTimeAxis=True, use12HourClock=False, writeMetricNames=False, writeLastValue=True, writeAllValues=False, showDistinctCount=None, showLegendCounts=None, showLegendTime=None, showTransitionCount=None, colorMaps=_Nothing.NOTHING, rangeMaps=_Nothing.NOTHING, valueMaps=_Nothing.NOTHING)
Bases:
Panel
Generates Discrete panel json structure. https://grafana.com/grafana/plugins/natel-discrete-panel/
- Parameters:
colorMaps – list of DiscreteColorMappingItem, to color values (note these apply after value mappings)
backgroundColor – dito
lineColor – Separator line color between rows
metricNameColor – dito
timeTextColor – dito
valueTextColor – dito
decimals – number of decimals to display
rowHeight – dito
units – defines value units
legendSortBy – time (desc: ‘-ms’, asc: ‘ms), count (desc: ‘-count’, asc: ‘count’)
highlightOnMouseover – whether to highlight the state of hovered time falls in.
showLegend – dito
showLegendPercent – whether to show percentage of time spent in each state/value
showLegendNames –
showLegendValues – whether to values in legend
legendPercentDecimals – number of decimals for legend
showTimeAxis – dito
use12HourClock – dito
writeMetricNames – dito
writeLastValue – dito
writeAllValues – whether to show all values
showDistinctCount – whether to show distinct values count
showLegendCounts – whether to show value occurrence count
showLegendTime – whether to show of each state
showTransitionCount – whether to show transition count
colorMaps – list of DiscreteColorMappingItem
rangeMaps – list of RangeMap
valueMaps – list of ValueMap
- to_json_data()
- class grafanalib.core.DiscreteColorMappingItem(text, color=RGBA(r=216, g=200, b=27, a=0.27))
Bases:
object
Generates json structure for the value mapping item for the StatValueMappings class:
- Parameters:
text – String to color
color – To color the text with
- to_json_data()
- class grafanalib.core.ExternalLink(uri, title, keepTime=False)
Bases:
object
ExternalLink creates a top-level link attached to a dashboard.
- Parameters:
url – the URL to link to
title – the text of the link
keepTime – if true, the URL params for the dashboard’s current time period are appended
- to_json_data()
- class grafanalib.core.Gauge(minValue=0, maxValue=100, show=False, thresholdLabels=False, thresholdMarkers=True)
Bases:
object
- to_json_data()
- class grafanalib.core.GaugePanel(dataSource=None, targets=_Nothing.NOTHING, title='', cacheTimeout=None, description=None, editable=True, error=False, height=None, gridPos=None, hideTimeOverride=False, id=None, interval=None, links=_Nothing.NOTHING, maxDataPoints=100, minSpan=None, repeat=_Nothing.NOTHING, span=None, thresholdType='absolute', timeFrom=None, timeShift=None, transparent=False, transformations=_Nothing.NOTHING, extraJson=None, allValues=False, calc='mean', dataLinks=_Nothing.NOTHING, decimals=None, format='none', label=None, limit=None, max=100, min=0, rangeMaps=_Nothing.NOTHING, thresholdLabels=False, thresholdMarkers=True, thresholds=_Nothing.NOTHING, valueMaps=_Nothing.NOTHING)
Bases:
Panel
Generates Gauge panel json structure
- Parameters:
allValue – If All values should be shown or a Calculation
calc – Calculation to perform on metrics
dataLinks – list of data links hooked to datapoints on the graph
decimals – override automatic decimal precision for legend/tooltips
format – defines value units
labels – option to show gauge level labels
limit – limit of number of values to show when not Calculating
max – maximum value of the gauge
min – minimum value of the gauge
rangeMaps – the list of value to text mappings
thresholdLabel – label for gauge. Template Variables: “$__series_namei” “$__field_name” “$__cell_{N} / $__calc”
thresholdMarkers – option to show marker of level on gauge
thresholds – single stat thresholds
valueMaps – the list of value to text mappings
- to_json_data()
- class grafanalib.core.Graph(dataSource=None, targets=_Nothing.NOTHING, title='', cacheTimeout=None, description=None, editable=True, height=None, gridPos=None, hideTimeOverride=False, id=None, interval=None, links=_Nothing.NOTHING, maxDataPoints=100, minSpan=None, repeat=_Nothing.NOTHING, span=None, thresholdType='absolute', timeFrom=None, timeShift=None, transparent=False, transformations=_Nothing.NOTHING, extraJson=None, alert=None, alertThreshold=True, aliasColors=_Nothing.NOTHING, align=False, alignLevel=0, bars=False, dataLinks=_Nothing.NOTHING, error=False, fill=1, fillGradient=0, grid=_Nothing.NOTHING, isNew=True, legend=_Nothing.NOTHING, lines=True, lineWidth=2, nullPointMode='connected', percentage=False, pointRadius=5, points=False, renderer='flot', seriesOverrides=_Nothing.NOTHING, stack=False, steppedLine=False, tooltip=_Nothing.NOTHING, thresholds=_Nothing.NOTHING, unit='', xAxis=_Nothing.NOTHING, yAxes=_Nothing.NOTHING)
Bases:
Panel
Generates Graph panel json structure.
- Parameters:
alert – List of AlertConditions
align – Select to align left and right Y-axes by value
alignLevel – Available when Align is selected. Value to use for alignment of left and right Y-axes
bars – Display values as a bar chart
dataLinks – List of data links hooked to datapoints on the graph
fill – Area fill, amount of color fill for a series. (default 1, 0 is none)
fillGradient – Degree of gradient on the area fill. (0 is no gradient, 10 is a steep gradient. Default is 0.)
lines – Display values as a line graph
points – Display points for values (default False)
pointRadius – Controls how large the points are
stack – Each series is stacked on top of another
percentage – Available when Stack is selected. Each series is drawn as a percentage of the total of all series
thresholds – List of GraphThresholds - Only valid when alert not defined
unit – Set Y Axis Unit
- auto_ref_ids()
Give unique IDs all the panels without IDs.
Returns a new
Graph
that is the same as this one, except all of the metrics have theirrefId
property set. Any panels which had anrefId
property set will keep that property, all others will have auto-generated IDs provided for them.
- to_json_data()
- class grafanalib.core.GraphThreshold(value, colorMode='critical', fill=True, line=True, op='gt', yaxis='left', fillColor=RGBA(r=245, g=54, b=54, a=0.9), lineColor=RGBA(r=245, g=54, b=54, a=0.9))
Bases:
object
Threshold for for Graph panel
- Parameters:
colorMode – Color mode of the threshold, value can be ok, warning, critical or custom. If custom is selcted a lineColor and fillColor should be provided
fill – Display threshold fill, defaults to True
line – Display threshold line, defaults to True
value – When to use this color will be null if index is 0
op – EVAL_LT for less than or EVAL_GT for greater than to indicate what the threshold applies to.
yaxis – Choose left or right for Graph panels
fillColor – Fill color of the threshold, when colorMode = “custom”
lineColor – Line color of the threshold, when colorMode = “custom”
- Example:
- thresholds = [
GraphThreshold(colorMode=”ok”, value=10.0), GraphThreshold(colorMode=”critical”, value=90.0) ]
- to_json_data()
- grafanalib.core.GreaterThan(value)
- class grafanalib.core.Grid(threshold1=None, threshold1Color=_Nothing.NOTHING, threshold2=None, threshold2Color=_Nothing.NOTHING)
Bases:
object
- to_json_data()
- class grafanalib.core.GridPos(h, w, x, y)
Bases:
object
GridPos describes the panel size and position in grid coordinates.
- Parameters:
h – height of the panel, grid height units each represents 30 pixels
w – width of the panel 1-24 (the width of the dashboard is divided into 24 columns)
x – x cordinate of the panel, in same unit as w
y – y cordinate of the panel, in same unit as h
- to_json_data()
- class grafanalib.core.Heatmap(dataSource=None, targets=_Nothing.NOTHING, title='', cacheTimeout=None, description=None, editable=True, error=False, height=None, gridPos=None, hideTimeOverride=False, id=None, interval=None, links=_Nothing.NOTHING, maxDataPoints=100, minSpan=None, repeat=_Nothing.NOTHING, span=None, thresholds=_Nothing.NOTHING, thresholdType='absolute', timeFrom=None, timeShift=None, transparent=False, transformations=_Nothing.NOTHING, extraJson=None, legend={'show': False}, tooltip=_Nothing.NOTHING, cards={'cardPadding': None, 'cardRound': None}, color=_Nothing.NOTHING, dataFormat='timeseries', hideZeroBuckets=False, highlightCards=True, options=_Nothing.NOTHING, xAxis=_Nothing.NOTHING, xBucketNumber=None, xBucketSize=None, yAxis=_Nothing.NOTHING, yBucketBound=None, yBucketNumber=None, yBucketSize=None, reverseYBuckets=False)
Bases:
Panel
Generates Heatmap panel json structure (https://grafana.com/docs/grafana/latest/features/panels/heatmap/)
- Parameters:
heatmap – dict
cards – A heatmap card object: keys “cardPadding”, “cardRound”
color – Heatmap color object
dataFormat – ‘timeseries’ or ‘tsbuckets’
yBucketBound – ‘auto’, ‘upper’, ‘middle’, ‘lower’
reverseYBuckets – boolean
xBucketSize – Size
xBucketNumber – Number
yBucketSize – Size
yBucketNumber – Number
highlightCards – boolean
hideZeroBuckets – boolean
transparent – defines if the panel should be transparent
- heatmap = {}
- to_json_data()
- class grafanalib.core.HeatmapColor(cardColor='#b4ff00', colorScale='sqrt', colorScheme='interpolateOranges', exponent=0.5, mode='spectrum', max=None, min=None)
Bases:
object
A Color object for heatmaps
- Parameters:
cardColor – color
colorScale – scale
colorScheme – scheme
exponent – exponent
max – max
min – min
mode – mode
- to_json_data()
- class grafanalib.core.Histogram(dataSource=None, targets=_Nothing.NOTHING, title='', cacheTimeout=None, description=None, editable=True, error=False, height=None, gridPos=None, hideTimeOverride=False, id=None, interval=None, links=_Nothing.NOTHING, maxDataPoints=100, minSpan=None, repeat=_Nothing.NOTHING, span=None, thresholds=_Nothing.NOTHING, thresholdType='absolute', timeFrom=None, timeShift=None, transparent=False, transformations=_Nothing.NOTHING, extraJson=None, bucketOffset=0, bucketSize=0, colorMode='thresholds', combine=False, fillOpacity=80, legendDisplayMode='list', legendPlacement='bottom', lineWidth=0, mappings=_Nothing.NOTHING, overrides=_Nothing.NOTHING)
Bases:
Panel
Generates Histogram panel json structure Grafana docs on Histogram panel: https://grafana.com/docs/grafana/latest/visualizations/histogram/#
- Parameters:
bucketOffset – Bucket offset for none-zero-based buckets
bucketSize – Bucket size, default Auto
colorMode – Default thresholds
combine – Combine all series into a single histogram
fillOpacity – Controls the opacity of state regions, default 0.9
legendDisplayMode – refine how the legend appears, list, table or hidden
legendPlacement – bottom or top
lineWidth – Controls line width of state regions
mappings – To assign colors to boolean or string values, use Value mappings
overrides – To override the base characteristics of certain data
- to_json_data()
- class grafanalib.core.Legend(avg=False, current=False, max=False, min=False, show=True, total=False, values=None, alignAsTable=False, hideEmpty=False, hideZero=False, rightSide=False, sideWidth=None, sort=None, sortDesc=False)
Bases:
object
- to_json_data()
- class grafanalib.core.Logs(dataSource=None, targets=_Nothing.NOTHING, title='', cacheTimeout=None, description=None, editable=True, error=False, height=None, gridPos=None, hideTimeOverride=False, id=None, interval=None, links=_Nothing.NOTHING, maxDataPoints=100, minSpan=None, repeat=_Nothing.NOTHING, span=None, thresholds=_Nothing.NOTHING, thresholdType='absolute', timeFrom=None, timeShift=None, transparent=False, transformations=_Nothing.NOTHING, extraJson=None, showLabels=False, showCommonLabels=False, showTime=False, wrapLogMessages=False, sortOrder='Descending', dedupStrategy='none', enableLogDetails=False, overrides=_Nothing.NOTHING, prettifyLogMessage=False)
Bases:
Panel
Generates Logs panel json structure Grafana doc on Logs panel: https://grafana.com/docs/grafana/latest/panels/visualizations/logs-panel/
- Parameters:
showLabels – Show or hide the unique labels column, which shows only non-common labels
showCommonLabels – Show or hide the common labels.
showTime – Show or hide the log timestamp column
wrapLogMessages – Toggle line wrapping
sortOrder – Display results in ‘Descending’ or ‘Ascending’ time order. The default is Descending, showing the newest logs first.
dedupStrategy – One of none, exact, numbers, signature. Default is none
enableLogDetails – Set this to True to see the log details view for each log row.
overrides – To override the base characteristics of certain data
prettifyLogMessage – Set this to true to pretty print all JSON logs. This setting does not affect logs in any format other than JSON.
- to_json_data()
- grafanalib.core.LowerThan(value)
- class grafanalib.core.News(dataSource=None, targets=_Nothing.NOTHING, title='', cacheTimeout=None, description=None, editable=True, error=False, height=None, gridPos=None, hideTimeOverride=False, id=None, interval=None, links=_Nothing.NOTHING, maxDataPoints=100, minSpan=None, repeat=_Nothing.NOTHING, span=None, thresholds=_Nothing.NOTHING, thresholdType='absolute', timeFrom=None, timeShift=None, transparent=False, transformations=_Nothing.NOTHING, extraJson=None, feedUrl='', showImage=True, useProxy=False)
Bases:
Panel
Generates News panel json structure
- Parameters:
feedUrl – URL to query, only RSS feed formats are supported (not Atom).
showImage – Controls if the news item social (og:image) image is shown above text content
useProxy – If the feed is unable to connect, consider a CORS proxy
- to_json_data()
- grafanalib.core.NoValue()
- class grafanalib.core.NumberColumnStyleType(colorMode=None, colors=_Nothing.NOTHING, thresholds=_Nothing.NOTHING, decimals=2, unit='short')
Bases:
object
- TYPE = 'number'
- to_json_data()
- grafanalib.core.OutsideRange(from_value, to_value)
- class grafanalib.core.Panel(dataSource=None, targets=_Nothing.NOTHING, title='', cacheTimeout=None, description=None, editable=True, error=False, height=None, gridPos=None, hideTimeOverride=False, id=None, interval=None, links=_Nothing.NOTHING, maxDataPoints=100, minSpan=None, repeat=_Nothing.NOTHING, span=None, thresholds=_Nothing.NOTHING, thresholdType='absolute', timeFrom=None, timeShift=None, transparent=False, transformations=_Nothing.NOTHING, extraJson=None)
Bases:
object
Generic panel for shared defaults
- Parameters:
cacheTimeout – metric query result cache ttl
dataSource – Grafana datasource name
description – optional panel description
editable – defines if panel is editable via web interfaces
height – defines panel height
hideTimeOverride – hides time overrides
id – panel id
interval – defines time interval between metric queries
links – additional web links
maxDataPoints – maximum metric query results, that will be used for rendering
minSpan – minimum span number
repeat – Template’s name to repeat Graph on
span – defines the number of spans that will be used for panel
targets – list of metric requests for chosen datasource
thresholds – single stat thresholds
thresholdType – type of threshold, absolute or percentage
timeFrom – time range that Override relative time
title – of the panel
transparent – defines if panel should be transparent
transformations – defines transformations applied to the table
extraJson – raw JSON additions or overrides added to the JSON output of this panel, can be used for using unsupported features
- panel_json(overrides)
- class grafanalib.core.PieChart(dataSource=None, targets=_Nothing.NOTHING, title='', cacheTimeout=None, description=None, editable=True, error=False, height=None, gridPos=None, hideTimeOverride=False, id=None, interval=None, links=_Nothing.NOTHING, maxDataPoints=100, minSpan=None, repeat=_Nothing.NOTHING, span=None, thresholdType='absolute', timeFrom=None, timeShift=None, transparent=False, transformations=_Nothing.NOTHING, extraJson=None, aliasColors=_Nothing.NOTHING, format='none', legendType='Right side', overrides=_Nothing.NOTHING, pieType='pie', percentageDecimals=0, showLegend=True, showLegendValues=True, showLegendPercentage=False, thresholds='')
Bases:
Panel
Generates Pie Chart panel json structure
This panel was deprecated in Grafana 8.0, please use PieChartv2 instead
Grafana doc on Pie Chart: https://grafana.com/grafana/plugins/grafana-piechart-panel
- Parameters:
aliasColors – dictionary of color overrides
format – defines value units
legendType – defines where the legend position
overrides – To override the base characteristics of certain data
pieType – defines the shape of the pie chart (pie or donut)
percentageDecimals – Number of decimal places to show if percentages shown in legned
showLegend – defines if the legend should be shown
showLegendValues – defines if the legend should show values
showLegendPercentage – Show percentages in the legend
thresholds – defines thresholds
- to_json_data()
- class grafanalib.core.PieChartv2(dataSource=None, targets=_Nothing.NOTHING, title='', cacheTimeout=None, description=None, editable=True, error=False, height=None, gridPos=None, hideTimeOverride=False, id=None, interval=None, links=_Nothing.NOTHING, maxDataPoints=100, minSpan=None, repeat=_Nothing.NOTHING, span=None, thresholds=_Nothing.NOTHING, thresholdType='absolute', timeFrom=None, timeShift=None, transparent=False, transformations=_Nothing.NOTHING, extraJson=None, custom=_Nothing.NOTHING, colorMode='palette-classic', legendDisplayMode='list', legendPlacement='bottom', legendValues=_Nothing.NOTHING, mappings=_Nothing.NOTHING, overrides=_Nothing.NOTHING, pieType='pie', reduceOptionsCalcs=['lastNotNull'], reduceOptionsFields='', reduceOptionsValues=False, tooltipMode='single', unit='')
Bases:
Panel
Generates Pie Chart panel json structure Grafana docs on Pie Chart: https://grafana.com/docs/grafana/latest/visualizations/pie-chart-panel/
- Parameters:
custom – Custom overides
colorMode – Color mode palette-classic (Default),
legendDisplayMode – Display mode of legend: list, table or hidden
legendPlacement – Location of the legend in the panel: bottom or right
legendValues – List of value to be shown in legend eg. [‘value’, ‘percent’]
mappings – To assign colors to boolean or string values, use Value mappings
overrides – Overrides
pieType – Pie chart type pie (Default), donut
reduceOptionsCalcs – Reducer function / calculation
reduceOptionsFields – Fields that should be included in the panel
reduceOptionsValues – Calculate a single value per column or series or show each row
tooltipMode – Tooltip mode single (Default), multi, none
unit – units
- to_json_data()
- class grafanalib.core.Repeat(direction=None, variable=None, maxPerRow=None)
Bases:
object
Panel repetition settings.
- Parameters:
direction – The direction into which to repeat (‘h’ or ‘v’)
variable – The name of the variable over whose values to repeat
maxPerRow – The maximum number of panels per row in horizontal repetition
- to_json_data()
- class grafanalib.core.Row(panels=_Nothing.NOTHING, collapse=False, editable=True, height=_Nothing.NOTHING, showTitle=None, title=None, repeat=None)
Bases:
object
Legacy support for old row, when not used with gridpos
- to_json_data()
- class grafanalib.core.RowPanel(dataSource=None, targets=_Nothing.NOTHING, title='', cacheTimeout=None, description=None, editable=True, error=False, height=None, gridPos=None, hideTimeOverride=False, id=None, interval=None, links=_Nothing.NOTHING, maxDataPoints=100, minSpan=None, repeat=_Nothing.NOTHING, span=None, thresholds=_Nothing.NOTHING, thresholdType='absolute', timeFrom=None, timeShift=None, transparent=False, transformations=_Nothing.NOTHING, extraJson=None, panels=_Nothing.NOTHING, collapsed=False)
Bases:
Panel
Generates Row panel json structure.
- Parameters:
title – title of the panel
collapsed – set True if row should be collapsed
panels – list of panels in the row, only to be used when collapsed=True
- to_json_data()
- class grafanalib.core.SeriesOverride(alias, bars=False, lines=True, yaxis=1, fill=1, zindex=0, dashes=False, dashLength=None, spaceLength=None, color=None, fillBelowTo=None)
Bases:
object
To override properties of e.g. Graphs.
- Parameters:
alias – Name of the metric to apply to
bars – Whether to show data point bars
lines – Whether to keep graph lines
yaxis – Whether to move axis of the metric to the right (=2) or not (=1)
fill – Fill strength (0…10)
color – Whether to change color to
fillBelowTo – Alias of the other metric to fill below
zindex – Move things to front or background (-3…3)
dashed – Whether to dash the line
dashLength – Length of dashes (1..20)
spaceLength – Length of spaces betwee dashed
zindex – Move things to front or background
- to_json_data()
- class grafanalib.core.SingleStat(dataSource=None, targets=_Nothing.NOTHING, title='', description=None, editable=True, error=False, height=None, gridPos=None, hideTimeOverride=False, id=None, interval=None, links=_Nothing.NOTHING, maxDataPoints=100, repeat=_Nothing.NOTHING, span=None, thresholdType='absolute', timeFrom=None, timeShift=None, transparent=False, transformations=_Nothing.NOTHING, extraJson=None, cacheTimeout=None, colors=_Nothing.NOTHING, colorBackground=False, colorValue=False, decimals=None, format='none', gauge=_Nothing.NOTHING, mappingType=1, mappingTypes=_Nothing.NOTHING, minSpan=None, nullText=None, nullPointMode='connected', postfix='', postfixFontSize='50%', prefix='', prefixFontSize='50%', rangeMaps=_Nothing.NOTHING, sparkline=_Nothing.NOTHING, thresholds='', valueFontSize='80%', valueName='avg', valueMaps=_Nothing.NOTHING)
Bases:
Panel
Generates Single Stat panel json structure
This panel was deprecated in Grafana 7.0, please use Stat instead
Grafana doc on singlestat: https://grafana.com/docs/grafana/latest/features/panels/singlestat/
- Parameters:
cacheTimeout – metric query result cache ttl
colors – the list of colors that can be used for coloring panel value or background. Additional info on coloring in docs: https://grafana.com/docs/grafana/latest/features/panels/singlestat/#coloring
colorBackground – defines if grafana will color panel background
colorValue – defines if grafana will color panel value
decimals – override automatic decimal precision for legend/tooltips
format – defines value units
gauge – draws and additional speedometer-like gauge based
mappingType – defines panel mapping type. Additional info can be found in docs: https://grafana.com/docs/grafana/latest/features/panels/singlestat/#value-to-text-mapping
mappingTypes – the list of available mapping types for panel
nullText – defines what to show if metric query result is undefined
nullPointMode – defines how to render undefined values
postfix – defines postfix that will be attached to value
postfixFontSize – defines postfix font size
prefix – defines prefix that will be attached to value
prefixFontSize – defines prefix font size
rangeMaps – the list of value to text mappings
sparkline – defines if grafana should draw an additional sparkline. Sparkline grafana documentation: https://grafana.com/docs/grafana/latest/features/panels/singlestat/#spark-lines
thresholds – single stat thresholds
valueFontSize – defines value font size
valueName – defines value type. possible values are: min, max, avg, current, total, name, first, delta, range
valueMaps – the list of value to text mappings
- to_json_data()
- class grafanalib.core.SparkLine(fillColor=_Nothing.NOTHING, full=False, lineColor=_Nothing.NOTHING, show=False)
Bases:
object
- to_json_data()
- class grafanalib.core.SqlTarget(expr='', format='time_series', hide=False, legendFormat='', interval='', intervalFactor=2, metric='', refId='', step=10, target='', instant=False, datasource=None, rawSql='', rawQuery=True, srcFilePath='', sqlParams=_Nothing.NOTHING)
Bases:
Target
Metric target to support SQL queries
- to_json_data()
Override the Target to_json_data to add additional fields. rawSql: this will contain the actual SQL queries rawQuery: this is set to True by default as in case of False
the rawSql would be unused
- class grafanalib.core.Stat(dataSource=None, targets=_Nothing.NOTHING, title='', cacheTimeout=None, description=None, editable=True, error=False, height=None, gridPos=None, hideTimeOverride=False, id=None, interval=None, links=_Nothing.NOTHING, maxDataPoints=100, minSpan=None, repeat=_Nothing.NOTHING, span=None, thresholdType='absolute', timeFrom=None, timeShift=None, transparent=False, transformations=_Nothing.NOTHING, extraJson=None, alignment='auto', color=None, colorMode='value', decimals=None, format='none', graphMode='area', mappings=_Nothing.NOTHING, noValue='none', orientation='auto', overrides=_Nothing.NOTHING, reduceCalc: str = 'mean', fields='', textMode='auto', thresholds='')
Bases:
Panel
Generates Stat panel json structure
Grafana doc on stat: https://grafana.com/docs/grafana/latest/panels/visualizations/stat-panel/
- Parameters:
alignment – defines value & title positioning: keys ‘auto’ ‘centre’
colorMode – defines if Grafana will color panel background: keys “value” “background”
decimals – number of decimals to display
format – defines value units
graphMode – defines if Grafana will draw graph: keys ‘area’ ‘none’
noValue – define the default value if no value is found
mappings – the list of values to text mappings This should be a list of StatMapping objects https://grafana.com/docs/grafana/latest/panels/field-configuration-options/#value-mapping
orientation – Stacking direction in case of multiple series or fields: keys ‘auto’ ‘horizontal’ ‘vertical’
overrides – To override the base characteristics of certain timeseries data
reduceCalc – algorithm for reduction to a single value: keys ‘mean’ ‘lastNotNull’ ‘last’ ‘first’ ‘firstNotNull’ ‘min’ ‘max’ ‘sum’ ‘total’
fields – should be included in the panel
textMode – define Grafana will show name or value: keys: ‘auto’ ‘name’ ‘none’ ‘value’ ‘value_and_name’
thresholds – single stat thresholds
- to_json_data()
- class grafanalib.core.StatMapping(text, mapValue='', startValue='', endValue='', id=None)
Bases:
object
Deprecated Grafana v8 Generates json structure for the value mapping for the Stat panel:
- Parameters:
text – Sting that will replace input value
value – Value to be replaced
startValue – When using a range, the start value of the range
endValue – When using a range, the end value of the range
id – panel id
- to_json_data()
- class grafanalib.core.StatRangeMapping(text, startValue='', endValue='', id=None)
Bases:
object
Deprecated Grafana v8 Generates json structure for the range mappings for the StatPanel:
- Parameters:
text – Sting that will replace input value
startValue – When using a range, the start value of the range
endValue – When using a range, the end value of the range
id – panel id
- to_json_data()
- class grafanalib.core.StatRangeMappings(text, startValue=0, endValue=0, color='', index=None)
Bases:
object
Generates json structure for the range mappings for the StatPanel:
- Parameters:
text – Sting that will replace input value
startValue – When using a range, the start value of the range
endValue – When using a range, the end value of the range
color – How to color the text if mapping occurs
index – index
- to_json_data()
- class grafanalib.core.StatValueMapping(text, mapValue='', id=None)
Bases:
object
Deprecated Grafana v8 Generates json structure for the value mappings for the StatPanel:
- Parameters:
text – Sting that will replace input value
mapValue – Value to be replaced
id – panel id
- to_json_data()
- class grafanalib.core.StatValueMappingItem(text, mapValue='', color='', index=None)
Bases:
object
Generates json structure for the value mapping item for the StatValueMappings class:
- Parameters:
text – String that will replace input value
mapValue – Value to be replaced
color – How to color the text if mapping occurs
index – index
- to_json_data()
- class grafanalib.core.StatValueMappings(*mappings: StatValueMappingItem)
Bases:
object
Generates json structure for the value mappings for the StatPanel:
- Parameters:
mappingItems – List of StatValueMappingItem objects
- mappings=[
- core.StatValueMappings(
core.StatValueMappingItem(‘Offline’, ‘0’, ‘red’), # Value must a string core.StatValueMappingItem(‘Online’, ‘1’, ‘green’)
),
],
- to_json_data()
- class grafanalib.core.StateTimeline(dataSource=None, targets=_Nothing.NOTHING, title='', cacheTimeout=None, description=None, editable=True, error=False, height=None, gridPos=None, hideTimeOverride=False, id=None, interval=None, links=_Nothing.NOTHING, maxDataPoints=100, minSpan=None, repeat=_Nothing.NOTHING, span=None, thresholds=_Nothing.NOTHING, thresholdType='absolute', timeFrom=None, timeShift=None, transparent=False, transformations=_Nothing.NOTHING, extraJson=None, alignValue='left', colorMode='thresholds', fillOpacity=70, legendDisplayMode='list', legendPlacement='bottom', lineWidth=0, mappings=_Nothing.NOTHING, overrides=_Nothing.NOTHING, mergeValues=True, rowHeight=0.9, showValue='auto', tooltipMode='single')
Bases:
Panel
Generates State Timeline panel json structure Grafana docs on State Timeline panel: https://grafana.com/docs/grafana/latest/visualizations/state-timeline/
- Parameters:
alignValue – Controls value alignment inside state regions, default left
colorMode – Default thresholds
fillOpacity – Controls the opacity of state regions, default 0.9
legendDisplayMode – refine how the legend appears, list, table or hidden
legendPlacement – bottom or top
lineWidth – Controls line width of state regions
mappings – To assign colors to boolean or string values, use Value mappings
overrides – To override the base characteristics of certain data
mergeValues – Controls whether Grafana merges identical values if they are next to each other, default True
rowHeight – Controls how much space between rows there are. 1 = no space = 0.5 = 50% space
showValue – Controls whether values are rendered inside the state regions. Auto will render values if there is sufficient space.
tooltipMode – Default single
- to_json_data()
- class grafanalib.core.Statusmap(dataSource=None, targets=_Nothing.NOTHING, title='', cacheTimeout=None, description=None, editable=True, error=False, height=None, gridPos=None, hideTimeOverride=False, id=None, interval=None, links=_Nothing.NOTHING, maxDataPoints=100, minSpan=None, repeat=_Nothing.NOTHING, span=None, thresholds=_Nothing.NOTHING, thresholdType='absolute', timeFrom=None, timeShift=None, transparent=False, transformations=_Nothing.NOTHING, extraJson=None, alert=None, cards={'cardHSpacing': 2, 'cardMinWidth': 5, 'cardRound': None, 'cardVSpacing': 2}, color=_Nothing.NOTHING, isNew=True, legend=_Nothing.NOTHING, nullPointMode='null as zero', tooltip=_Nothing.NOTHING, xAxis=_Nothing.NOTHING, yAxis=_Nothing.NOTHING)
Bases:
Panel
Generates json structure for the flant-statusmap-panel visualisation plugin (https://grafana.com/grafana/plugins/flant-statusmap-panel/).
- Parameters:
alert – Alert
cards – A statusmap card object: keys ‘cardRound’, ‘cardMinWidth’, ‘cardHSpacing’, ‘cardVSpacing’
color – A StatusmapColor object
isNew – isNew
legend – Legend object
nullPointMode – null
tooltip – Tooltip object
xAxis – XAxis object
yAxis – YAxis object
- to_json_data()
- class grafanalib.core.StatusmapColor(cardColor='#b4ff00', colorScale='sqrt', colorScheme='GnYlRd', exponent=0.5, mode='spectrum', thresholds=_Nothing.NOTHING, max=None, min=None)
Bases:
object
A Color object for Statusmaps
- Parameters:
cardColor – colour
colorScale – scale
colorScheme – scheme
exponent – exponent
max – max
min – min
mode – mode
thresholds – threshold
- to_json_data()
- class grafanalib.core.StringColumnStyleType(decimals=2, colorMode=None, colors=_Nothing.NOTHING, thresholds=_Nothing.NOTHING, preserveFormat=False, sanitize=False, unit='short', mappingType=1, valueMaps=_Nothing.NOTHING, rangeMaps=_Nothing.NOTHING)
Bases:
object
- TYPE = 'string'
- to_json_data()
- class grafanalib.core.Svg(dataSource=None, targets=_Nothing.NOTHING, title='', cacheTimeout=None, description=None, editable=True, error=False, gridPos=None, hideTimeOverride=False, id=None, interval=None, links=_Nothing.NOTHING, maxDataPoints=100, minSpan=None, repeat=_Nothing.NOTHING, span=None, thresholds=_Nothing.NOTHING, thresholdType='absolute', timeFrom=None, timeShift=None, transparent=False, transformations=_Nothing.NOTHING, extraJson=None, format='none', jsCodeFilePath='', jsCodeInitFilePath='', height=None, svgFilePath='')
Bases:
Panel
Generates SVG panel json structure Grafana doc on SVG: https://grafana.com/grafana/plugins/marcuscalidus-svg-panel
- Parameters:
format – defines value units
jsCodeFilePath – path to javascript file to be run on dashboard refresh
jsCodeInitFilePath – path to javascript file to be run after the first initialization of the SVG
reduceCalc – algorithm for reduction to a single value, keys ‘mean’ ‘lastNotNull’ ‘last’ ‘first’ ‘firstNotNull’ ‘min’ ‘max’ ‘sum’ ‘total’
svgFilePath – path to SVG image file to be displayed
- static read_file(file_path)
- to_json_data()
- class grafanalib.core.Table(dataSource=None, targets=_Nothing.NOTHING, title='', cacheTimeout=None, description=None, editable=True, error=False, height=None, gridPos=None, hideTimeOverride=False, id=None, interval=None, links=_Nothing.NOTHING, maxDataPoints=100, minSpan=None, repeat=_Nothing.NOTHING, span=None, thresholds=_Nothing.NOTHING, thresholdType='absolute', timeFrom=None, timeShift=None, transparent=False, transformations=_Nothing.NOTHING, extraJson=None, align='auto', colorMode='thresholds', columns=_Nothing.NOTHING, displayMode='auto', fontSize='100%', filterable=False, mappings=_Nothing.NOTHING, overrides=_Nothing.NOTHING, showHeader=True, unit='', sortBy=_Nothing.NOTHING)
Bases:
Panel
Generates Table panel json structure
Now supports Grafana v8+ Grafana doc on table: https://grafana.com/docs/grafana/latest/visualizations/table/
- Parameters:
align – Align cell contents; auto (default), left, center, right
colorMode – Default thresholds
columns – Table columns for Aggregations view
displayMode – By default, Grafana automatically chooses display settings, you can choose; color-text, color-background, color-background-solid, gradient-gauge, lcd-gauge, basic, json-view
fontSize – Defines value font size
filterable – Allow user to filter columns, default False
mappings – To assign colors to boolean or string values, use Value mappings
overrides – To override the base characteristics of certain data
showHeader – Show the table header
unit – units
sortBy – Sort rows by table fields
- span = (_CountingAttr(counter=529, _default=6, repr=True, eq=True, order=True, hash=None, init=True, on_setattr=None, alias=None, metadata={}),)
- to_json_data()
- classmethod with_styled_columns(columns, styles=None, **kwargs)
Styled columns is not support in Grafana v8 Table
- class grafanalib.core.Target(expr='', format='time_series', hide=False, legendFormat='', interval='', intervalFactor=2, metric='', refId='', step=10, target='', instant=False, datasource=None)
Bases:
object
Metric to show.
- Parameters:
target – Graphite way to select data
- to_json_data()
- class grafanalib.core.Template(name, query, default=None, dataSource=None, label=None, allValue=None, includeAll=False, multi=False, options=_Nothing.NOTHING, regex=None, useTags=False, tagsQuery=None, tagValuesQuery=None, refresh=1, type='query', hide=0, sort=1, auto=False, autoCount=30, autoMin='10s')
Bases:
object
Template create a new ‘variable’ for the dashboard, defines the variable name, human name, query to fetch the values and the default value.
- Parameters:
default – the default value for the variable
dataSource – where to fetch the values for the variable from
label – the variable’s human label
name – the variable’s name
query – the query users to fetch the valid values of the variable
refresh – Controls when to update values in the dropdown
allValue – specify a custom all value with regex, globs or lucene syntax.
includeAll – Add a special All option whose value includes all options.
regex – Regex to filter or capture specific parts of the names return by your data source query.
multi – If enabled, the variable will support the selection of multiple options at the same time.
type – The template type, can be one of: query (default), interval, datasource, custom, constant, adhoc.
hide – Hide this variable in the dashboard, can be one of: SHOW (default), HIDE_LABEL, HIDE_VARIABLE
auto – Interval will be dynamically calculated by dividing time range by the count specified in auto_count.
autoCount – Number of intervals for dividing the time range.
autoMin – Smallest interval for auto interval generator.
- to_json_data()
- class grafanalib.core.Text(dataSource=None, targets=_Nothing.NOTHING, title='', cacheTimeout=None, description=None, editable=True, height=None, gridPos=None, hideTimeOverride=False, id=None, interval=None, links=_Nothing.NOTHING, maxDataPoints=100, minSpan=None, repeat=_Nothing.NOTHING, span=None, thresholds=_Nothing.NOTHING, thresholdType='absolute', timeFrom=None, timeShift=None, transparent=False, transformations=_Nothing.NOTHING, extraJson=None, content='', error=False, mode='markdown')
Bases:
Panel
Generates a Text panel.
- to_json_data()
- class grafanalib.core.Threshold(color, index, value, line=True, op='gt', yaxis='left')
Bases:
object
Threshold for for panels
- Parameters:
color – Color of threshold
index – Index of color in panel
line – Display Threshold line, defaults to True
value – When to use this color will be null if index is 0
op – EVAL_LT for less than or EVAL_GT for greater than to indicate what the threshold applies to.
yaxis – Choose left or right for panels
Care must be taken in the order in which the Threshold objects are specified, Grafana expects the value to increase.
- Example::
- thresholds = [
Threshold(‘green’, 0, 0.0), Threshold(‘red’, 1, 80.0)]
- to_json_data()
- class grafanalib.core.TimePicker(refreshIntervals, timeOptions, nowDelay=None, hidden=False)
Bases:
object
Time Picker
- Parameters:
refreshIntervals – dashboard auto-refresh interval options
timeOptions – dashboard time range options
nowDelay – exclude recent data that may be incomplete, as a number + unit (s: second, m: minute, h: hour, etc)
hidden – hide the time picker from dashboard
- to_json_data()
- class grafanalib.core.TimeRange(from_time, to_time)
Bases:
object
A time range for an alert condition.
A condition has to hold for this length of time before triggering.
- Parameters:
from_time (str) – Either a number + unit (s: second, m: minute, h: hour, etc) e.g.
"5m"
for 5 minutes, or"now"
.to_time (str) – Either a number + unit (s: second, m: minute, h: hour, etc) e.g.
"5m"
for 5 minutes, or"now"
.
- to_json_data()
- class grafanalib.core.TimeSeries(dataSource=None, targets=_Nothing.NOTHING, title='', cacheTimeout=None, description=None, editable=True, error=False, height=None, gridPos=None, hideTimeOverride=False, id=None, interval=None, links=_Nothing.NOTHING, maxDataPoints=100, minSpan=None, repeat=_Nothing.NOTHING, span=None, thresholds=_Nothing.NOTHING, thresholdType='absolute', timeFrom=None, timeShift=None, transparent=False, transformations=_Nothing.NOTHING, extraJson=None, axisPlacement='auto', axisLabel='', barAlignment=0, colorMode='palette-classic', drawStyle='line', fillOpacity=0, gradientMode='none', legendDisplayMode='list', legendPlacement='bottom', legendCalcs=_Nothing.NOTHING, lineInterpolation='linear', lineWidth=1, mappings=_Nothing.NOTHING, overrides=_Nothing.NOTHING, pointSize=5, scaleDistributionType='linear', scaleDistributionLog=2, spanNulls=False, showPoints='auto', stacking=_Nothing.NOTHING, tooltipMode='single', tooltipSort='none', unit='', thresholdsStyleMode='off', valueMin=None, valueMax=None, valueDecimals=None, axisSoftMin=None, axisSoftMax=None)
Bases:
Panel
Generates Time Series panel json structure added in Grafana v8
Grafana doc on time series: https://grafana.com/docs/grafana/latest/panels/visualizations/time-series/
- Parameters:
axisPlacement – auto(Default), left. right, hidden
axisLabel – axis label string
barAlignment – bar alignment -1 (left), 0 (centre, default), 1
colorMode – Color mode palette-classic (Default),
drawStyle – how to display your time series data line (Default), bars, points
fillOpacity – fillOpacity
gradientMode – gradientMode
legendDisplayMode – refine how the legend appears in your visualization list (Default), table, hidden
legendPlacement – bottom (Default), right
legendCalcs – which calculations should be displayed in the legend. Defaults to an empty list. Possible values are: allIsNull, allIsZero, changeCount, count, delta, diff, diffperc, distinctCount, firstNotNull, max, mean, min, logmin, range, step, total. For more information see
lineInterpolation – line interpolation linear (Default), smooth, stepBefore, stepAfter
lineWidth – line width, default 1
mappings – To assign colors to boolean or string values, use Value mappings
overrides – To override the base characteristics of certain timeseries data
pointSize – point size, default 5
scaleDistributionType – axis scale linear or log
scaleDistributionLog – Base of if logarithmic scale type set, default 2
spanNulls – connect null values, default False
showPoints – show points auto (Default), always, never
stacking – dict to enable stacking, {“mode”: “normal”, “group”: “A”}
thresholds – single stat thresholds
tooltipMode – When you hover your cursor over the visualization, Grafana can display tooltips single (Default), multi, none
tooltipSort – To sort the tooltips none (Default), asc, desc
unit – units
thresholdsStyleMode – thresholds style mode off (Default), area, line, line+area
valueMin – Minimum value for Panel
valueMax – Maximum value for Panel
valueDecimals – Number of display decimals
axisSoftMin – soft minimum Y axis value
axisSoftMax – soft maximum Y axis value
- to_json_data()
- class grafanalib.core.Tooltip(msResolution=True, shared=True, sort=0, valueType='cumulative')
Bases:
object
- to_json_data()
- class grafanalib.core.ValueMap(text, value, op='=')
Bases:
object
Generates json structure for a value mapping item.
- Parameters:
op – comparison operator
value – value to map to text
text – text to map the value to
- to_json_data()
- grafanalib.core.WithinRange(from_value, to_value)
- class grafanalib.core.Worldmap(dataSource=None, targets=_Nothing.NOTHING, title='', cacheTimeout=None, description=None, editable=True, error=False, height=None, gridPos=None, hideTimeOverride=False, id=None, interval=None, links=_Nothing.NOTHING, maxDataPoints=100, minSpan=None, repeat=_Nothing.NOTHING, span=None, thresholdType='absolute', timeFrom=None, timeShift=None, transparent=False, transformations=_Nothing.NOTHING, extraJson=None, circleMaxSize=30, circleMinSize=2, decimals=0, geoPoint='geohash', locationData='countries', locationName='', hideEmpty=False, hideZero=False, initialZoom=1, jsonUrl='', jsonpCallback='', mapCenter='(0°, 0°)', mapCenterLatitude=0, mapCenterLongitude=0, metric='Value', mouseWheelZoom=False, stickyLabels=False, thresholds='0,100,150', thresholdColors=['#73BF69', '#73BF69', '#FADE2A', '#C4162A'], unitPlural='', unitSingle='', unitSingular='', aggregation='total')
Bases:
Panel
Generates Worldmap panel json structure Grafana doc on Worldmap: https://grafana.com/grafana/plugins/grafana-worldmap-panel/
- Parameters:
aggregation – metric aggregation: min, max, avg, current, total
circleMaxSize – Maximum map circle size
circleMinSize – Minimum map circle size
decimals – Number of decimals to show
geoPoint – Name of the geo_point/geohash column. This is used to calculate where the circle should be drawn.
locationData – Format of the location data, options in WORLDMAP_LOCATION_DATA
locationName – Name of the Location Name column. Used to label each circle on the map. If it is empty then the geohash value is used.
metric – Name of the metric column. This is used to give the circle a value - this determines how large the circle is.
mapCenter – Where to centre the map, default center (0°, 0°). Options: North America, Europe, West Asia, SE Asia, Last GeoHash, custom
mapCenterLatitude – If mapCenter=custom set the initial map latitude
mapCenterLongitude – If mapCenter=custom set the initial map longitude
hideEmpty – Hide series with only nulls
hideZero – Hide series with only zeros
initialZoom – Initial map zoom
jsonUrl – URL for JSON location data if json_endpoint or jsonp endpoint used
jsonpCallback – Callback if jsonp endpoint used
mouseWheelZoom – Zoom map on scroll of mouse wheel
stickyLabels – Sticky map labels
thresholds – String of thresholds eg. ‘0,10,20’
thresholdsColors – List of colors to be used in each threshold
unitPlural – Units plural
unitSingle – Units single
unitSingular – Units singular
- to_json_data()
- class grafanalib.core.XAxis(mode='time', name=None, values=_Nothing.NOTHING, show=True)
Bases:
object
X Axis
- Parameters:
mode – Mode of axis can be time, series or histogram
name – X axis name
value – list of values eg. [“current”] or [“avg”]
show – show X axis
- to_json_data()
- class grafanalib.core.YAxes(left=_Nothing.NOTHING, right=_Nothing.NOTHING)
Bases:
object
The pair of Y axes on a Grafana graph.
Each graph has two Y Axes, a left one and a right one.
- to_json_data()
- class grafanalib.core.YAxis(decimals=None, format=None, label=None, logBase=1, max=None, min=None, show=True)
Bases:
object
A single Y axis.
Grafana graphs have two Y axes: one on the left and one on the right.
- Parameters:
decimals – Defines how many decimals are displayed for Y value. (default auto)
format – The display unit for the Y value
label – The Y axis label. (default “”)
logBase – The scale to use for the Y value, linear, or logarithmic. (default linear)
max – The maximum Y value
min – The minimum Y value
show – Show or hide the axis
- to_json_data()
- class grafanalib.core.ePict(dataSource=None, targets=_Nothing.NOTHING, title='', cacheTimeout=None, description=None, editable=True, error=False, height=None, gridPos=None, hideTimeOverride=False, id=None, interval=None, links=_Nothing.NOTHING, maxDataPoints=100, minSpan=None, repeat=_Nothing.NOTHING, span=None, thresholds=_Nothing.NOTHING, thresholdType='absolute', timeFrom=None, timeShift=None, transparent=False, transformations=_Nothing.NOTHING, extraJson=None, bgURL='', autoScale=True, boxes=_Nothing.NOTHING)
Bases:
Panel
Generates ePict panel json structure. https://grafana.com/grafana/plugins/larona-epict-panel/
- Parameters:
autoScale – Whether to auto scale image to panel size.
bgURL – Where to load the image from.
boxes – The info boxes to be placed on the image.
- to_json_data()
- class grafanalib.core.ePictBox(angle=0, backgroundColor='#000', blinkHigh=False, blinkLow=False, color='#000', colorHigh='#000', colorLow='#000', colorMedium='#000', colorSymbol=False, customSymbol='', decimal=0, fontSize=12, hasBackground=False, hasOrb=False, hasSymbol=False, isUsingThresholds=False, orbHideText=False, orbLocation='Left', orbSize=13, prefix='', prefixSize=10, selected=False, serie='', suffix='', suffixSize=10, symbol='', symbolDefHeight=32, symbolDefWidth=32, symbolHeight=32, symbolHideText=False, symbolWidth=32, text='N/A', thresholds='', url='', xpos=0, ypos=0)
Bases:
object
ePict Box.
- Parameters:
angle – Rotation angle of box
backgroundColor – Dito
blinkHigh – Blink if below threshold
blinkLow – Blink if above threshold
color – Text color
colorHigh – High value color
colorLow – Low value color
colorMedium – In between value color
colorSymbol – Whether to enable background color for symbol
customSymbol – URL to custom symbol (will set symbol to “custom” if set)
decimal – Number of decimals
fontSize – Dito
hasBackground – Whether to enable background color for text
hasOrb – Whether an orb should be displayed
hasSymbol – Whether a (custom) symbol should be displayed
isUsingThresholds – Whether to enable thresholds.
orbHideText – Whether to hide text next to orb
orbLocation – Orb location (choose from ‘Left’, ‘Right’, ‘Top’ or ‘Bottom’)
orbSize – Dito
prefix – Value prefix to be displayed (e.g. °C)
prefixSize – Dito
selected – Dont know
serie – Which series to use data from
suffix – Value suffix to be displayed
suffixSize – Dito
symbol – Automatically placed by the plugin format: data:image/svg+xml;base64,<base64>, check manually.
symbolDefHeight – Dont know
symbolDefWidth – Dont know
symbolHeight – Dito
symbolHideText – Whether to hide value text next to symbol
symbolWidth – Dito
text – Dont know
thresholds – Coloring thresholds: Enter 2 comma-separated numbers. 20,60 will produce: value <= 20 -> green; value between 20 and 60 -> yellow; value >= 60 -> red. If set, it will also set isUsingThresholds to True
url – URL to open when clicked on
xpos – X in (0, X size of image)
ypos – Y in (0, Y size of image)
- to_json_data()
- grafanalib.core.is_valid_max_per_row(instance, attribute, value)
- grafanalib.core.is_valid_target(instance, attribute, value)
Check if a given attribute is a valid Target
- grafanalib.core.is_valid_triggers(instance, attribute, value)
Validator for AlertRule triggers
- grafanalib.core.is_valid_triggersv9(instance, attribute, value)
Validator for AlertRule triggers for Grafana v9
- grafanalib.core.is_valid_xaxis_mode(instance, attribute, value)
- grafanalib.core.single_y_axis(**kwargs)
Specify that a graph has a single Y axis.
Parameters are those passed to YAxis. Returns a YAxes object (i.e. a pair of axes) that can be used as the yAxes parameter of a graph.
- grafanalib.core.to_y_axes(data)
Backwards compatibility for ‘YAxes’.
In grafanalib 0.1.2 and earlier, Y axes were specified as a list of two elements. Now, we have a dedicated YAxes type.
This function converts a list of two YAxis values to a YAxes value, silently passes through YAxes values, warns about doing things the old way, and errors when there are invalid values.
grafanalib.elasticsearch module
Helpers to create Elasticsearch-specific Grafana queries.
- class grafanalib.elasticsearch.AverageMetricAgg(field='', id=0, hide=False, inline='')
Bases:
object
An aggregator that provides the average. value among the values.
- Parameters:
field – name of elasticsearch metric aggregator to provide the average of
id – id of the metric
hide – show/hide the metric in the final panel display
inline – script to apply to the data, using ‘_value’
- to_json_data()
- class grafanalib.elasticsearch.BucketScriptAgg(fields=_Nothing.NOTHING, id=0, hide=False, script='')
Bases:
object
An aggregator that applies a bucket script to the results of previous aggregations. https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-pipeline-bucket-script-aggregation.html
- Parameters:
fields – dictionary of field names mapped to aggregation IDs to be used in the bucket script e.g. { “field1”:1 }, which allows the output of aggregate ID 1 to be referenced as params.field1 in the bucket script
script – script to apply to the data using the variables specified in ‘fields’
id – id of the aggregator
hide – show/hide the metric in the final panel display
- to_json_data()
- class grafanalib.elasticsearch.CardinalityMetricAgg(field='', id=0, hide=False, inline='')
Bases:
object
An aggregator that provides the cardinality. value among the values.
- Parameters:
field – name of elasticsearch field to provide the cardinality for
id – id of the metric
hide – show/hide the metric in the final panel display
inline – script to apply to the data, using ‘_value’
- to_json_data()
- class grafanalib.elasticsearch.CountMetricAgg(id=0, hide=False, inline='')
Bases:
object
An aggregator that counts the number of values.
It’s the default aggregator for elasticsearch queries. :param hide: show/hide the metric in the final panel display :param id: id of the metric :param inline: script to apply to the data, using ‘_value’
- to_json_data()
- class grafanalib.elasticsearch.DateHistogramGroupBy(id=0, field='time_iso8601', interval='auto', minDocCount=0)
Bases:
object
A bucket aggregator that groups results by date.
- Parameters:
id – ascending unique number per GroupBy clause
field – name of the elasticsearch field to group by
interval – interval to group by
minDocCount – min. amount of records in the timespan to return a result
- to_json_data()
- class grafanalib.elasticsearch.DerivativeMetricAgg(field='', hide=False, id=0, pipelineAgg=1, unit='')
Bases:
object
An aggregator that takes the derivative of another metric aggregator.
- Parameters:
field – id of elasticsearch metric aggregator to provide the derivative of
hide – show/hide the metric in the final panel display
id – id of the metric
pipelineAgg – pipeline aggregator id
unit – derivative units
- to_json_data()
- class grafanalib.elasticsearch.ElasticsearchAlertCondition(evaluator=None, timeRange=None, operator='and', reducerType='last', useNewAlerts=False, target=None, *, type='query')
Bases:
AlertCondition
Override alert condition to support Elasticseach target.
See AlertCondition for more information.
- Parameters:
target (Target) – Metric the alert condition is based on.
evaluator (Evaluator) – How we decide whether we should alert on the metric. e.g.
GreaterThan(5)
means the metric must be greater than 5 to trigger the condition. SeeGreaterThan
,LowerThan
,WithinRange
,OutsideRange
,NoValue
.timeRange (TimeRange) – How long the condition must be true for before we alert.
operator – One of
OP_AND
orOP_OR
. How this condition combines with other conditions.reducerType – RTYPE_*
type – CTYPE_*
- class grafanalib.elasticsearch.ElasticsearchTarget(alias=None, bucketAggs=_Nothing.NOTHING, metricAggs=_Nothing.NOTHING, query='', refId='', timeField='@timestamp', hide=False)
Bases:
object
Generates Elasticsearch target JSON structure.
Grafana docs on using Elasticsearch: http://docs.grafana.org/features/datasources/elasticsearch/ Elasticsearch docs on querying or reading data: https://www.elastic.co/guide/en/elasticsearch/reference/current/index.html
- Parameters:
alias – legend alias
bucketAggs – Bucket aggregators
metricAggs – Metric Aggregators
query – query
refId – target reference id
timeField – name of the elasticsearch time field
hide – show/hide the target result in the final panel display
- auto_bucket_agg_ids()
Give unique IDs all bucketAggs without ID.
Returns a new
ElasticsearchTarget
that is the same as this one, except all of the bucketAggs have theirid
property set. Any panels which had anid
property set will keep that property, all others will have auto-generated IDs provided for them.If the bucketAggs don’t have unique ID associated with it, the generated graph will be broken.
- to_json_data()
- class grafanalib.elasticsearch.Filter(label='', query='')
Bases:
object
A Filter for a FilterGroupBy aggregator.
- Parameters:
label – label for the metric that is shown in the graph
query – the query to filter by
- to_json_data()
- class grafanalib.elasticsearch.FiltersGroupBy(id=0, filters=_Nothing.NOTHING)
Bases:
object
A bucket aggregator that groups records by a filter expression.
- Parameters:
id – ascending unique number per GroupBy clause
filters – list of Filter objects
- to_json_data()
- class grafanalib.elasticsearch.MaxMetricAgg(field='', id=0, hide=False, inline='')
Bases:
object
An aggregator that provides the max. value among the values.
- Parameters:
field – name of elasticsearch field to provide the maximum for
hide – show/hide the metric in the final panel display
id – id of the metric
inline – script to apply to the data, using ‘_value’
- to_json_data()
- class grafanalib.elasticsearch.MinMetricAgg(field='', id=0, hide=False, inline='')
Bases:
object
An aggregator that provides the min. value among the values. https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-metrics-min-aggregation.html :param field: name of elasticsearch field to provide the minimum for :param hide: show/hide the metric in the final panel display :param id: id of the metric :param inline: script to apply to the data, using ‘_value’
- to_json_data()
- class grafanalib.elasticsearch.PercentilesMetricAgg(field='', id=0, hide=False, inline='', percents=_Nothing.NOTHING, settings=_Nothing.NOTHING)
Bases:
object
A multi-value metrics aggregation that calculates one or more percentiles over numeric values extracted from the aggregated documents https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-metrics-percentile-aggregation.html :param field: name of elasticsearch field to provide the percentiles for :param hide: show/hide the metric in the final panel display :param id: id of the metric :param inline: script to apply to the data, using ‘_value’ :param percents: list of percentiles, like [95,99]
- to_json_data()
- class grafanalib.elasticsearch.RateMetricAgg(field='', id=0, hide=False, unit='', mode='', script='')
Bases:
object
An aggregator that provides the rate of the values. https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-metrics-rate-aggregation.html :param field: name of elasticsearch field to provide the sum over :param hide: show/hide the metric in the final panel display :param id: id of the metric :param unit: calendar interval to group by
supported calendar intervals https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-bucket-datehistogram-aggregation.html#calendar_intervals “minute” “hour” “day” “week” “month” “quarter” “year”
- Parameters:
mode – sum or count the values
script – script to apply to the data, using ‘_value’
- to_json_data()
- class grafanalib.elasticsearch.SumMetricAgg(field='', id=0, hide=False, inline='')
Bases:
object
An aggregator that provides the sum of the values. https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-metrics-sum-aggregation.html :param field: name of elasticsearch field to provide the sum over :param hide: show/hide the metric in the final panel display :param id: id of the metric :param inline: script to apply to the data, using ‘_value’
- to_json_data()
- class grafanalib.elasticsearch.TermsGroupBy(field, id=0, minDocCount=1, order='desc', orderBy='_term', size=0)
Bases:
object
A multi-bucket aggregator based on field values.
- Parameters:
id – ascending unique number per GroupBy clause
field – name of the field to group by
minDocCount – min. amount of matching records to return a result
order – ORDER_ASC or ORDER_DESC
orderBy – term to order the bucket Term value: ‘_term’, Doc Count: ‘_count’ or to use metric function use the string value “2”
size – how many buckets are returned
- to_json_data()
grafanalib.formatunits module
Grafana unit formats (https://github.com/grafana/grafana/blob/main/packages/grafana-data/src/valueFormats/categories.ts)
To use: from grafanalib import formatunits as UNITS
format = UNITS.BYTES
grafanalib.influxdb module
Helpers to create InfluxDB-specific Grafana queries.
- class grafanalib.influxdb.InfluxDBTarget(alias='', format='time_series', datasource='', measurement='', query='', rawQuery=True, refId='')
Bases:
object
Generates InfluxDB target JSON structure.
Grafana docs on using InfluxDB: https://grafana.com/docs/features/datasources/influxdb/ InfluxDB docs on querying or reading data: https://v2.docs.influxdata.com/v2.0/query-data/
- Parameters:
alias – legend alias
format – Bucket aggregators
datasource – Influxdb name (for multiple datasource with same panel)
measurement – Metric Aggregators
query – query
rawQuery – target reference id
refId – target reference id
- to_json_data()
grafanalib.opentsdb module
Support for OpenTSDB.
- class grafanalib.opentsdb.OpenTSDBFilter(value, tag, type='literal_or', groupBy=False)
Bases:
object
- to_json_data()
- class grafanalib.opentsdb.OpenTSDBTarget(metric, refId='', aggregator='sum', alias=None, isCounter=False, counterMax=None, counterResetValue=None, disableDownsampling=False, downsampleAggregator='sum', downsampleFillPolicy='none', downsampleInterval=None, filters=_Nothing.NOTHING, shouldComputeRate=False, currentFilterGroupBy=False, currentFilterKey='', currentFilterType='literal_or', currentFilterValue='')
Bases:
object
Generates OpenTSDB target JSON structure.
Grafana docs on using OpenTSDB: http://docs.grafana.org/features/datasources/opentsdb/ OpenTSDB docs on querying or reading data: http://opentsdb.net/docs/build/html/user_guide/query/index.html
- Parameters:
metric – OpenTSDB metric name
refId – target reference id
aggregator – defines metric aggregator. The list of opentsdb aggregators: http://opentsdb.net/docs/build/html/user_guide/query/aggregators.html#available-aggregators
alias – legend alias. Use patterns like $tag_tagname to replace part of the alias for a tag value.
isCounter – defines if rate function results should be interpret as counter
counterMax – defines rate counter max value
counterResetValue – defines rate counter reset value
disableDownsampling – defines if downsampling should be disabled. OpenTSDB docs on downsampling: http://opentsdb.net/docs/build/html/user_guide/query/index.html#downsampling
downsampleAggregator – defines downsampling aggregator
downsampleFillPolicy – defines downsampling fill policy
downsampleInterval – defines downsampling interval
filters – defines the list of metric query filters. OpenTSDB docs on filters: http://opentsdb.net/docs/build/html/user_guide/query/index.html#filters
shouldComputeRate – defines if rate function should be used. OpenTSDB docs on rate function: http://opentsdb.net/docs/build/html/user_guide/query/index.html#rate
currentFilterGroupBy – defines if grouping should be enabled for current filter
currentFilterKey – defines current filter key
currentFilterType – defines current filter type
currentFilterValue – defines current filter value
- to_json_data()
grafanalib.prometheus module
Helpers for Prometheus-driven graphs.
- grafanalib.prometheus.PromGraph(data_source, title, expressions, **kwargs)
Create a graph that renders Prometheus data.
- Parameters:
data_source (str) – The name of the data source that provides Prometheus data.
title – The title of the graph.
expressions – List of tuples of (legend, expr), where ‘expr’ is a Prometheus expression. Or a list of dict where keys are Target’s args.
kwargs – Passed on to Graph.
grafanalib.validators module
- grafanalib.validators.is_color_code(instance, attribute, value)
A validator that raises a
ValueError
if attribute value is not valid color code. Value considered as valid color code if it starts with # char followed by hexadecimal.
- grafanalib.validators.is_in(choices)
A validator that raises a
ValueError
if the attribute value is not in a provided list.- Parameters:
choices – List of valid choices
- grafanalib.validators.is_interval(instance, attribute, value)
A validator that raises a
ValueError
if the attribute value is not matching regular expression.
- grafanalib.validators.is_list_of(etype)
A validator that raises a
ValueError
if the attribute value is not in a provided list.- Parameters:
choices – List of valid choices
grafanalib.weave module
Weave-specific dashboard configuration.
Unlike ‘core’, which has logic for building generic Grafana dashboards, this has our Weave-specific preferences.
- grafanalib.weave.PercentUnitAxis(label=None)
A Y axis that shows a percentage based on a unit value.
- grafanalib.weave.QPSGraph(data_source, title, expressions, **kwargs)
Create a graph of QPS, broken up by response code.
Data is drawn from Prometheus.
- Parameters:
title – Title of the graph.
expressions – List of Prometheus expressions. Must be 5.
kwargs – Passed on to Graph.
- grafanalib.weave.stacked(graph)
Turn a graph into a stacked graph.
grafanalib.zabbix module
- class grafanalib.zabbix.ZabbixAggregateByFunction(added=False, interval='1m', function='avg')
Bases:
object
Takes all timeseries and consolidate all its points falled in given interval into one point using function, which can be one of: avg, min, max, median. https://alexanderzobnin.github.io/grafana-zabbix/reference/functions/#aggregateBy
- to_json_data()
- class grafanalib.zabbix.ZabbixAverageFunction(added=False, interval='1m')
Bases:
object
Deprecated, use aggregateBy(interval, avg) instead. https://alexanderzobnin.github.io/grafana-zabbix/reference/functions/#average
- to_json_data()
- class grafanalib.zabbix.ZabbixBottomFunction(added=False, number=5, function='avg')
Bases:
object
- to_json_data()
- class grafanalib.zabbix.ZabbixColor(color, priority, severity, show=True)
Bases:
object
- to_json_data()
- class grafanalib.zabbix.ZabbixDeltaFunction(added=False)
Bases:
object
Convert absolute values to delta, for example, bits to bits/sec https://alexanderzobnin.github.io/grafana-zabbix/reference/functions/#delta
- to_json_data()
- class grafanalib.zabbix.ZabbixGroupByFunction(added=False, interval='1m', function='avg')
Bases:
object
Takes each timeseries and consolidate its points falled in given interval into one point using function, which can be one of: avg, min, max, median. https://alexanderzobnin.github.io/grafana-zabbix/reference/functions//#groupBy
- to_json_data()
- class grafanalib.zabbix.ZabbixMaxFunction(added=False, interval='1m')
Bases:
object
Deprecated, use aggregateBy(interval, max) instead. https://alexanderzobnin.github.io/grafana-zabbix/reference/functions/#max
- to_json_data()
- class grafanalib.zabbix.ZabbixMedianFunction(added=False, interval='1m')
Bases:
object
Deprecated, use aggregateBy(interval, median) instead. https://alexanderzobnin.github.io/grafana-zabbix/reference/functions/#median
- to_json_data()
- class grafanalib.zabbix.ZabbixMinFunction(added=False, interval='1m')
Bases:
object
Deprecated, use aggregateBy(interval, min) instead. https://alexanderzobnin.github.io/grafana-zabbix/reference/functions/#min
- to_json_data()
- class grafanalib.zabbix.ZabbixScaleFunction(added=False, factor=100)
Bases:
object
Takes timeseries and multiplies each point by the given factor. https://alexanderzobnin.github.io/grafana-zabbix/reference/functions//#scale
- to_json_data()
- class grafanalib.zabbix.ZabbixSetAliasByRegexFunction(regexp, added=False)
Bases:
object
Returns part of the metric name matched by regex. https://alexanderzobnin.github.io/grafana-zabbix/reference/functions/#setAliasByRegex
- to_json_data()
- class grafanalib.zabbix.ZabbixSetAliasFunction(alias, added=False)
Bases:
object
Returns given alias instead of the metric name. https://alexanderzobnin.github.io/grafana-zabbix/reference/functions/#setAlias
- to_json_data()
- class grafanalib.zabbix.ZabbixSumSeriesFunction(added=False)
Bases:
object
This will add metrics together and return the sum at each datapoint. This method required interpolation of each timeseries so it may cause high CPU load. Try to combine it with groupBy() function to reduce load. https://alexanderzobnin.github.io/grafana-zabbix/reference/functions/#sumSeries
- to_json_data()
- class grafanalib.zabbix.ZabbixTarget(application='', expr='', functions=_Nothing.NOTHING, group='', host='', intervalFactor=2, item='', itService='', mode=0, options=_Nothing.NOTHING, refId='', slaProperty=_Nothing.NOTHING, textFilter='', useCaptureGroups=False)
Bases:
object
Generates Zabbix datasource target JSON structure.
Grafana-Zabbix is a plugin for Grafana allowing to visualize monitoring data from Zabbix and create dashboards for analyzing metrics and realtime monitoring.
Grafana docs on using Zabbix plugin: https://alexanderzobnin.github.io/grafana-zabbix/
- Parameters:
application – zabbix application name
expr – zabbix arbitary query
functions – list of zabbix aggregation functions
group – zabbix host group
host – hostname
intervalFactor – defines interval between metric queries
item – regexp that defines which metric to query
itService – zabbix it service name
mode – query mode type
options – additional query options
refId – target reference id
slaProperty – zabbix it service sla property. Zabbix returns the following availability information about IT service Status - current status of the IT service SLA - SLA for the given time interval OK time - time the service was in OK state, in seconds Problem time - time the service was in problem state, in seconds Down time - time the service was in scheduled downtime, in seconds
textFilter – query text filter. Use regex to extract a part of the returned value.
useCaptureGroups – defines if capture groups should be used during metric query
- to_json_data()
- class grafanalib.zabbix.ZabbixTimeShiftFunction(added=False, interval='24h')
Bases:
object
Draws the selected metrics shifted in time. If no sign is given, a minus sign ( - ) is implied which will shift the metric back in time. If a plus sign ( + ) is given, the metric will be shifted forward in time. https://alexanderzobnin.github.io/grafana-zabbix/reference/functions/#timeShift
- to_json_data()
- class grafanalib.zabbix.ZabbixTopFunction(added=False, number=5, function='avg')
Bases:
object
- to_json_data()
- class grafanalib.zabbix.ZabbixTrendValueFunction(added=False, type='avg')
Bases:
object
Specifying type of trend value returned by Zabbix when trends are used (avg, min or max). https://alexanderzobnin.github.io/grafana-zabbix/reference/functions/#trendValue
- to_json_data()
- class grafanalib.zabbix.ZabbixTrigger(application='', group='', host='', trigger='')
Bases:
object
- to_json_data()
- class grafanalib.zabbix.ZabbixTriggersPanel(dataSource, title, ackEventColor=_Nothing.NOTHING, ageField=True, customLastChangeFormat=False, description='', fontSize=_Nothing.NOTHING, height=Pixels(num=250), hideHostsInMaintenance=False, hostField=True, hostTechNameField=False, id=None, infoField=True, lastChangeField=True, lastChangeFormat='', limit=10, links=_Nothing.NOTHING, markAckEvents=False, minSpan=None, okEventColor=_Nothing.NOTHING, pageSize=10, repeat=None, scroll=True, severityField=False, showEvents=_Nothing.NOTHING, showTriggers='all triggers', sortTriggersBy=_Nothing.NOTHING, span=None, statusField=False, transparent=False, triggerSeverity=(('#B7DBAB', 'Not classified'), ('#82B5D8', 'Information'), ('#E5AC0E', 'Warning'), ('#C15C17', 'Average'), ('#BF1B00', 'High'), ('#890F02', 'Disaster')), triggers=_Nothing.NOTHING)
Bases:
object
- Parameters:
dataSource – query datasource name
title – panel title
ackEventColor – acknowledged triggers color
customLastChangeFormat – defines last change field data format. See momentjs docs for time format: http://momentjs.com/docs/#/displaying/format/
description – additional panel description
fontSize – panel font size
height – panel height in Pixels
hideHostsInMaintenance – defines if triggers form hosts in maintenance should be shown
hostField – defines if host field should be shown
hostTechNameField – defines if field with host technical name should be shown
id – panel identificator
infoField – defines if field with host info should be shown
lastChangeField – defines if field with last change time should be shown
limit – defines number of queried triggers
links – list of dashboard links
markAckEvents – defines if acknowledged triggers should be colored with different color
minSpan – defines panel minimum spans
okEventColor – defines color for triggers with Ok status
pageSize – defines number of triggers per panel page
scroll – defines if scroll should be shown
severityField – defines if severity field should be shown
showEvents – defines event type to query (Ok, Problems, All)
showTriggers – defines trigger type to query (all, acknowledged, unacknowledged)
sortTriggersBy – defines trigger sort policy
span – defines span number for panel
statusField – defines if status field should be shown
transparent – defines if panel should be transparent
triggerSeverity – defines colors for trigger severity,
triggers – trigger query
- to_json_data()
- grafanalib.zabbix.convertZabbixSeverityColors(colors)
- grafanalib.zabbix.zabbixMetricTarget(application, group, host, item, functions=[])
- grafanalib.zabbix.zabbixServiceTarget(service, sla={'name': 'Status', 'property': 'status'})
- grafanalib.zabbix.zabbixTextTarget(application, group, host, item, text, useCaptureGroups=False)
Module contents
Routines for building Grafana dashboards.