Skip to content

Instantly share code, notes, and snippets.

@coip
Created April 2, 2020 15:39
Show Gist options
  • Save coip/280472fceeca2e52d0ee74f513388bce to your computer and use it in GitHub Desktop.
Save coip/280472fceeca2e52d0ee74f513388bce to your computer and use it in GitHub Desktop.
testing appinsights for fs .env scoping. helped identify issue with scheduled task invocation, might be an otherwise useful snippet.
package main
import (
"fmt"
"os"
"path/filepath"
"time"
"github.com/joho/godotenv"
"github.com/microsoft/ApplicationInsights-Go/appinsights"
)
const (
envinsightskey = "ikey"
envfile = ".env"
)
var (
insightsClient appinsights.TelemetryClient
)
func init() {
var (
keyProvided bool
instrumentationKey string
)
if err := godotenv.Load(envfile); err != nil {
dir, _ := os.Getwd()
panic(fmt.Errorf("provide envfile in %s%s%s", dir, string(filepath.Separator), envfile))
}
if instrumentationKey, keyProvided = os.LookupEnv(envinsightskey); keyProvided == false {
panic(fmt.Errorf("provide value for key=%q in envfile", envinsightskey))
} else {
insightsClient = appinsights.NewTelemetryClientFromConfig(
appinsights.NewTelemetryConfiguration(instrumentationKey),
)
appinsights.NewDiagnosticsMessageListener(func(msg string) error {
fmt.Printf("[%s] %s\n", time.Now().Format(time.UnixDate), msg)
return nil
})
}
}
func main() {
var event = func() string {
host, _ := os.Hostname()
return fmt.Sprintf("testing on %s.", host)
}
insightsClient.TrackEvent(event())
select {
case <-insightsClient.Channel().Close(10 * time.Second):
// Ten second timeout for retries.
os.Exit(0)
// If we got here, then all telemetry was submitted
// successfully, and we can proceed to exiting.
case <-time.After(30 * time.Second):
// Thirty second absolute timeout. This covers any
// previous telemetry submission that may not have
// completed before Close was called.
os.Exit(1)
// There are a number of reasons we could have
// reached here. We gave it a go, but telemetry
// submission failed somewhere. Perhaps old events
// were still retrying, or perhaps we're throttled.
// Either way, we don't want to wait around for it
// to complete, so let's just exit.
}
//ref for select above: https://github.com/microsoft/ApplicationInsights-Go#shutdown
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment