github.com/newrelic/newrelic-client-go@v1.1.0/pkg/alerts/example_policy_test.go (about) 1 package alerts 2 3 import ( 4 "log" 5 "os" 6 7 "github.com/newrelic/newrelic-client-go/pkg/config" 8 ) 9 10 func Example_policy() { 11 // Initialize the client configuration. A Personal API key is required to 12 // communicate with the backend API. 13 // is deprecated. 14 cfg := config.New() 15 cfg.PersonalAPIKey = os.Getenv("NEW_RELIC_API_KEY") 16 17 // Initialize the client. 18 client := New(cfg) 19 20 // Create a new alert policy. 21 p := Policy{ 22 Name: "Example alert policy", 23 IncidentPreference: IncidentPreferenceTypes.PerCondition, 24 } 25 26 policy, err := client.CreatePolicy(p) 27 if err != nil { 28 log.Fatal("error creating policy:", err) 29 } 30 31 // Create a new alert notification channel. 32 ec := Channel{ 33 Name: "Example email notification channel", 34 Type: ChannelTypes.Email, 35 Configuration: ChannelConfiguration{ 36 Recipients: "test@newrelic.com", 37 IncludeJSONAttachment: "1", 38 }, 39 } 40 41 emailChannel, err := client.CreateChannel(ec) 42 if err != nil { 43 log.Fatal("error creating notification channel:", err) 44 } 45 46 // Associate the new alert channel with the created policy. 47 _, err = client.UpdatePolicyChannels(policy.ID, []int{emailChannel.ID}) 48 if err != nil { 49 log.Fatal("error associating policy with channel:", err) 50 } 51 52 // Create a new NRQL alert condition. 53 nc := &NrqlCondition{ 54 Name: "Example NRQL condition", 55 Type: "static", 56 RunbookURL: "https://www.example.com/myrunbook", 57 Enabled: true, 58 ValueFunction: ValueFunctionTypes.SingleValue, 59 Nrql: NrqlQuery{ 60 Query: "FROM Transaction SELECT average(duration) WHERE appName = 'Example Application'", 61 SinceValue: "3", 62 }, 63 Terms: []ConditionTerm{ 64 { 65 Duration: 5, 66 Operator: OperatorTypes.Above, 67 Priority: PriorityTypes.Warning, 68 Threshold: 3, 69 TimeFunction: TimeFunctionTypes.All, 70 }, 71 { 72 Duration: 5, 73 Operator: OperatorTypes.Above, 74 Priority: PriorityTypes.Critical, 75 Threshold: 1, 76 TimeFunction: TimeFunctionTypes.All, 77 }, 78 }, 79 } 80 81 _, err = client.CreateNrqlCondition(policy.ID, *nc) 82 if err != nil { 83 log.Fatal("error creating NRQL condition:", err) 84 } 85 }