remove the global log error/warn etc functions (#41404)

* remove the global log error/warn etc functions and use request context logger whenever possible
This commit is contained in:
ying-jeanne 2021-11-08 17:56:56 +01:00 committed by GitHub
parent bda60f3458
commit 54de1078c8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
28 changed files with 88 additions and 93 deletions

View File

@ -17,6 +17,7 @@ import (
) )
var pluginProxyTransport *http.Transport var pluginProxyTransport *http.Transport
var applog = log.New("app.routes")
func (hs *HTTPServer) initAppPluginRoutes(r *web.Mux) { func (hs *HTTPServer) initAppPluginRoutes(r *web.Mux) {
pluginProxyTransport = &http.Transport{ pluginProxyTransport = &http.Transport{
@ -51,7 +52,8 @@ func (hs *HTTPServer) initAppPluginRoutes(r *web.Mux) {
for _, method := range strings.Split(route.Method, ",") { for _, method := range strings.Split(route.Method, ",") {
r.Handle(strings.TrimSpace(method), url, handlers) r.Handle(strings.TrimSpace(method), url, handlers)
} }
log.Debug("Plugins: Adding proxy route", "url", url)
applog.Debug("Plugins: Adding proxy route", "url", url)
} }
} }
} }

View File

@ -40,6 +40,8 @@ type Avatar struct {
timestamp time.Time timestamp time.Time
} }
var alog = log.New("avatar")
func New(hash string) *Avatar { func New(hash string) *Avatar {
return &Avatar{ return &Avatar{
hash: hash, hash: hash,
@ -95,7 +97,7 @@ func (a *CacheServer) Handler(ctx *models.ReqContext) {
if avatar.Expired() { if avatar.Expired() {
// The cache item is either expired or newly created, update it from the server // The cache item is either expired or newly created, update it from the server
if err := avatar.Update(); err != nil { if err := avatar.Update(); err != nil {
log.Debug("avatar update", "err", err) ctx.Logger.Debug("avatar update", "err", err)
avatar = a.notFound avatar = a.notFound
} }
} }
@ -104,7 +106,7 @@ func (a *CacheServer) Handler(ctx *models.ReqContext) {
avatar = a.notFound avatar = a.notFound
} else if !exists { } else if !exists {
if err := a.cache.Add(hash, avatar, gocache.DefaultExpiration); err != nil { if err := a.cache.Add(hash, avatar, gocache.DefaultExpiration); err != nil {
log.Debug("add avatar to cache", "err", err) ctx.Logger.Debug("add avatar to cache", "err", err)
} }
} }
@ -117,7 +119,7 @@ func (a *CacheServer) Handler(ctx *models.ReqContext) {
ctx.Resp.Header().Set("Cache-Control", "private, max-age=3600") ctx.Resp.Header().Set("Cache-Control", "private, max-age=3600")
if err := avatar.Encode(ctx.Resp); err != nil { if err := avatar.Encode(ctx.Resp); err != nil {
log.Warn("avatar encode error:", "err", err) ctx.Logger.Warn("avatar encode error:", "err", err)
ctx.Resp.WriteHeader(500) ctx.Resp.WriteHeader(500)
} }
} }
@ -142,7 +144,7 @@ func newNotFound(cfg *setting.Cfg) *Avatar {
// variable. // variable.
// nolint:gosec // nolint:gosec
if data, err := ioutil.ReadFile(path); err != nil { if data, err := ioutil.ReadFile(path); err != nil {
log.Error("Failed to read user_profile.png", "path", path) alog.Error("Failed to read user_profile.png", "path", path)
} else { } else {
avatar.data = bytes.NewBuffer(data) avatar.data = bytes.NewBuffer(data)
} }
@ -215,7 +217,7 @@ var client = &http.Client{
func (a *thunderTask) fetch() error { func (a *thunderTask) fetch() error {
a.Avatar.timestamp = time.Now() a.Avatar.timestamp = time.Now()
log.Debug("avatar.fetch(fetch new avatar)", "url", a.Url) alog.Debug("avatar.fetch(fetch new avatar)", "url", a.Url)
req, err := http.NewRequest("GET", a.Url, nil) req, err := http.NewRequest("GET", a.Url, nil)
if err != nil { if err != nil {
return err return err
@ -232,7 +234,7 @@ func (a *thunderTask) fetch() error {
} }
defer func() { defer func() {
if err := resp.Body.Close(); err != nil { if err := resp.Body.Close(); err != nil {
log.Warn("Failed to close response body", "err", err) alog.Warn("Failed to close response body", "err", err)
} }
}() }()

View File

@ -13,6 +13,7 @@ import (
) )
var regNonAlphaNumeric = regexp.MustCompile("[^a-zA-Z0-9]+") var regNonAlphaNumeric = regexp.MustCompile("[^a-zA-Z0-9]+")
var mlog = log.New("models")
type AnyId struct { type AnyId struct {
Id int64 `json:"id"` Id int64 `json:"id"`
@ -65,7 +66,7 @@ func GetGravatarUrl(text string) string {
hasher := md5.New() hasher := md5.New()
if _, err := hasher.Write([]byte(strings.ToLower(text))); err != nil { if _, err := hasher.Write([]byte(strings.ToLower(text))); err != nil {
log.Warn("Failed to hash text", "err", err) mlog.Warn("Failed to hash text", "err", err)
} }
return fmt.Sprintf(setting.AppSubUrl+"/avatar/%x", hasher.Sum(nil)) return fmt.Sprintf(setting.AppSubUrl+"/avatar/%x", hasher.Sum(nil))
} }

View File

@ -7,7 +7,6 @@ import (
"github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/components/simplejson" "github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/plugins" "github.com/grafana/grafana/pkg/plugins"
"github.com/grafana/grafana/pkg/services/accesscontrol" "github.com/grafana/grafana/pkg/services/accesscontrol"
@ -64,7 +63,7 @@ func (hs *HTTPServer) getFSDataSources(c *models.ReqContext, enabledPlugins Enab
meta, exists := enabledPlugins.Get(plugins.DataSource, ds.Type) meta, exists := enabledPlugins.Get(plugins.DataSource, ds.Type)
if !exists { if !exists {
log.Error("Could not find plugin definition for data source", "datasource_type", ds.Type) c.Logger.Error("Could not find plugin definition for data source", "datasource_type", ds.Type)
continue continue
} }
dsMap["preload"] = meta.Preload dsMap["preload"] = meta.Preload

View File

@ -11,7 +11,6 @@ import (
"github.com/grafana/grafana/pkg/api/dtos" "github.com/grafana/grafana/pkg/api/dtos"
"github.com/grafana/grafana/pkg/api/response" "github.com/grafana/grafana/pkg/api/response"
"github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/infra/metrics" "github.com/grafana/grafana/pkg/infra/metrics"
"github.com/grafana/grafana/pkg/infra/network" "github.com/grafana/grafana/pkg/infra/network"
"github.com/grafana/grafana/pkg/login" "github.com/grafana/grafana/pkg/login"
@ -131,7 +130,7 @@ func (hs *HTTPServer) LoginView(c *models.ReqContext) {
if err := hs.ValidateRedirectTo(redirectTo); err != nil { if err := hs.ValidateRedirectTo(redirectTo); err != nil {
// the user is already logged so instead of rendering the login page with error // the user is already logged so instead of rendering the login page with error
// it should be redirected to the home page. // it should be redirected to the home page.
log.Debug("Ignored invalid redirect_to cookie value", "redirect_to", redirectTo) c.Logger.Debug("Ignored invalid redirect_to cookie value", "redirect_to", redirectTo)
redirectTo = hs.Cfg.AppSubURL + "/" redirectTo = hs.Cfg.AppSubURL + "/"
} }
cookies.DeleteCookie(c.Resp, "redirect_to", hs.CookieOptionsFromCfg) cookies.DeleteCookie(c.Resp, "redirect_to", hs.CookieOptionsFromCfg)
@ -152,12 +151,12 @@ func (hs *HTTPServer) tryOAuthAutoLogin(c *models.ReqContext) bool {
} }
oauthInfos := hs.SocialService.GetOAuthInfoProviders() oauthInfos := hs.SocialService.GetOAuthInfoProviders()
if len(oauthInfos) != 1 { if len(oauthInfos) != 1 {
log.Warn("Skipping OAuth auto login because multiple OAuth providers are configured") c.Logger.Warn("Skipping OAuth auto login because multiple OAuth providers are configured")
return false return false
} }
for key := range oauthInfos { for key := range oauthInfos {
redirectUrl := hs.Cfg.AppSubURL + "/login/" + key redirectUrl := hs.Cfg.AppSubURL + "/login/" + key
log.Info("OAuth auto login enabled. Redirecting to " + redirectUrl) c.Logger.Info("OAuth auto login enabled. Redirecting to " + redirectUrl)
c.Redirect(redirectUrl, 307) c.Redirect(redirectUrl, 307)
return true return true
} }
@ -249,7 +248,7 @@ func (hs *HTTPServer) LoginPost(c *models.ReqContext) response.Response {
if err := hs.ValidateRedirectTo(redirectTo); err == nil { if err := hs.ValidateRedirectTo(redirectTo); err == nil {
result["redirectUrl"] = redirectTo result["redirectUrl"] = redirectTo
} else { } else {
log.Info("Ignored invalid redirect_to cookie value.", "url", redirectTo) c.Logger.Info("Ignored invalid redirect_to cookie value.", "url", redirectTo)
} }
cookies.DeleteCookie(c.Resp, "redirect_to", hs.CookieOptionsFromCfg) cookies.DeleteCookie(c.Resp, "redirect_to", hs.CookieOptionsFromCfg)
} }

View File

@ -256,7 +256,7 @@ func (hs *HTTPServer) OAuthLogin(ctx *models.ReqContext) {
ctx.Redirect(redirectTo) ctx.Redirect(redirectTo)
return return
} }
log.Debug("Ignored invalid redirect_to cookie value", "redirect_to", redirectTo) ctx.Logger.Debug("Ignored invalid redirect_to cookie value", "redirect_to", redirectTo)
} }
ctx.Redirect(setting.AppSubUrl + "/") ctx.Redirect(setting.AppSubUrl + "/")

View File

@ -41,6 +41,8 @@ type exitWithCode struct {
var serverFs = flag.NewFlagSet("server", flag.ContinueOnError) var serverFs = flag.NewFlagSet("server", flag.ContinueOnError)
var clilog = log.New("cli")
func (e exitWithCode) Error() string { func (e exitWithCode) Error() string {
return e.reason return e.reason
} }
@ -133,7 +135,7 @@ func executeServer(configFile, homePath, pidFile, packaging string, traceDiagnos
} }
defer func() { defer func() {
if err := f.Close(); err != nil { if err := f.Close(); err != nil {
log.Error("Failed to write trace diagnostics", "path", traceDiagnostics.file, "err", err) clilog.Error("Failed to write trace diagnostics", "path", traceDiagnostics.file, "err", err)
} }
}() }()

View File

@ -74,7 +74,7 @@ func (u *S3Uploader) Upload(ctx context.Context, imageDiskPath string) (string,
return "", err return "", err
} }
key := u.path + rand + pngExt key := u.path + rand + pngExt
log.Debug("Uploading image to s3.", "bucket", u.bucket, "path", key) u.log.Debug("Uploading image to s3.", "bucket", u.bucket, "path", key)
// We can ignore the gosec G304 warning on this one because `imageDiskPath` comes // We can ignore the gosec G304 warning on this one because `imageDiskPath` comes
// from alert notifiers and is only used to upload images generated by alerting. // from alert notifiers and is only used to upload images generated by alerting.

View File

@ -36,22 +36,6 @@ func New(logger string, ctx ...interface{}) Logger {
return Root.New(params...) return Root.New(params...)
} }
func Warn(msg string, v ...interface{}) {
Root.Warn(msg, v...)
}
func Debug(msg string, args ...interface{}) {
Root.Debug(msg, args...)
}
func Info(msg string, args ...interface{}) {
Root.Info(msg, args...)
}
func Error(msg string, args ...interface{}) {
Root.Error(msg, args...)
}
func Close() error { func Close() error {
var err error var err error
for _, logger := range loggersToClose { for _, logger := range loggersToClose {

View File

@ -8,7 +8,6 @@ import (
"net/http" "net/http"
"strings" "strings"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/util/errutil" "github.com/grafana/grafana/pkg/util/errutil"
"github.com/jmespath/go-jmespath" "github.com/jmespath/go-jmespath"
) )
@ -67,8 +66,7 @@ func (s *SocialBase) httpGet(client *http.Client, url string) (response httpGetR
err = fmt.Errorf(string(response.Body)) err = fmt.Errorf(string(response.Body))
return return
} }
s.log.Debug("HTTP GET", "url", url, "status", r.Status, "response_body", string(response.Body))
log.Debug("HTTP GET", "url", url, "status", r.Status, "response_body", string(response.Body))
err = nil err = nil
return return

View File

@ -28,7 +28,7 @@ func (f *Finder) Find(pluginDirs []string) ([]string, error) {
for _, dir := range pluginDirs { for _, dir := range pluginDirs {
exists, err := fs.Exists(dir) exists, err := fs.Exists(dir)
if err != nil { if err != nil {
log.Warn("Error occurred when checking if plugin directory exists", "dir", dir, "err", err) logger.Warn("Error occurred when checking if plugin directory exists", "dir", dir, "err", err)
} }
if !exists { if !exists {
logger.Warn("Skipping finding plugins as directory does not exist", "dir", dir) logger.Warn("Skipping finding plugins as directory does not exist", "dir", dir)

View File

@ -99,7 +99,7 @@ func readPluginManifest(body []byte) (*pluginManifest, error) {
return manifest, nil return manifest, nil
} }
func Calculate(log log.Logger, plugin *plugins.Plugin) (plugins.Signature, error) { func Calculate(mlog log.Logger, plugin *plugins.Plugin) (plugins.Signature, error) {
if plugin.IsCorePlugin() { if plugin.IsCorePlugin() {
return plugins.Signature{ return plugins.Signature{
Status: plugins.SignatureInternal, Status: plugins.SignatureInternal,
@ -113,7 +113,7 @@ func Calculate(log log.Logger, plugin *plugins.Plugin) (plugins.Signature, error
// on plugin the folder structure on disk and not user input. // on plugin the folder structure on disk and not user input.
byteValue, err := ioutil.ReadFile(manifestPath) byteValue, err := ioutil.ReadFile(manifestPath)
if err != nil || len(byteValue) < 10 { if err != nil || len(byteValue) < 10 {
log.Debug("Plugin is unsigned", "id", plugin.ID) mlog.Debug("Plugin is unsigned", "id", plugin.ID)
return plugins.Signature{ return plugins.Signature{
Status: plugins.SignatureUnsigned, Status: plugins.SignatureUnsigned,
}, nil }, nil
@ -121,7 +121,7 @@ func Calculate(log log.Logger, plugin *plugins.Plugin) (plugins.Signature, error
manifest, err := readPluginManifest(byteValue) manifest, err := readPluginManifest(byteValue)
if err != nil { if err != nil {
log.Debug("Plugin signature invalid", "id", plugin.ID) mlog.Debug("Plugin signature invalid", "id", plugin.ID)
return plugins.Signature{ return plugins.Signature{
Status: plugins.SignatureInvalid, Status: plugins.SignatureInvalid,
}, nil }, nil
@ -145,7 +145,7 @@ func Calculate(log log.Logger, plugin *plugins.Plugin) (plugins.Signature, error
for _, u := range manifest.RootURLs { for _, u := range manifest.RootURLs {
rootURL, err := url.Parse(u) rootURL, err := url.Parse(u)
if err != nil { if err != nil {
log.Warn("Could not parse plugin root URL", "plugin", plugin.ID, "rootUrl", rootURL) mlog.Warn("Could not parse plugin root URL", "plugin", plugin.ID, "rootUrl", rootURL)
return plugins.Signature{}, err return plugins.Signature{}, err
} }
@ -158,7 +158,7 @@ func Calculate(log log.Logger, plugin *plugins.Plugin) (plugins.Signature, error
} }
if !foundMatch { if !foundMatch {
log.Warn("Could not find root URL that matches running application URL", "plugin", plugin.ID, mlog.Warn("Could not find root URL that matches running application URL", "plugin", plugin.ID,
"appUrl", appURL, "rootUrls", manifest.RootURLs) "appUrl", appURL, "rootUrls", manifest.RootURLs)
return plugins.Signature{ return plugins.Signature{
Status: plugins.SignatureInvalid, Status: plugins.SignatureInvalid,
@ -170,7 +170,7 @@ func Calculate(log log.Logger, plugin *plugins.Plugin) (plugins.Signature, error
// Verify the manifest contents // Verify the manifest contents
for p, hash := range manifest.Files { for p, hash := range manifest.Files {
err = verifyHash(plugin.ID, filepath.Join(plugin.PluginDir, p), hash) err = verifyHash(mlog, plugin.ID, filepath.Join(plugin.PluginDir, p), hash)
if err != nil { if err != nil {
return plugins.Signature{ return plugins.Signature{
Status: plugins.SignatureModified, Status: plugins.SignatureModified,
@ -183,7 +183,7 @@ func Calculate(log log.Logger, plugin *plugins.Plugin) (plugins.Signature, error
if manifest.isV2() { if manifest.isV2() {
pluginFiles, err := pluginFilesRequiringVerification(plugin) pluginFiles, err := pluginFilesRequiringVerification(plugin)
if err != nil { if err != nil {
log.Warn("Could not collect plugin file information in directory", "pluginID", plugin.ID, "dir", plugin.PluginDir) mlog.Warn("Could not collect plugin file information in directory", "pluginID", plugin.ID, "dir", plugin.PluginDir)
return plugins.Signature{ return plugins.Signature{
Status: plugins.SignatureInvalid, Status: plugins.SignatureInvalid,
}, err }, err
@ -198,14 +198,14 @@ func Calculate(log log.Logger, plugin *plugins.Plugin) (plugins.Signature, error
} }
if len(unsignedFiles) > 0 { if len(unsignedFiles) > 0 {
log.Warn("The following files were not included in the signature", "plugin", plugin.ID, "files", unsignedFiles) mlog.Warn("The following files were not included in the signature", "plugin", plugin.ID, "files", unsignedFiles)
return plugins.Signature{ return plugins.Signature{
Status: plugins.SignatureModified, Status: plugins.SignatureModified,
}, nil }, nil
} }
} }
log.Debug("Plugin signature valid", "id", plugin.ID) mlog.Debug("Plugin signature valid", "id", plugin.ID)
return plugins.Signature{ return plugins.Signature{
Status: plugins.SignatureValid, Status: plugins.SignatureValid,
Type: manifest.SignatureType, Type: manifest.SignatureType,
@ -213,18 +213,18 @@ func Calculate(log log.Logger, plugin *plugins.Plugin) (plugins.Signature, error
}, nil }, nil
} }
func verifyHash(pluginID string, path string, hash string) error { func verifyHash(mlog log.Logger, pluginID string, path string, hash string) error {
// nolint:gosec // nolint:gosec
// We can ignore the gosec G304 warning on this one because `path` is based // We can ignore the gosec G304 warning on this one because `path` is based
// on the path provided in a manifest file for a plugin and not user input. // on the path provided in a manifest file for a plugin and not user input.
f, err := os.Open(path) f, err := os.Open(path)
if err != nil { if err != nil {
log.Warn("Plugin file listed in the manifest was not found", "plugin", pluginID, "path", path) mlog.Warn("Plugin file listed in the manifest was not found", "plugin", pluginID, "path", path)
return fmt.Errorf("plugin file listed in the manifest was not found") return fmt.Errorf("plugin file listed in the manifest was not found")
} }
defer func() { defer func() {
if err := f.Close(); err != nil { if err := f.Close(); err != nil {
log.Warn("Failed to close plugin file", "path", path, "err", err) mlog.Warn("Failed to close plugin file", "path", path, "err", err)
} }
}() }()
@ -234,7 +234,7 @@ func verifyHash(pluginID string, path string, hash string) error {
} }
sum := hex.EncodeToString(h.Sum(nil)) sum := hex.EncodeToString(h.Sum(nil))
if sum != hash { if sum != hash {
log.Warn("Plugin file checksum does not match signature checksum", "plugin", pluginID, "path", path) mlog.Warn("Plugin file checksum does not match signature checksum", "plugin", pluginID, "path", path)
return fmt.Errorf("plugin file checksum does not match signature checksum") return fmt.Errorf("plugin file checksum does not match signature checksum")
} }

View File

@ -7,7 +7,6 @@ import (
"strings" "strings"
"time" "time"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/hashicorp/go-version" "github.com/hashicorp/go-version"
) )
@ -30,25 +29,25 @@ func (m *PluginManager) checkForUpdates() {
pluginSlugs := m.externalPluginIDsAsCSV() pluginSlugs := m.externalPluginIDsAsCSV()
resp, err := httpClient.Get("https://grafana.com/api/plugins/versioncheck?slugIn=" + pluginSlugs + "&grafanaVersion=" + m.cfg.BuildVersion) resp, err := httpClient.Get("https://grafana.com/api/plugins/versioncheck?slugIn=" + pluginSlugs + "&grafanaVersion=" + m.cfg.BuildVersion)
if err != nil { if err != nil {
log.Debug("Failed to get plugins repo from grafana.com", "error", err.Error()) m.log.Debug("Failed to get plugins repo from grafana.com", "error", err.Error())
return return
} }
defer func() { defer func() {
if err := resp.Body.Close(); err != nil { if err := resp.Body.Close(); err != nil {
log.Warn("Failed to close response body", "err", err) m.log.Warn("Failed to close response body", "err", err)
} }
}() }()
body, err := ioutil.ReadAll(resp.Body) body, err := ioutil.ReadAll(resp.Body)
if err != nil { if err != nil {
log.Debug("Update check failed, reading response from grafana.com", "error", err.Error()) m.log.Debug("Update check failed, reading response from grafana.com", "error", err.Error())
return return
} }
var gcomPlugins []gcomPlugin var gcomPlugins []gcomPlugin
err = json.Unmarshal(body, &gcomPlugins) err = json.Unmarshal(body, &gcomPlugins)
if err != nil { if err != nil {
log.Debug("Failed to unmarshal plugin repo, reading response from grafana.com", "error", err.Error()) m.log.Debug("Failed to unmarshal plugin repo, reading response from grafana.com", "error", err.Error())
return return
} }

View File

@ -134,7 +134,7 @@ func (ac *OSSAccessControlService) saveFixedRole(role accesscontrol.RoleDTO) {
// needs to be increased. Hence, we don't overwrite a role with a // needs to be increased. Hence, we don't overwrite a role with a
// greater version. // greater version.
if storedRole.Version >= role.Version { if storedRole.Version >= role.Version {
log.Debug("the has already been stored in a greater version, skipping registration", "role", role.Name) ac.Log.Debug("the has already been stored in a greater version, skipping registration", "role", role.Name)
return return
} }
} }
@ -150,7 +150,7 @@ func (ac *OSSAccessControlService) assignFixedRole(role accesscontrol.RoleDTO, b
if ok { if ok {
for _, assignedRole := range assignments { for _, assignedRole := range assignments {
if assignedRole == role.Name { if assignedRole == role.Name {
log.Debug("the role has already been assigned", "rolename", role.Name, "build_in_role", builtInRole) ac.Log.Debug("the role has already been assigned", "rolename", role.Name, "build_in_role", builtInRole)
alreadyAssigned = true alreadyAssigned = true
} }
} }

View File

@ -24,7 +24,7 @@ type EvalContext struct {
StartTime time.Time StartTime time.Time
EndTime time.Time EndTime time.Time
Rule *Rule Rule *Rule
log log.Logger Log log.Logger
dashboardRef *models.DashboardRef dashboardRef *models.DashboardRef
@ -46,7 +46,7 @@ func NewEvalContext(alertCtx context.Context, rule *Rule, requestValidator model
Rule: rule, Rule: rule,
Logs: make([]*ResultLogEntry, 0), Logs: make([]*ResultLogEntry, 0),
EvalMatches: make([]*EvalMatch, 0), EvalMatches: make([]*EvalMatch, 0),
log: log.New("alerting.evalContext"), Log: log.New("alerting.evalContext"),
PrevAlertState: rule.State, PrevAlertState: rule.State,
RequestValidator: requestValidator, RequestValidator: requestValidator,
} }
@ -152,7 +152,7 @@ func (c *EvalContext) GetNewState() models.AlertStateType {
func getNewStateInternal(c *EvalContext) models.AlertStateType { func getNewStateInternal(c *EvalContext) models.AlertStateType {
if c.Error != nil { if c.Error != nil {
c.log.Error("Alert Rule Result Error", c.Log.Error("Alert Rule Result Error",
"ruleId", c.Rule.ID, "ruleId", c.Rule.ID,
"name", c.Rule.Name, "name", c.Rule.Name,
"error", c.Error, "error", c.Error,
@ -169,7 +169,7 @@ func getNewStateInternal(c *EvalContext) models.AlertStateType {
} }
if c.NoDataFound { if c.NoDataFound {
c.log.Info("Alert Rule returned no data", c.Log.Info("Alert Rule returned no data",
"ruleId", c.Rule.ID, "ruleId", c.Rule.ID,
"name", c.Rule.Name, "name", c.Rule.Name,
"changing state to", c.Rule.NoDataState.ToAlertState()) "changing state to", c.Rule.NoDataState.ToAlertState())

View File

@ -239,22 +239,22 @@ func generateImageCaption(evalContext *alerting.EvalContext, ruleURL string, met
if len(ruleURL) > 0 { if len(ruleURL) > 0 {
urlLine := fmt.Sprintf("\nURL: %s", ruleURL) urlLine := fmt.Sprintf("\nURL: %s", ruleURL)
message = appendIfPossible(message, urlLine, captionLengthLimit) message = appendIfPossible(evalContext.Log, message, urlLine, captionLengthLimit)
} }
if metrics != "" { if metrics != "" {
metricsLines := fmt.Sprintf("\n\nMetrics:%s", metrics) metricsLines := fmt.Sprintf("\n\nMetrics:%s", metrics)
message = appendIfPossible(message, metricsLines, captionLengthLimit) message = appendIfPossible(evalContext.Log, message, metricsLines, captionLengthLimit)
} }
return message return message
} }
func appendIfPossible(message string, extra string, sizeLimit int) string { func appendIfPossible(tlog log.Logger, message string, extra string, sizeLimit int) string {
if len(extra)+len(message) <= sizeLimit { if len(extra)+len(message) <= sizeLimit {
return message + extra return message + extra
} }
log.Debug("Line too long for image caption.", "value", extra) tlog.Debug("Line too long for image caption.", "value", extra)
return message return message
} }

View File

@ -148,7 +148,7 @@ func (h *ContextHandler) initContextWithAnonymousUser(reqContext *models.ReqCont
org, err := h.SQLStore.GetOrgByName(h.Cfg.AnonymousOrgName) org, err := h.SQLStore.GetOrgByName(h.Cfg.AnonymousOrgName)
if err != nil { if err != nil {
log.Error("Anonymous access organization error.", "org_name", h.Cfg.AnonymousOrgName, "error", err) reqContext.Logger.Error("Anonymous access organization error.", "org_name", h.Cfg.AnonymousOrgName, "error", err)
return false return false
} }

View File

@ -739,7 +739,7 @@ func subscribeStatusToHTTPError(status backend.SubscribeStreamStatus) (int, stri
case backend.SubscribeStreamStatusPermissionDenied: case backend.SubscribeStreamStatusPermissionDenied:
return http.StatusForbidden, http.StatusText(http.StatusForbidden) return http.StatusForbidden, http.StatusText(http.StatusForbidden)
default: default:
log.Warn("unknown subscribe status", "status", status) logger.Warn("unknown subscribe status", "status", status)
return http.StatusInternalServerError, http.StatusText(http.StatusInternalServerError) return http.StatusInternalServerError, http.StatusText(http.StatusInternalServerError)
} }
} }
@ -751,7 +751,7 @@ func publishStatusToHTTPError(status backend.PublishStreamStatus) (int, string)
case backend.PublishStreamStatusPermissionDenied: case backend.PublishStreamStatusPermissionDenied:
return http.StatusForbidden, http.StatusText(http.StatusForbidden) return http.StatusForbidden, http.StatusText(http.StatusForbidden)
default: default:
log.Warn("unknown publish status", "status", status) logger.Warn("unknown publish status", "status", status)
return http.StatusInternalServerError, http.StatusText(http.StatusInternalServerError) return http.StatusInternalServerError, http.StatusText(http.StatusInternalServerError)
} }
} }

View File

@ -74,7 +74,7 @@ func sameHostOriginCheck() func(r *http.Request) bool {
return func(r *http.Request) bool { return func(r *http.Request) bool {
err := checkSameHost(r) err := checkSameHost(r)
if err != nil { if err != nil {
log.Warn("Origin check failure", "origin", r.Header.Get("origin"), "error", err) logger.Warn("Origin check failure", "origin", r.Header.Get("origin"), "error", err)
return false return false
} }
return true return true

View File

@ -56,13 +56,13 @@ func (ls *Implementation) UpsertUser(cmd *models.UpsertUserCommand) error {
return err return err
} }
if !cmd.SignupAllowed { if !cmd.SignupAllowed {
log.Warn("Not allowing login, user not found in internal user database and allow signup = false", "authmode", extUser.AuthModule) cmd.ReqContext.Logger.Warn("Not allowing login, user not found in internal user database and allow signup = false", "authmode", extUser.AuthModule)
return login.ErrInvalidCredentials return login.ErrInvalidCredentials
} }
limitReached, err := ls.QuotaService.QuotaReached(cmd.ReqContext, "user") limitReached, err := ls.QuotaService.QuotaReached(cmd.ReqContext, "user")
if err != nil { if err != nil {
log.Warn("Error getting user quota.", "error", err) cmd.ReqContext.Logger.Warn("Error getting user quota.", "error", err)
return login.ErrGettingUserQuota return login.ErrGettingUserQuota
} }
if limitReached { if limitReached {

View File

@ -11,6 +11,8 @@ import (
api "github.com/grafana/grafana/pkg/services/ngalert/api/tooling/definitions" api "github.com/grafana/grafana/pkg/services/ngalert/api/tooling/definitions"
) )
var cfglogger = log.New("notifier.config")
func PersistTemplates(cfg *api.PostableUserConfig, path string) ([]string, bool, error) { func PersistTemplates(cfg *api.PostableUserConfig, path string) ([]string, bool, error) {
if len(cfg.TemplateFiles) < 1 { if len(cfg.TemplateFiles) < 1 {
return nil, false, nil return nil, false, nil
@ -52,7 +54,7 @@ func PersistTemplates(cfg *api.PostableUserConfig, path string) ([]string, bool,
// Now that we have the list of _actual_ templates, let's remove the ones that we don't need. // Now that we have the list of _actual_ templates, let's remove the ones that we don't need.
existingFiles, err := ioutil.ReadDir(path) existingFiles, err := ioutil.ReadDir(path)
if err != nil { if err != nil {
log.Error("unable to read directory for deleting Alertmanager templates", "err", err, "path", path) cfglogger.Error("unable to read directory for deleting Alertmanager templates", "err", err, "path", path)
} }
for _, existingFile := range existingFiles { for _, existingFile := range existingFiles {
p := filepath.Join(path, existingFile.Name()) p := filepath.Join(path, existingFile.Name())
@ -61,7 +63,7 @@ func PersistTemplates(cfg *api.PostableUserConfig, path string) ([]string, bool,
templatesChanged = true templatesChanged = true
err := os.Remove(p) err := os.Remove(p)
if err != nil { if err != nil {
log.Error("unable to delete template", "err", err, "file", p) cfglogger.Error("unable to delete template", "err", err, "file", p)
} }
} }
} }

View File

@ -543,7 +543,7 @@ func (sch *schedule) ruleRoutine(grafanaCtx context.Context, key models.AlertRul
return evaluate(currentRule, attempt, ctx) return evaluate(currentRule, attempt, ctx)
}) })
if err != nil { if err != nil {
log.Error("evaluation failed after all retries", "err", err) logger.Error("evaluation failed after all retries", "err", err)
} }
}() }()
case <-stopCh: case <-stopCh:

View File

@ -11,6 +11,8 @@ type OSSSearchUserFilter struct {
filters map[string]models.FilterHandler filters map[string]models.FilterHandler
} }
var fltlog = log.New("filters")
func ProvideOSSSearchUserFilter() *OSSSearchUserFilter { func ProvideOSSSearchUserFilter() *OSSSearchUserFilter {
filters := make(map[string]models.FilterHandler) filters := make(map[string]models.FilterHandler)
filters[activeLast30Days] = NewActiveLast30DaysFilter filters[activeLast30Days] = NewActiveLast30DaysFilter
@ -26,7 +28,7 @@ func (o *OSSSearchUserFilter) GetFilter(filterName string, params []string) mode
} }
filter, err := f(params) filter, err := f(params)
if err != nil { if err != nil {
log.Warn("Cannot initialise the filter.", "filter", filterName, "error", err) fltlog.Warn("Cannot initialise the filter.", "filter", filterName, "error", err)
return nil return nil
} }
return filter return filter

View File

@ -12,13 +12,15 @@ import (
// encrypted. // encrypted.
type SecureJsonData map[string][]byte type SecureJsonData map[string][]byte
var seclogger = log.New("securejsondata")
// DecryptedValue returns single decrypted value from SecureJsonData. Similar to normal map access second return value // DecryptedValue returns single decrypted value from SecureJsonData. Similar to normal map access second return value
// is true if the key exists and false if not. // is true if the key exists and false if not.
func (s SecureJsonData) DecryptedValue(key string) (string, bool) { func (s SecureJsonData) DecryptedValue(key string) (string, bool) {
if value, ok := s[key]; ok { if value, ok := s[key]; ok {
decryptedData, err := util.Decrypt(value, setting.SecretKey) decryptedData, err := util.Decrypt(value, setting.SecretKey)
if err != nil { if err != nil {
log.Error(err.Error()) seclogger.Error(err.Error())
os.Exit(1) os.Exit(1)
} }
return string(decryptedData), true return string(decryptedData), true
@ -33,7 +35,7 @@ func (s SecureJsonData) Decrypt() map[string]string {
for key, data := range s { for key, data := range s {
decryptedData, err := util.Decrypt(data, setting.SecretKey) decryptedData, err := util.Decrypt(data, setting.SecretKey)
if err != nil { if err != nil {
log.Error(err.Error()) seclogger.Error(err.Error())
os.Exit(1) os.Exit(1)
} }
@ -48,7 +50,7 @@ func GetEncryptedJsonData(sjd map[string]string) SecureJsonData {
for key, data := range sjd { for key, data := range sjd {
encryptedData, err := util.Encrypt([]byte(data), setting.SecretKey) encryptedData, err := util.Encrypt([]byte(data), setting.SecretKey)
if err != nil { if err != nil {
log.Error(err.Error()) seclogger.Error(err.Error())
os.Exit(1) os.Exit(1)
} }

View File

@ -12,6 +12,8 @@ import (
"xorm.io/xorm" "xorm.io/xorm"
) )
var tsclogger = log.New("sqlstore.transactions")
// WithTransactionalDbSession calls the callback with a session within a transaction. // WithTransactionalDbSession calls the callback with a session within a transaction.
func (ss *SQLStore) WithTransactionalDbSession(ctx context.Context, callback dbTransactionFunc) error { func (ss *SQLStore) WithTransactionalDbSession(ctx context.Context, callback dbTransactionFunc) error {
return inTransactionWithRetryCtx(ctx, ss.engine, callback, 0) return inTransactionWithRetryCtx(ctx, ss.engine, callback, 0)
@ -67,7 +69,7 @@ func inTransactionWithRetryCtx(ctx context.Context, engine *xorm.Engine, callbac
if len(sess.events) > 0 { if len(sess.events) > 0 {
for _, e := range sess.events { for _, e := range sess.events {
if err = bus.Publish(e); err != nil { if err = bus.Publish(e); err != nil {
log.Error("Failed to publish event after commit.", "error", err) tsclogger.Error("Failed to publish event after commit.", "error", err)
} }
} }
} }

View File

@ -454,7 +454,7 @@ type CommandLineArgs struct {
Args []string Args []string
} }
func parseAppUrlAndSubUrl(section *ini.Section) (string, string, error) { func (cfg Cfg) parseAppUrlAndSubUrl(section *ini.Section) (string, string, error) {
appUrl := valueAsString(section, "root_url", "http://localhost:3000/") appUrl := valueAsString(section, "root_url", "http://localhost:3000/")
if appUrl[len(appUrl)-1] != '/' { if appUrl[len(appUrl)-1] != '/' {
@ -464,7 +464,7 @@ func parseAppUrlAndSubUrl(section *ini.Section) (string, string, error) {
// Check if has app suburl. // Check if has app suburl.
url, err := url.Parse(appUrl) url, err := url.Parse(appUrl)
if err != nil { if err != nil {
log.Error("Invalid root_url.", "url", appUrl, "error", err) cfg.Logger.Error("Invalid root_url.", "url", appUrl, "error", err)
os.Exit(1) os.Exit(1)
} }
@ -621,7 +621,7 @@ func applyCommandLineProperties(props map[string]string, file *ini.File) {
} }
} }
func getCommandLineProperties(args []string) map[string]string { func (cfg Cfg) getCommandLineProperties(args []string) map[string]string {
props := make(map[string]string) props := make(map[string]string)
for _, arg := range args { for _, arg := range args {
@ -632,7 +632,7 @@ func getCommandLineProperties(args []string) map[string]string {
trimmed := strings.TrimPrefix(arg, "cfg:") trimmed := strings.TrimPrefix(arg, "cfg:")
parts := strings.Split(trimmed, "=") parts := strings.Split(trimmed, "=")
if len(parts) != 2 { if len(parts) != 2 {
log.Error("Invalid command line argument.", "argument", arg) cfg.Logger.Error("Invalid command line argument.", "argument", arg)
os.Exit(1) os.Exit(1)
} }
@ -708,7 +708,7 @@ func (cfg *Cfg) loadConfiguration(args CommandLineArgs) (*ini.File, error) {
parsedFile.BlockMode = false parsedFile.BlockMode = false
// command line props // command line props
commandLineProps := getCommandLineProperties(args.Args) commandLineProps := cfg.getCommandLineProperties(args.Args)
// load default overrides // load default overrides
applyCommandLineDefaultProperties(commandLineProps, parsedFile) applyCommandLineDefaultProperties(commandLineProps, parsedFile)
@ -719,7 +719,7 @@ func (cfg *Cfg) loadConfiguration(args CommandLineArgs) (*ini.File, error) {
if err2 != nil { if err2 != nil {
return nil, err2 return nil, err2
} }
log.Error(err.Error()) cfg.Logger.Error(err.Error())
os.Exit(1) os.Exit(1)
} }
@ -963,7 +963,7 @@ func (cfg *Cfg) Load(args CommandLineArgs) error {
cfg.readDataSourcesSettings() cfg.readDataSourcesSettings()
if VerifyEmailEnabled && !cfg.Smtp.Enabled { if VerifyEmailEnabled && !cfg.Smtp.Enabled {
log.Warn("require_email_validation is enabled but smtp is disabled") cfg.Logger.Warn("require_email_validation is enabled but smtp is disabled")
} }
// check old key name // check old key name
@ -1358,7 +1358,7 @@ func (cfg *Cfg) readRenderingSettings(iniFile *ini.File) error {
_, err := url.Parse(cfg.RendererCallbackUrl) _, err := url.Parse(cfg.RendererCallbackUrl)
if err != nil { if err != nil {
// XXX: Should return an error? // XXX: Should return an error?
log.Error("Invalid callback_url.", "url", cfg.RendererCallbackUrl, "error", err) cfg.Logger.Error("Invalid callback_url.", "url", cfg.RendererCallbackUrl, "error", err)
os.Exit(1) os.Exit(1)
} }
} }
@ -1416,7 +1416,7 @@ func readSnapshotsSettings(cfg *Cfg, iniFile *ini.File) error {
func (cfg *Cfg) readServerSettings(iniFile *ini.File) error { func (cfg *Cfg) readServerSettings(iniFile *ini.File) error {
server := iniFile.Section("server") server := iniFile.Section("server")
var err error var err error
AppUrl, AppSubUrl, err = parseAppUrlAndSubUrl(server) AppUrl, AppSubUrl, err = cfg.parseAppUrlAndSubUrl(server)
if err != nil { if err != nil {
return err return err
} }

View File

@ -98,7 +98,8 @@ func TestLoadingSettings(t *testing.T) {
}) })
t.Run("Should get property map from command line args array", func(t *testing.T) { t.Run("Should get property map from command line args array", func(t *testing.T) {
props := getCommandLineProperties([]string{"cfg:test=value", "cfg:map.test=1"}) cfg := NewCfg()
props := cfg.getCommandLineProperties([]string{"cfg:test=value", "cfg:map.test=1"})
require.Equal(t, 2, len(props)) require.Equal(t, 2, len(props))
require.Equal(t, "value", props["test"]) require.Equal(t, "value", props["test"])
@ -313,11 +314,12 @@ func TestParseAppURLAndSubURL(t *testing.T) {
for _, tc := range testCases { for _, tc := range testCases {
f := ini.Empty() f := ini.Empty()
cfg := NewCfg()
s, err := f.NewSection("server") s, err := f.NewSection("server")
require.NoError(t, err) require.NoError(t, err)
_, err = s.NewKey("root_url", tc.rootURL) _, err = s.NewKey("root_url", tc.rootURL)
require.NoError(t, err) require.NoError(t, err)
appURL, appSubURL, err := parseAppUrlAndSubUrl(s) appURL, appSubURL, err := cfg.parseAppUrlAndSubUrl(s)
require.NoError(t, err) require.NoError(t, err)
require.Equal(t, tc.expectedAppURL, appURL) require.Equal(t, tc.expectedAppURL, appURL)
require.Equal(t, tc.expectedAppSubURL, appSubURL) require.Equal(t, tc.expectedAppSubURL, appSubURL)

View File

@ -10,7 +10,6 @@ import (
"testing" "testing"
"github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/sqlstore" "github.com/grafana/grafana/pkg/services/sqlstore"
"github.com/grafana/grafana/pkg/tests/testinfra" "github.com/grafana/grafana/pkg/tests/testinfra"
@ -110,7 +109,7 @@ func makePostRequest(t *testing.T, URL string) (int, map[string]interface{}) {
require.NoError(t, err) require.NoError(t, err)
t.Cleanup(func() { t.Cleanup(func() {
_ = resp.Body.Close() _ = resp.Body.Close()
log.Warn("Failed to close response body", "err", err) fmt.Printf("Failed to close response body err: %s", err)
}) })
b, err := ioutil.ReadAll(resp.Body) b, err := ioutil.ReadAll(resp.Body)
require.NoError(t, err) require.NoError(t, err)