[MM-31360] downgrade error logs which doesn't break the flow (#16612)

* downgrade error logs which doesn't break the flow

* reflect revivew comments
Этот коммит содержится в:
Ibrahim Serdar Acikgoz
2021-01-04 17:02:34 +03:00
коммит произвёл GitHub
родитель c1dd23a3c8
Коммит f9c0c1072f
20 изменённых файлов: 86 добавлений и 118 удалений

Просмотреть файл

@@ -212,7 +212,7 @@ func updateChannel(c *Context, w http.ResponseWriter, r *http.Request) {
if oldChannelDisplayName != channel.DisplayName {
if err := c.App.PostUpdateChannelDisplayNameMessage(c.App.Session().UserId, channel, oldChannelDisplayName, channel.DisplayName); err != nil {
mlog.Error(err.Error())
mlog.Warn("Error while posting channel display name message", mlog.Err(err))
}
}

Просмотреть файл

@@ -361,7 +361,7 @@ func getSupportedTimezones(c *Context, w http.ResponseWriter, r *http.Request) {
b, err := json.Marshal(supportedTimezones)
if err != nil {
c.Log.Warn("Unable to marshal JSON in timezones.", mlog.Err(err))
c.Logger.Warn("Unable to marshal JSON in timezones.", mlog.Err(err))
w.WriteHeader(http.StatusInternalServerError)
}

Просмотреть файл

@@ -167,7 +167,7 @@ func createUser(c *Context, w http.ResponseWriter, r *http.Request) {
if ruser != nil {
err = c.App.CheckAndSendUserLimitWarningEmails()
if err != nil {
mlog.Error(err.Error())
c.LogErrorByCode(err)
}
}
@@ -1358,7 +1358,7 @@ func updateUserActive(c *Context, w http.ResponseWriter, r *http.Request) {
if isSelfDeactive {
c.App.Srv().Go(func() {
if err = c.App.Srv().EmailService.SendDeactivateAccountEmail(user.Email, user.Locale, c.App.GetSiteURL()); err != nil {
mlog.Error(err.Error())
c.LogErrorByCode(err)
}
})
}
@@ -1823,7 +1823,7 @@ func loginCWS(c *Context, w http.ResponseWriter, r *http.Request) {
user, err := c.App.AuthenticateUserForLogin("", loginID, "", "", token, false)
if err != nil {
c.LogAuditWithUserId("", "failure - login_id="+loginID)
mlog.Error("CWS authentication error", mlog.Err(err))
c.LogErrorByCode(err)
http.Redirect(w, r, *c.App.Config().ServiceSettings.SiteURL, 302)
return
}
@@ -1831,7 +1831,7 @@ func loginCWS(c *Context, w http.ResponseWriter, r *http.Request) {
c.LogAuditWithUserId(user.Id, "authenticated")
err = c.App.DoLogin(w, r, user, "", false, false, false)
if err != nil {
mlog.Error("CWS login error", mlog.Err(err))
c.LogErrorByCode(err)
http.Redirect(w, r, *c.App.Config().ServiceSettings.SiteURL, 302)
return
}
@@ -2110,7 +2110,7 @@ func sendVerificationEmail(c *Context, w http.ResponseWriter, r *http.Request) {
if err = c.App.SendEmailVerification(user, user.Email, redirect); err != nil {
// Don't want to leak whether the email is valid or not
mlog.Error(err.Error())
c.LogErrorByCode(err)
ReturnStatusOK(w)
return
}

Просмотреть файл

@@ -46,7 +46,7 @@ func serverCmdF(command *cobra.Command, args []string) error {
customDefaults, err := loadCustomDefaults()
if err != nil {
mlog.Error("Error loading custom configuration defaults: " + err.Error())
mlog.Warn("Error loading custom configuration defaults: " + err.Error())
}
configStore, err := config.NewStore(getConfigDSN(command, config.GetEnvironment()), !disableConfigWatch, customDefaults)
@@ -79,7 +79,7 @@ func runServer(configStore *config.Store, usedPlatform bool, interruptChan chan
defer server.Shutdown()
if usedPlatform {
mlog.Error("The platform binary has been deprecated, please switch to using the mattermost binary.")
mlog.Warn("The platform binary has been deprecated, please switch to using the mattermost binary.")
}
api := api4.Init(server, server.AppOptions, server.Router)

Просмотреть файл

@@ -28,7 +28,7 @@ func prettyPrintStruct(t interface{}) string {
func structToMap(t interface{}) map[string]interface{} {
defer func() {
if r := recover(); r != nil {
mlog.Error("Panicked in structToMap. This should never happen.", mlog.Any("recover", r))
mlog.Warn("Panicked in structToMap. This should never happen.", mlog.Any("recover", r))
}
}()

Просмотреть файл

@@ -3752,7 +3752,7 @@ func (o *Config) Sanitize() {
func structToMapFilteredByTag(t interface{}, typeOfTag, filterTag string) map[string]interface{} {
defer func() {
if r := recover(); r != nil {
mlog.Error("Panicked in structToMapFilteredByTag. This should never happen.", mlog.Any("recover", r))
mlog.Warn("Panicked in structToMapFilteredByTag. This should never happen.", mlog.Any("recover", r))
}
}()

Просмотреть файл

@@ -161,7 +161,7 @@ func GenerateMiniPreviewImage(img image.Image) *[]byte {
buf := new(bytes.Buffer)
if err := jpeg.Encode(buf, preview, &jpeg.Options{Quality: 90}); err != nil {
mlog.Error("Unable to encode image as mini preview jpg", mlog.Err(err))
mlog.Info("Unable to encode image as mini preview jpg", mlog.Err(err))
return nil
}
data := buf.Bytes()

Просмотреть файл

@@ -56,7 +56,7 @@ func (job *PluginHealthCheckJob) CheckPlugin(id string) {
return
}
mlog.Error("Health check failed for plugin", mlog.String("id", id), mlog.Err(err))
mlog.Warn("Health check failed for plugin", mlog.String("id", id), mlog.Err(err))
timestamps := job.getStoredTimestamps(id)
timestamps = append(timestamps, time.Now())

Просмотреть файл

@@ -81,8 +81,7 @@ func newAWSMarketplaceMeteringService() (*marketplacemetering.MarketplaceMeterin
_, err = creds.Get()
if err != nil {
mlog.Error("session is invalid", mlog.String("error", err.Error()))
return nil, errors.New("cannot obtain credentials")
return nil, errors.Wrap(err, "cannot obtain credentials")
}
return marketplacemetering.New(session.Must(session.NewSession(&aws.Config{
@@ -102,11 +101,11 @@ func (awsm *AwsMeter) GetUserCategoryUsage(dimensions []string, startTime time.T
case model.AWS_METERING_DIMENSION_USAGE_HRS:
userCount, err = awsm.store.User().AnalyticsActiveCountForPeriod(model.GetMillisForTime(startTime), model.GetMillisForTime(endTime), model.UserCountOptions{})
if err != nil {
mlog.Error("Failed to obtain usage data", mlog.String("dimension", dimension), mlog.String("start", startTime.String()), mlog.Int64("count", userCount), mlog.Err(err))
mlog.Warn("Failed to obtain usage data", mlog.String("dimension", dimension), mlog.String("start", startTime.String()), mlog.Int64("count", userCount), mlog.Err(err))
continue
}
default:
mlog.Error("Dimension does not exist!", mlog.String("dimension", dimension))
mlog.Debug("Dimension does not exist!", mlog.String("dimension", dimension))
continue
}

Просмотреть файл

@@ -47,7 +47,7 @@ func makeLocalBackend(proxy *ImageProxy) *LocalBackend {
if proxy.Logger != nil {
logger, err := proxy.Logger.StdLogAt(mlog.LevelDebug, mlog.String("image_proxy", "local"))
if err != nil {
mlog.Error("Failed to initialize logger for image proxy", mlog.Err(err))
mlog.Warn("Failed to initialize logger for image proxy", mlog.Err(err))
}
impl.Logger = logger
@@ -55,7 +55,7 @@ func makeLocalBackend(proxy *ImageProxy) *LocalBackend {
baseURL, err := url.Parse(*proxy.ConfigService.Config().ServiceSettings.SiteURL)
if err != nil {
mlog.Error("Failed to set base URL for image proxy. Relative image links may not work.", mlog.Err(err))
mlog.Warn("Failed to set base URL for image proxy. Relative image links may not work.", mlog.Err(err))
} else {
impl.DefaultBaseURL = baseURL
}
@@ -92,7 +92,7 @@ func (backend *LocalBackend) GetImage(w http.ResponseWriter, r *http.Request, im
req, err := http.NewRequest(http.MethodGet, "/"+imageURL, nil)
if err != nil {
// http.NewRequest should only return an error on an invalid URL
mlog.Error("Failed to create request for proxied image", mlog.String("url", imageURL), mlog.Err(err))
mlog.Debug("Failed to create request for proxied image", mlog.String("url", imageURL), mlog.Err(err))
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte{})
@@ -101,7 +101,7 @@ func (backend *LocalBackend) GetImage(w http.ResponseWriter, r *http.Request, im
u, err := url.Parse(imageURL)
if err != nil {
mlog.Error("Failed to parse URL for proxied image", mlog.String("url", imageURL), mlog.Err(err))
mlog.Debug("Failed to parse URL for proxied image", mlog.String("url", imageURL), mlog.Err(err))
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte{})
return

Просмотреть файл

@@ -318,7 +318,7 @@ func (worker *BleveIndexerWorker) IndexPostsBatch(progress IndexingProgress) (In
progress.DonePosts = true
progress.LastEntityTime = progress.StartAtTime
} else if progress.LastEntityTime == newLastMessageTime && len(posts) == BatchSize {
mlog.Error("More posts with the same CreateAt time were detected than the permitted batch size. Aborting indexing job.", mlog.Int64("CreateAt", newLastMessageTime), mlog.Int("Batch Size", BatchSize))
mlog.Warn("More posts with the same CreateAt time were detected than the permitted batch size. Aborting indexing job.", mlog.Int64("CreateAt", newLastMessageTime), mlog.Int("Batch Size", BatchSize))
progress.DonePosts = true
progress.LastEntityTime = progress.StartAtTime
} else {
@@ -396,7 +396,7 @@ func (worker *BleveIndexerWorker) IndexChannelsBatch(progress IndexingProgress)
progress.DoneChannels = true
progress.LastEntityTime = progress.StartAtTime
} else if progress.LastEntityTime == newLastChannelTime && len(channels) == BatchSize {
mlog.Error("More channels with the same CreateAt time were detected than the permitted batch size. Aborting indexing job.", mlog.Int64("CreateAt", newLastChannelTime), mlog.Int("Batch Size", BatchSize))
mlog.Warn("More channels with the same CreateAt time were detected than the permitted batch size. Aborting indexing job.", mlog.Int64("CreateAt", newLastChannelTime), mlog.Int("Batch Size", BatchSize))
progress.DoneChannels = true
progress.LastEntityTime = progress.StartAtTime
} else {
@@ -474,7 +474,7 @@ func (worker *BleveIndexerWorker) IndexUsersBatch(progress IndexingProgress) (In
progress.DoneUsers = true
progress.LastEntityTime = progress.StartAtTime
} else if progress.LastEntityTime == newLastUserTime && len(users) == BatchSize {
mlog.Error("More users with the same CreateAt time were detected than the permitted batch size. Aborting indexing job.", mlog.Int64("CreateAt", newLastUserTime), mlog.Int("Batch Size", BatchSize))
mlog.Warn("More users with the same CreateAt time were detected than the permitted batch size. Aborting indexing job.", mlog.Int64("CreateAt", newLastUserTime), mlog.Int("Batch Size", BatchSize))
progress.DoneUsers = true
progress.LastEntityTime = progress.StartAtTime
} else {

Просмотреть файл

@@ -686,16 +686,16 @@ func (si *SlackImporter) oldImportUser(team *model.Team, user *model.User) *mode
ruser, nErr := si.store.User().Save(user)
if nErr != nil {
mlog.Error("Error saving user.", mlog.Err(nErr))
mlog.Debug("Error saving user.", mlog.Err(nErr))
return nil
}
if _, err := si.store.User().VerifyEmail(ruser.Id, ruser.Email); err != nil {
mlog.Error("Failed to set email verified.", mlog.Err(err))
mlog.Warn("Failed to set email verified.", mlog.Err(err))
}
if err := si.actions.JoinUserToTeam(team, user, ""); err != nil {
mlog.Error("Failed to join team when importing.", mlog.Err(err))
mlog.Warn("Failed to join team when importing.", mlog.Err(err))
}
return ruser

Просмотреть файл

@@ -263,7 +263,7 @@ func (ts *TelemetryService) trackActivity() {
teamCount, err := ts.dbStore.Team().AnalyticsTeamCount(false)
if err != nil {
mlog.Error(err.Error())
mlog.Info("Could not get team count", mlog.Err(err))
}
if ucc, err := ts.dbStore.Channel().AnalyticsTypeCount("", "O"); err == nil {
@@ -1075,42 +1075,42 @@ func (ts *TelemetryService) trackElasticsearch() {
func (ts *TelemetryService) trackGroups() {
groupCount, err := ts.dbStore.Group().GroupCount()
if err != nil {
mlog.Error(err.Error())
mlog.Debug("Could not get group_count", mlog.Err(err))
}
groupTeamCount, err := ts.dbStore.Group().GroupTeamCount()
if err != nil {
mlog.Error(err.Error())
mlog.Debug("Could not get group_team_count", mlog.Err(err))
}
groupChannelCount, err := ts.dbStore.Group().GroupChannelCount()
if err != nil {
mlog.Error(err.Error())
mlog.Debug("Could not get group_channel_count", mlog.Err(err))
}
groupSyncedTeamCount, nErr := ts.dbStore.Team().GroupSyncedTeamCount()
if nErr != nil {
mlog.Error(nErr.Error())
mlog.Debug("Could not get group_synced_team_count", mlog.Err(nErr))
}
groupSyncedChannelCount, nErr := ts.dbStore.Channel().GroupSyncedChannelCount()
if nErr != nil {
mlog.Error(nErr.Error())
mlog.Debug("Could not get group_synced_channel_count", mlog.Err(nErr))
}
groupMemberCount, err := ts.dbStore.Group().GroupMemberCount()
if err != nil {
mlog.Error(err.Error())
mlog.Debug("Could not get group_member_count", mlog.Err(err))
}
distinctGroupMemberCount, err := ts.dbStore.Group().DistinctGroupMemberCount()
if err != nil {
mlog.Error(err.Error())
mlog.Debug("Could not get distinct_group_member_count", mlog.Err(err))
}
groupCountWithAllowReference, err := ts.dbStore.Group().GroupCountWithAllowReference()
if err != nil {
mlog.Error(err.Error())
mlog.Debug("Could not get group_count_with_allow_reference", mlog.Err(err))
}
ts.sendTelemetry(TrackGroups, map[string]interface{}{
@@ -1128,44 +1128,44 @@ func (ts *TelemetryService) trackGroups() {
func (ts *TelemetryService) trackChannelModeration() {
channelSchemeCount, err := ts.dbStore.Scheme().CountByScope(model.SCHEME_SCOPE_CHANNEL)
if err != nil {
mlog.Error(err.Error())
mlog.Debug("Could not get channel_scheme_count", mlog.Err(err))
}
createPostUser, err := ts.dbStore.Scheme().CountWithoutPermission(model.SCHEME_SCOPE_CHANNEL, model.PERMISSION_CREATE_POST.Id, model.RoleScopeChannel, model.RoleTypeUser)
if err != nil {
mlog.Error(err.Error())
mlog.Debug("Could not get create_post_user_disabled_count", mlog.Err(err))
}
createPostGuest, err := ts.dbStore.Scheme().CountWithoutPermission(model.SCHEME_SCOPE_CHANNEL, model.PERMISSION_CREATE_POST.Id, model.RoleScopeChannel, model.RoleTypeGuest)
if err != nil {
mlog.Error(err.Error())
mlog.Debug("Could not get create_post_guest_disabled_count", mlog.Err(err))
}
// only need to track one of 'add_reaction' or 'remove_reaction` because they're both toggled together by the channel moderation feature
postReactionsUser, err := ts.dbStore.Scheme().CountWithoutPermission(model.SCHEME_SCOPE_CHANNEL, model.PERMISSION_ADD_REACTION.Id, model.RoleScopeChannel, model.RoleTypeUser)
if err != nil {
mlog.Error(err.Error())
mlog.Debug("Could not get post_reactions_user_disabled_count", mlog.Err(err))
}
postReactionsGuest, err := ts.dbStore.Scheme().CountWithoutPermission(model.SCHEME_SCOPE_CHANNEL, model.PERMISSION_ADD_REACTION.Id, model.RoleScopeChannel, model.RoleTypeGuest)
if err != nil {
mlog.Error(err.Error())
mlog.Debug("Could not get post_reactions_guest_disabled_count", mlog.Err(err))
}
// only need to track one of 'manage_public_channel_members' or 'manage_private_channel_members` because they're both toggled together by the channel moderation feature
manageMembersUser, err := ts.dbStore.Scheme().CountWithoutPermission(model.SCHEME_SCOPE_CHANNEL, model.PERMISSION_MANAGE_PUBLIC_CHANNEL_MEMBERS.Id, model.RoleScopeChannel, model.RoleTypeUser)
if err != nil {
mlog.Error(err.Error())
mlog.Debug("Could not get manage_members_user_disabled_count", mlog.Err(err))
}
useChannelMentionsUser, err := ts.dbStore.Scheme().CountWithoutPermission(model.SCHEME_SCOPE_CHANNEL, model.PERMISSION_USE_CHANNEL_MENTIONS.Id, model.RoleScopeChannel, model.RoleTypeUser)
if err != nil {
mlog.Error(err.Error())
mlog.Debug("Could not get use_channel_mentions_user_disabled_count", mlog.Err(err))
}
useChannelMentionsGuest, err := ts.dbStore.Scheme().CountWithoutPermission(model.SCHEME_SCOPE_CHANNEL, model.PERMISSION_USE_CHANNEL_MENTIONS.Id, model.RoleScopeChannel, model.RoleTypeGuest)
if err != nil {
mlog.Error(err.Error())
mlog.Debug("Could not get use_channel_mentions_guest_disabled_count", mlog.Err(err))
}
ts.sendTelemetry(TrackChannelModeration, map[string]interface{}{
@@ -1319,7 +1319,7 @@ func (ts *TelemetryService) trackPluginConfig(cfg *model.Config, marketplaceURL
pluginsEnvironment := ts.srv.GetPluginsEnvironment()
if pluginsEnvironment != nil {
if plugins, appErr := pluginsEnvironment.Available(); appErr != nil {
mlog.Error("Unable to add plugin versions to telemetry", mlog.Err(appErr))
mlog.Warn("Unable to add plugin versions to telemetry", mlog.Err(appErr))
} else {
// If marketplace request failed, use predefined list
if marketplacePlugins == nil {

Просмотреть файл

@@ -81,25 +81,25 @@ func getCurrentVersionTgzUrl() string {
func verifySignature(filename string, sigfilename string, publicKey string) error {
keyring, err := openpgp.ReadArmoredKeyRing(bytes.NewReader([]byte(publicKey)))
if err != nil {
mlog.Error("Unable to load the public key to verify the file signature", mlog.Err(err))
mlog.Debug("Unable to load the public key to verify the file signature", mlog.Err(err))
return NewInvalidSignature()
}
mattermost_tar, err := os.Open(filename)
if err != nil {
mlog.Error("Unable to open the Mattermost .tar file to verify the file signature", mlog.Err(err))
mlog.Debug("Unable to open the Mattermost .tar file to verify the file signature", mlog.Err(err))
return NewInvalidSignature()
}
signature, err := os.Open(sigfilename)
if err != nil {
mlog.Error("Unable to open the Mattermost .sig file verify the file signature", mlog.Err(err))
mlog.Debug("Unable to open the Mattermost .sig file verify the file signature", mlog.Err(err))
return NewInvalidSignature()
}
_, err = openpgp.CheckDetachedSignature(keyring, mattermost_tar, signature)
if err != nil {
mlog.Error("Unable to verify the Mattermost file signature", mlog.Err(err))
mlog.Debug("Unable to verify the Mattermost file signature", mlog.Err(err))
return NewInvalidSignature()
}
return nil
@@ -157,8 +157,7 @@ func canIUpgrade() error {
func CanIUpgradeToE0() error {
if err := canIUpgrade(); err != nil {
mlog.Error("Unable to upgrade from TE to E0", mlog.Err(err))
return err
return errors.Wrap(err, "unable to upgrade from TE to E0")
}
if model.BuildEnterpriseReady == "true" {
mlog.Warn("Unable to upgrade from TE to E0. The server is already running E0.")
@@ -252,12 +251,14 @@ func download(url string, limit int64) (string, error) {
func getFilePermissionsOrDefault(filename string, def os.FileMode) os.FileMode {
file, err := os.Open(filename)
if err != nil {
mlog.Error("Unable to get the file permissions", mlog.String("filename", filename), mlog.Err(err))
mlog.Warn("Unable to get the file permissions", mlog.String("filename", filename), mlog.Err(err))
return def
}
defer file.Close()
fileStats, err := file.Stat()
if err != nil {
mlog.Error("Unable to get the file permissions", mlog.String("filename", filename), mlog.Err(err))
mlog.Warn("Unable to get the file permissions", mlog.String("filename", filename), mlog.Err(err))
return def
}
return fileStats.Mode()

Просмотреть файл

@@ -74,7 +74,7 @@ func InitTranslationsWithDir(dir string) error {
func GetTranslationsBySystemLocale() (i18n.TranslateFunc, error) {
locale := *settings.DefaultServerLocale
if _, ok := locales[locale]; !ok {
mlog.Error("Failed to load system translations for", mlog.String("locale", locale), mlog.String("attempting to fall back to default locale", model.DEFAULT_LOCALE))
mlog.Warn("Failed to load system translations for", mlog.String("locale", locale), mlog.String("attempting to fall back to default locale", model.DEFAULT_LOCALE))
locale = model.DEFAULT_LOCALE
}

Просмотреть файл

@@ -18,7 +18,7 @@ import (
type Context struct {
App app.AppIface
Log *mlog.Logger
Logger *mlog.Logger
Params *Params
Err *model.AppError
siteURLHeader string
@@ -68,7 +68,7 @@ func (c *Context) LogAudit(extraInfo string) {
audit := &model.Audit{UserId: c.App.Session().UserId, IpAddress: c.App.IpAddress(), Action: c.App.Path(), ExtraInfo: extraInfo, SessionId: c.App.Session().Id}
if err := c.App.Srv().Store.Audit().Save(audit); err != nil {
appErr := model.NewAppError("LogAudit", "app.audit.save.saving.app_error", nil, err.Error(), http.StatusInternalServerError)
c.LogError(appErr)
c.LogErrorByCode(appErr)
}
}
@@ -81,42 +81,23 @@ func (c *Context) LogAuditWithUserId(userId, extraInfo string) {
audit := &model.Audit{UserId: userId, IpAddress: c.App.IpAddress(), Action: c.App.Path(), ExtraInfo: extraInfo, SessionId: c.App.Session().Id}
if err := c.App.Srv().Store.Audit().Save(audit); err != nil {
appErr := model.NewAppError("LogAuditWithUserId", "app.audit.save.saving.app_error", nil, err.Error(), http.StatusInternalServerError)
c.LogError(appErr)
c.LogErrorByCode(appErr)
}
}
func (c *Context) LogError(err *model.AppError) {
// Filter out 404s, endless reconnects and browser compatibility errors
if err.StatusCode == http.StatusNotFound ||
(c.App.Path() == "/api/v3/users/websocket" && err.StatusCode == http.StatusUnauthorized) ||
err.Id == "web.check_browser_compatibility.app_error" {
c.LogDebug(err)
} else {
c.Log.Error(
err.SystemMessage(utils.TDefault),
mlog.String("err_where", err.Where),
mlog.Int("http_code", err.StatusCode),
mlog.String("err_details", err.DetailedError),
)
func (c *Context) LogErrorByCode(err *model.AppError) {
code := err.StatusCode
var level mlog.LogLevel
switch {
case (code >= http.StatusBadRequest && code < http.StatusInternalServerError) ||
err.Id == "web.check_browser_compatibility.app_error":
level = mlog.LvlDebug
case code == http.StatusNotImplemented:
level = mlog.LvlInfo
default:
level = mlog.LvlError
}
}
func (c *Context) LogInfo(err *model.AppError) {
// Filter out 401s
if err.StatusCode == http.StatusUnauthorized {
c.LogDebug(err)
} else {
c.Log.Info(
err.SystemMessage(utils.TDefault),
mlog.String("err_where", err.Where),
mlog.Int("http_code", err.StatusCode),
mlog.String("err_details", err.DetailedError),
)
}
}
func (c *Context) LogDebug(err *model.AppError) {
c.Log.Debug(
c.Logger.Log(level,
err.SystemMessage(utils.TDefault),
mlog.String("err_where", err.Where),
mlog.Int("http_code", err.StatusCode),

Просмотреть файл

@@ -115,7 +115,7 @@ func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
c.App.SetAcceptLanguage(r.Header.Get("Accept-Language"))
c.App.SetPath(r.URL.Path)
c.Params = ParamsFromRequest(r)
c.Log = c.App.Log()
c.Logger = c.App.Log()
if *c.App.Config().ServiceSettings.EnableOpenTracing {
span, ctx := tracing.StartRootSpanByContext(context.Background(), "web:ServeHTTP")
@@ -191,7 +191,7 @@ func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if token != "" && tokenLocation != app.TokenLocationCloudHeader {
session, err := c.App.GetSession(token)
if err != nil {
c.Log.Info("Invalid session", mlog.Err(err))
c.Logger.Info("Invalid session", mlog.Err(err))
if err.StatusCode == http.StatusInternalServerError {
c.Err = err
} else if h.RequireSession {
@@ -214,14 +214,14 @@ func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// Check to see if this provided token matches our CWS Token
session, err := c.App.GetCloudSession(token)
if err != nil {
c.Log.Warn("Invalid CWS token", mlog.Err(err))
c.Logger.Warn("Invalid CWS token", mlog.Err(err))
c.Err = err
} else {
c.App.SetSession(session)
}
}
c.Log = c.App.Log().With(
c.Logger = c.App.Log().With(
mlog.String("path", c.App.Path()),
mlog.String("request_id", c.App.RequestId()),
mlog.String("ip_addr", c.App.IpAddress()),
@@ -264,20 +264,7 @@ func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if c.Err != nil {
c.Err.Translate(c.App.T)
c.Err.RequestId = c.App.RequestId()
if c.Err.Id == "api.context.session_expired.app_error" {
c.LogInfo(c.Err)
} else {
code := c.Err.StatusCode
switch {
case code >= http.StatusBadRequest && code < http.StatusInternalServerError:
c.LogDebug(c.Err)
case code == http.StatusNotImplemented:
c.LogInfo(c.Err)
default:
c.LogError(c.Err)
}
}
c.LogErrorByCode(c.Err)
c.Err.Where = r.URL.Path
@@ -350,9 +337,9 @@ func (h *Handler) checkCSRFToken(c *Context, r *http.Request, token string, toke
}
if *c.App.Config().ServiceSettings.ExperimentalStrictCSRFEnforcement {
c.Log.Warn(csrfErrorMessage, fields...)
c.Logger.Warn(csrfErrorMessage, fields...)
} else {
c.Log.Debug(csrfErrorMessage, fields...)
c.Logger.Debug(csrfErrorMessage, fields...)
csrfCheckPassed = true
}
}

Просмотреть файл

@@ -451,8 +451,8 @@ func TestCheckCSRFToken(t *testing.T) {
tokenLocation := app.TokenLocationCookie
c := &Context{
App: th.App,
Log: th.App.Log(),
App: th.App,
Logger: th.App.Log(),
}
r, _ := http.NewRequest(http.MethodPost, "", nil)
r.Header.Set(model.HEADER_REQUESTED_WITH, model.HEADER_REQUESTED_WITH_XML)
@@ -500,8 +500,8 @@ func TestCheckCSRFToken(t *testing.T) {
tokenLocation := app.TokenLocationCookie
c := &Context{
App: th.App,
Log: th.App.Log(),
App: th.App,
Logger: th.App.Log(),
}
r, _ := http.NewRequest(http.MethodPost, "", nil)
r.Header.Set(model.HEADER_REQUESTED_WITH, model.HEADER_REQUESTED_WITH_XML)

Просмотреть файл

@@ -280,7 +280,7 @@ func completeOAuth(c *Context, w http.ResponseWriter, r *http.Request) {
if err != nil {
err.Translate(c.App.T)
mlog.Error(err.Error())
c.LogErrorByCode(err)
if action == model.OAUTH_ACTION_MOBILE {
w.Write([]byte(err.ToJson()))
} else {
@@ -292,7 +292,7 @@ func completeOAuth(c *Context, w http.ResponseWriter, r *http.Request) {
user, err := c.App.CompleteOAuth(service, body, teamId, props, tokenUser)
if err != nil {
err.Translate(c.App.T)
mlog.Error(err.Error())
c.LogErrorByCode(err)
if action == model.OAUTH_ACTION_MOBILE {
w.Write([]byte(err.ToJson()))
} else {
@@ -309,7 +309,7 @@ func completeOAuth(c *Context, w http.ResponseWriter, r *http.Request) {
} else {
isMobile, parseErr := strconv.ParseBool(props[model.USER_AUTH_SERVICE_IS_MOBILE])
if parseErr != nil {
mlog.Error("Error parsing boolean property from props", mlog.Err(parseErr))
mlog.Debug("Error parsing boolean property from props", mlog.Err(parseErr))
}
err = c.App.DoLogin(w, r, user, "", isMobile, false, false)
if err != nil {

Просмотреть файл

@@ -119,7 +119,7 @@ func completeSaml(c *Context, w http.ResponseWriter, r *http.Request) {
case model.OAUTH_ACTION_SIGNUP:
if teamId := relayProps["team_id"]; teamId != "" {
if err = c.App.AddUserToTeamByTeamId(teamId, user); err != nil {
mlog.Error(err.Error())
c.LogErrorByCode(err)
break
}
c.App.AddDirectChannels(teamId, user)
@@ -135,7 +135,7 @@ func completeSaml(c *Context, w http.ResponseWriter, r *http.Request) {
c.LogAuditWithUserId(user.Id, "Revoked all sessions for user")
c.App.Srv().Go(func() {
if err = c.App.Srv().EmailService.SendSignInChangeEmail(user.Email, strings.Title(model.USER_AUTH_SERVICE_SAML)+" SSO", user.Locale, c.App.GetSiteURL()); err != nil {
mlog.Error(err.Error())
c.LogErrorByCode(err)
}
})
}
@@ -145,7 +145,7 @@ func completeSaml(c *Context, w http.ResponseWriter, r *http.Request) {
isMobile, parseErr := strconv.ParseBool(relayProps[model.USER_AUTH_SERVICE_IS_MOBILE])
if parseErr != nil {
mlog.Error("Error parsing boolean property from relay props", mlog.Err(parseErr))
mlog.Warn("Error parsing boolean property from relay props", mlog.Err(parseErr))
}
err = c.App.DoLogin(w, r, user, "", isMobile, false, true)
if err != nil {