* move logger under platform
Этот коммит содержится в:
Ibrahim Serdar Acikgoz
2022-08-24 10:10:56 +03:00
коммит произвёл GitHub
родитель 6a6e05073e
Коммит efbcb0a35a
36 изменённых файлов: 327 добавлений и 297 удалений

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

@@ -67,7 +67,7 @@ func (s *Server) GetLogsSkipSend(page, perPage int) ([]string, *model.AppError)
var lines []string
if *s.platform.Config().LogSettings.EnableFile {
s.Log.Flush()
s.Log().Flush()
logFile := config.GetLogFileLocation(*s.platform.Config().LogSettings.FileLocation)
file, err := os.Open(logFile)
if err != nil {

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

@@ -89,10 +89,10 @@ func (a *App) Srv() *Server {
return a.ch.srv
}
func (a *App) Log() *mlog.Logger {
return a.ch.srv.Log
return a.ch.srv.Log()
}
func (a *App) NotificationsLog() *mlog.Logger {
return a.ch.srv.NotificationsLog
return a.ch.srv.NotificationsLog()
}
func (a *App) AccountMigration() einterfaces.AccountMigrationInterface {

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

@@ -29,21 +29,21 @@ type channelsWrapper struct {
}
func (s *channelsWrapper) GetDirectChannel(userID1, userID2 string) (*model.Channel, *model.AppError) {
return s.srv.getDirectChannel(request.EmptyContext(s.srv.GetLogger()), userID1, userID2)
return s.srv.getDirectChannel(request.EmptyContext(s.srv.Log()), userID1, userID2)
}
// GetChannelByID gets a Channel by its ID.
func (s *channelsWrapper) GetChannelByID(channelID string) (*model.Channel, *model.AppError) {
return s.srv.getChannel(request.EmptyContext(s.srv.GetLogger()), channelID)
return s.srv.getChannel(request.EmptyContext(s.srv.Log()), channelID)
}
// GetChannelMember gets a channel member by userID.
func (s *channelsWrapper) GetChannelMember(channelID string, userID string) (*model.ChannelMember, *model.AppError) {
return s.srv.getChannelMember(request.EmptyContext(s.srv.GetLogger()), channelID, userID)
return s.srv.getChannelMember(request.EmptyContext(s.srv.Log()), channelID, userID)
}
func (s *channelsWrapper) GetChannelsForTeamForUser(teamID string, userID string, opts *model.ChannelSearchOpts) (model.ChannelList, *model.AppError) {
return s.srv.getChannelsForTeamForUser(request.EmptyContext(s.srv.GetLogger()), teamID, userID, opts)
return s.srv.getChannelsForTeamForUser(request.EmptyContext(s.srv.Log()), teamID, userID, opts)
}
// Ensure the wrapper implements the product service.

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

@@ -101,7 +101,7 @@ func init() {
func NewChannels(s *Server, services map[ServiceKey]any) (*Channels, error) {
ch := &Channels{
srv: s,
imageProxy: imageproxy.MakeImageProxy(s.platform, s.httpService, s.Log),
imageProxy: imageproxy.MakeImageProxy(s.platform, s.httpService, s.Log()),
uploadLockMap: map[string]bool{},
}
@@ -167,12 +167,12 @@ func NewChannels(s *Server, services map[ServiceKey]any) (*Channels, error) {
if samlInterfaceNew != nil {
ch.Saml = samlInterfaceNew(New(ServerConnector(ch)))
if err := ch.Saml.ConfigureSP(); err != nil {
s.Log.Error("An error occurred while configuring SAML Service Provider", mlog.Err(err))
s.Log().Error("An error occurred while configuring SAML Service Provider", mlog.Err(err))
}
ch.AddConfigListener(func(_, _ *model.Config) {
if err := ch.Saml.ConfigureSP(); err != nil {
s.Log.Error("An error occurred while configuring SAML Service Provider", mlog.Err(err))
s.Log().Error("An error occurred while configuring SAML Service Provider", mlog.Err(err))
}
})
}
@@ -235,7 +235,7 @@ func NewChannels(s *Server, services map[ServiceKey]any) (*Channels, error) {
func (ch *Channels) Start() error {
// Start plugins
ctx := request.EmptyContext(ch.srv.GetLogger())
ctx := request.EmptyContext(ch.srv.Log())
ch.initPlugins(ctx, *ch.cfgSvc.Config().PluginSettings.Directory, *ch.cfgSvc.Config().PluginSettings.ClientDirectory)
ch.AddConfigListener(func(prevCfg, cfg *model.Config) {
@@ -243,7 +243,7 @@ func (ch *Channels) Start() error {
// to ensure we don't re-init plugins unnecessarily.
diffs, err := config.Diff(prevCfg, cfg)
if err != nil {
ch.srv.Log.Warn("Error in comparing configs", mlog.Err(err))
ch.srv.Log().Warn("Error in comparing configs", mlog.Err(err))
return
}

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

@@ -84,7 +84,7 @@ func (s *Server) RemoveClusterLeaderChangedListener(id string) {
}
func (s *Server) InvokeClusterLeaderChangedListeners() {
s.Log.Info("Cluster leader changed. Invoking ClusterLeaderChanged listeners.")
s.Log().Info("Cluster leader changed. Invoking ClusterLeaderChanged listeners.")
// This needs to be run in a separate goroutine otherwise a recursive lock happens
// because the listener function eventually ends up calling .IsLeader().
// Fixing this would require the changed event to pass the leader directly, but that

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

@@ -594,7 +594,7 @@ func (a *App) OpenInteractiveDialog(request model.OpenDialogRequest) *model.AppE
jsonRequest, err := json.Marshal(request)
if err != nil {
a.ch.srv.GetLogger().Warn("Error encoding request", mlog.Err(err))
a.ch.srv.Log().Warn("Error encoding request", mlog.Err(err))
}
message := model.NewWebSocketEvent(model.WebsocketEventOpenDialog, "", "", userID, nil)

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

@@ -366,7 +366,7 @@ func (s *Server) RequestTrialLicense(trialRequest *model.TrialLicenseRequest) *m
var licenseResponse map[string]string
err = json.NewDecoder(resp.Body).Decode(&licenseResponse)
if err != nil {
s.GetLogger().Warn("Error decoding license response", mlog.Err(err))
s.Log().Warn("Error decoding license response", mlog.Err(err))
}
if _, ok := licenseResponse["license"]; !ok {

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

@@ -55,7 +55,6 @@ func Config(dsn string, readOnly bool, configDefaults *model.Config) Option {
platformCfg := platform.ServiceConfig{
ConfigStore: configStore,
Logger: s.Log,
StartMetrics: s.startMetrics,
Cluster: s.Cluster,
}
@@ -78,7 +77,6 @@ func ConfigStore(configStore *config.Store) Option {
return func(s *Server) error {
platformCfg := platform.ServiceConfig{
ConfigStore: configStore,
Logger: s.Log,
StartMetrics: s.startMetrics,
Cluster: s.Cluster,
}
@@ -127,9 +125,15 @@ func StartSearchEngine(s *Server) error {
return nil
}
// SetLogger requires platform service to be initialized before calling.
// If not, logger should be set after platform service are initialized.
func SetLogger(logger *mlog.Logger) Option {
return func(s *Server) error {
s.Log = logger
if s.platform == nil {
return errors.New("platform service is not initialized")
}
s.platform.SetLogger(logger)
return nil
}
}

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

@@ -21,7 +21,6 @@ import (
type ServiceConfig struct {
// Mandatory fields
ConfigStore *config.Store
Logger *mlog.Logger
StartMetrics bool // TODO: find an elegant way to start/stop metrics server by default
// Optional fields
Metrics einterfaces.MetricsInterface
@@ -34,16 +33,6 @@ func (c *ServiceConfig) validate() error {
return errors.New("ConfigStore is required")
}
if c.Logger == nil {
var err error
// If Logger is not set, use a default logger temporarily.
// this should be removed once the logger is properly configured with the service config.
// MM-45841
c.Logger, err = mlog.NewLogger()
if err != nil {
return err
}
}
return nil
}

117
app/platform/log.go Обычный файл
Просмотреть файл

@@ -0,0 +1,117 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
package platform
import (
"context"
"errors"
"fmt"
"time"
"github.com/mattermost/mattermost-server/v6/config"
"github.com/mattermost/mattermost-server/v6/model"
"github.com/mattermost/mattermost-server/v6/shared/mlog"
)
func (ps *PlatformService) ReconfigureLogger() error {
return ps.initLogging()
}
// initLogging initializes and configures the logger(s). This may be called more than once.
func (ps *PlatformService) initLogging() error {
// create the app logger if needed
if ps.logger == nil {
var err error
ps.logger, err = mlog.NewLogger()
if err != nil {
return err
}
logCfg, err := config.MloggerConfigFromLoggerConfig(&ps.Config().LogSettings, nil, config.GetLogFileLocation)
if err != nil {
return err
}
if errCfg := ps.logger.ConfigureTargets(logCfg, nil); errCfg != nil {
return fmt.Errorf("failed to configure test logger: %w", errCfg)
}
}
// create notification logger if needed
if ps.notificationsLogger == nil {
l, err := mlog.NewLogger()
if err != nil {
return err
}
ps.notificationsLogger = l.With(mlog.String("logSource", "notifications"))
}
if err := ps.ConfigureLogger("logging", ps.logger, &ps.Config().LogSettings, config.GetLogFileLocation); err != nil {
// if the config is locked then a unit test has already configured and locked the logger; not an error.
if !errors.Is(err, mlog.ErrConfigurationLock) {
// revert to default logger if the config is invalid
mlog.InitGlobalLogger(nil)
return err
}
}
// Redirect default Go logger to app logger.
ps.logger.RedirectStdLog(mlog.LvlStdLog)
// Use the app logger as the global logger (eventually remove all instances of global logging).
mlog.InitGlobalLogger(ps.logger)
notificationLogSettings := config.GetLogSettingsFromNotificationsLogSettings(&ps.Config().NotificationLogSettings)
if err := ps.ConfigureLogger("notification logging", ps.notificationsLogger, notificationLogSettings, config.GetNotificationsLogFileLocation); err != nil {
if !errors.Is(err, mlog.ErrConfigurationLock) {
mlog.Error("Error configuring notification logger", mlog.Err(err))
return err
}
}
return nil
}
func (ps *PlatformService) Logger() *mlog.Logger {
return ps.logger
}
func (ps *PlatformService) NotificationsLogger() *mlog.Logger {
return ps.notificationsLogger
}
func (ps *PlatformService) EnableLoggingMetrics() {
if ps.metrics == nil || ps.metrics.metricsImpl == nil {
return
}
ps.logger.SetMetricsCollector(ps.metrics.metricsImpl.GetLoggerMetricsCollector(), mlog.DefaultMetricsUpdateFreqMillis)
// logging config needs to be reloaded when metrics collector is added or changed.
if err := ps.initLogging(); err != nil {
mlog.Error("Error re-configuring logging for metrics")
return
}
mlog.Debug("Logging metrics enabled")
}
// RemoveUnlicensedLogTargets removes any unlicensed log target types.
func (ps *PlatformService) RemoveUnlicensedLogTargets(license *model.License) {
if license != nil && *license.Features.AdvancedLogging {
// advanced logging enabled via license; no need to remove any targets
return
}
timeoutCtx, cancelCtx := context.WithTimeout(context.Background(), time.Second*10)
defer cancelCtx()
ps.logger.RemoveTargets(timeoutCtx, func(ti mlog.TargetInfo) bool {
return ti.Type != "*targets.Writer" && ti.Type != "*targets.File"
})
ps.notificationsLogger.RemoveTargets(timeoutCtx, func(ti mlog.TargetInfo) bool {
return ti.Type != "*targets.Writer" && ti.Type != "*targets.File"
})
}

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

@@ -20,7 +20,9 @@ import (
type PlatformService struct {
serviceConfig ServiceConfig
configStore *config.Store
logger *mlog.Logger
logger *mlog.Logger
notificationsLogger *mlog.Logger
metrics *platformMetrics
@@ -44,10 +46,13 @@ func New(sc ServiceConfig) (*PlatformService, error) {
ps := &PlatformService{
serviceConfig: sc,
configStore: sc.ConfigStore,
logger: sc.Logger,
cluster: sc.Cluster,
}
if err := ps.initLogging(); err != nil {
return nil, fmt.Errorf("failed to initialize logging: %w", err)
}
if err := ps.resetMetrics(sc.Metrics, ps.configStore.Get); err != nil {
return nil, err
}
@@ -77,3 +82,7 @@ func (ps *PlatformService) ShutdownConfig() error {
func (ps *PlatformService) SetTelemetryId(id string) {
ps.telemetryId = id
}
func (ps *PlatformService) SetLogger(logger *mlog.Logger) {
ps.logger = logger
}

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

@@ -110,7 +110,7 @@ func (ch *Channels) syncPluginsActiveState() {
if *config.Enable {
availablePlugins, err := pluginsEnvironment.Available()
if err != nil {
ch.srv.Log.Error("Unable to get available plugins", mlog.Err(err))
ch.srv.Log().Error("Unable to get available plugins", mlog.Err(err))
return
}
@@ -162,14 +162,14 @@ func (ch *Channels) syncPluginsActiveState() {
pluginID := plugin.Manifest.Id
updatedManifest, activated, err := pluginsEnvironment.Activate(pluginID)
if err != nil {
plugin.WrapLogger(ch.srv.Log).Error("Unable to activate plugin", mlog.Err(err))
plugin.WrapLogger(ch.srv.Log()).Error("Unable to activate plugin", mlog.Err(err))
return
}
if activated {
// Notify all cluster clients if ready
if err := ch.notifyPluginEnabled(updatedManifest); err != nil {
ch.srv.Log.Error("Failed to notify cluster on plugin enable", mlog.Err(err))
ch.srv.Log().Error("Failed to notify cluster on plugin enable", mlog.Err(err))
}
}
}(plugin)
@@ -209,7 +209,7 @@ func (ch *Channels) initPlugins(c *request.Context, pluginDir, webappPluginDir s
return
}
ch.srv.Log.Info("Starting up plugins")
ch.srv.Log().Info("Starting up plugins")
if err := os.Mkdir(pluginDir, 0744); err != nil && !os.IsExist(err) {
mlog.Error("Failed to start up plugins", mlog.Err(err))
@@ -225,7 +225,7 @@ func (ch *Channels) initPlugins(c *request.Context, pluginDir, webappPluginDir s
return New(ServerConnector(ch)).NewPluginAPI(c, manifest)
}
env, err := plugin.NewEnvironment(newAPIFunc, NewDriverImpl(ch.srv), pluginDir, webappPluginDir, ch.srv.Log, ch.srv.GetMetrics())
env, err := plugin.NewEnvironment(newAPIFunc, NewDriverImpl(ch.srv), pluginDir, webappPluginDir, ch.srv.Log(), ch.srv.GetMetrics())
if err != nil {
mlog.Error("Failed to start up plugins", mlog.Err(err))
return
@@ -263,7 +263,7 @@ func (ch *Channels) initPlugins(c *request.Context, pluginDir, webappPluginDir s
if pluginsEnvironment := ch.GetPluginsEnvironment(); pluginsEnvironment != nil {
pluginsEnvironment.RunMultiPluginHook(func(hooks plugin.Hooks) bool {
if err := hooks.OnConfigurationChange(); err != nil {
ch.srv.Log.Error("Plugin OnConfigurationChange hook failed", mlog.Err(err))
ch.srv.Log().Error("Plugin OnConfigurationChange hook failed", mlog.Err(err))
}
return true
}, plugin.OnConfigurationChangeID)
@@ -1018,7 +1018,7 @@ func (ch *Channels) installFeatureFlagPlugins() {
// Skip installing if the plugin has been previously disabled.
pluginState := ch.cfgSvc.Config().PluginSettings.PluginStates[pluginID]
if pluginState != nil && !pluginState.Enable {
ch.srv.Log.Debug("Not auto installing/upgrade because plugin was disabled", mlog.String("plugin_id", pluginID), mlog.String("version", version))
ch.srv.Log().Debug("Not auto installing/upgrade because plugin was disabled", mlog.String("plugin_id", pluginID), mlog.String("version", version))
continue
}
@@ -1036,17 +1036,17 @@ func (ch *Channels) installFeatureFlagPlugins() {
if !inCloud && pluginExists {
parsedVersion, err := semver.Parse(version)
if err != nil {
ch.srv.Log.Debug("Bad version from feature flag", mlog.String("plugin_id", pluginID), mlog.Err(err), mlog.String("version", version))
ch.srv.Log().Debug("Bad version from feature flag", mlog.String("plugin_id", pluginID), mlog.Err(err), mlog.String("version", version))
return
}
parsedExistingVersion, err := semver.Parse(pluginStatus.Version)
if err != nil {
ch.srv.Log.Debug("Bad version from plugin manifest", mlog.String("plugin_id", pluginID), mlog.Err(err), mlog.String("version", pluginStatus.Version))
ch.srv.Log().Debug("Bad version from plugin manifest", mlog.String("plugin_id", pluginID), mlog.Err(err), mlog.String("version", pluginStatus.Version))
return
}
if parsedVersion.LTE(parsedExistingVersion) {
ch.srv.Log.Debug("Skip installation because given version was a downgrade and on-prem installations should not downgrade.", mlog.String("plugin_id", pluginID), mlog.Err(err), mlog.String("version", pluginStatus.Version))
ch.srv.Log().Debug("Skip installation because given version was a downgrade and on-prem installations should not downgrade.", mlog.String("plugin_id", pluginID), mlog.Err(err), mlog.String("version", pluginStatus.Version))
return
}
}
@@ -1056,12 +1056,12 @@ func (ch *Channels) installFeatureFlagPlugins() {
Version: version,
})
if err != nil {
ch.srv.Log.Debug("Unable to install plugin from FF manifest", mlog.String("plugin_id", pluginID), mlog.Err(err), mlog.String("version", version))
ch.srv.Log().Debug("Unable to install plugin from FF manifest", mlog.String("plugin_id", pluginID), mlog.Err(err), mlog.String("version", version))
} else {
if err := ch.enablePlugin(pluginID); err != nil {
ch.srv.Log.Debug("Unable to enable plugin installed from feature flag.", mlog.String("plugin_id", pluginID), mlog.Err(err), mlog.String("version", version))
ch.srv.Log().Debug("Unable to enable plugin installed from feature flag.", mlog.String("plugin_id", pluginID), mlog.Err(err), mlog.String("version", version))
} else {
ch.srv.Log.Debug("Installed and enabled plugin.", mlog.String("plugin_id", pluginID), mlog.String("version", version))
ch.srv.Log().Debug("Installed and enabled plugin.", mlog.String("plugin_id", pluginID), mlog.String("version", version))
}
}
}

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

@@ -796,7 +796,7 @@ func TestPreparePostForClientWithImageProxy(t *testing.T) {
*cfg.ImageProxySettings.RemoteImageProxyOptions = "foo"
})
th.App.ch.imageProxy = imageproxy.MakeImageProxy(th.Server.platform, th.Server.HTTPService(), th.Server.Log)
th.App.ch.imageProxy = imageproxy.MakeImageProxy(th.Server.platform, th.Server.HTTPService(), th.Server.Log())
return th
}

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

@@ -472,7 +472,7 @@ func TestImageProxy(t *testing.T) {
*cfg.ServiceSettings.SiteURL = "http://mymattermost.com"
})
th.App.ch.imageProxy = imageproxy.MakeImageProxy(th.Server.platform, th.Server.HTTPService(), th.Server.Log)
th.App.ch.imageProxy = imageproxy.MakeImageProxy(th.Server.platform, th.Server.HTTPService(), th.Server.Log())
for name, tc := range map[string]struct {
ProxyType string
@@ -686,7 +686,7 @@ func TestCreatePost(t *testing.T) {
*cfg.ImageProxySettings.RemoteImageProxyOptions = "foo"
})
th.App.ch.imageProxy = imageproxy.MakeImageProxy(th.Server.platform, th.Server.HTTPService(), th.Server.Log)
th.App.ch.imageProxy = imageproxy.MakeImageProxy(th.Server.platform, th.Server.HTTPService(), th.Server.Log())
imageURL := "http://mydomain.com/myimage"
proxiedImageURL := "http://mymattermost.com/api/v4/image?url=http%3A%2F%2Fmydomain.com%2Fmyimage"
@@ -956,7 +956,7 @@ func TestPatchPost(t *testing.T) {
*cfg.ImageProxySettings.RemoteImageProxyOptions = "foo"
})
th.App.ch.imageProxy = imageproxy.MakeImageProxy(th.Server.platform, th.Server.HTTPService(), th.Server.Log)
th.App.ch.imageProxy = imageproxy.MakeImageProxy(th.Server.platform, th.Server.HTTPService(), th.Server.Log())
imageURL := "http://mydomain.com/myimage"
proxiedImageURL := "http://mymattermost.com/api/v4/image?url=http%3A%2F%2Fmydomain.com%2Fmyimage"
@@ -1252,7 +1252,7 @@ func TestUpdatePost(t *testing.T) {
*cfg.ImageProxySettings.RemoteImageProxyOptions = "foo"
})
th.App.ch.imageProxy = imageproxy.MakeImageProxy(th.Server.platform, th.Server.HTTPService(), th.Server.Log)
th.App.ch.imageProxy = imageproxy.MakeImageProxy(th.Server.platform, th.Server.HTTPService(), th.Server.Log())
imageURL := "http://mydomain.com/myimage"
proxiedImageURL := "http://mymattermost.com/api/v4/image?url=http%3A%2F%2Fmydomain.com%2Fmyimage"

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

@@ -91,7 +91,7 @@ func (s *Server) DoSecurityUpdateCheck() {
var bulletins model.SecurityBulletins
if jsonErr := json.NewDecoder(res.Body).Decode(&bulletins); jsonErr != nil {
s.Log.Error("Failed to decode JSON", mlog.Err(jsonErr))
s.Log().Error("Failed to decode JSON", mlog.Err(jsonErr))
return
}

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

@@ -181,9 +181,7 @@ type Server struct {
phase2PermissionsMigrationComplete bool
Audit *audit.Audit
Log *mlog.Logger
NotificationsLog *mlog.Logger
Audit *audit.Audit
joinCluster bool
startMetrics bool
@@ -243,7 +241,6 @@ func NewServer(options ...Option) (*Server, error) {
platformCfg := platform.ServiceConfig{
ConfigStore: configStore,
Logger: s.Log,
StartMetrics: s.startMetrics,
Cluster: s.Cluster,
}
@@ -262,11 +259,6 @@ func NewServer(options ...Option) (*Server, error) {
}
}
// Step 2: Logging
if err := s.initLogging(); err != nil {
mlog.Error("Could not initiate logging", mlog.Err(err))
}
subpath, err := utils.GetSubpathFromConfig(s.platform.Config())
if err != nil {
return nil, errors.Wrap(err, "failed to parse SiteURL subpath")
@@ -412,7 +404,7 @@ func NewServer(options ...Option) (*Server, error) {
FileInfoStoreKey: &fileInfoWrapper{srv: s},
ClusterKey: s.clusterWrapper,
UserKey: New(ServerConnector(s.Channels())),
LogKey: s.GetLogger(),
LogKey: s.Log(),
CloudKey: &cloudWrapper{cloud: s.Cloud},
KVStoreKey: &kvStoreWrapper{srv: s},
StoreKey: store.NewStoreServiceAdapter(s.Store),
@@ -490,7 +482,7 @@ func NewServer(options ...Option) (*Server, error) {
return nil, errors.Wrap(err, "Unable to create opengraphdata cache")
}
s.createPushNotificationsHub(request.EmptyContext(s.GetLogger()))
s.createPushNotificationsHub(request.EmptyContext(s.Log()))
if err2 := i18n.InitTranslations(*s.platform.Config().LocalizationSettings.DefaultServerLocale, *s.platform.Config().LocalizationSettings.DefaultClientLocale); err2 != nil {
return nil, errors.Wrapf(err2, "unable to load Mattermost translation files")
@@ -523,7 +515,7 @@ func NewServer(options ...Option) (*Server, error) {
s.Publish(message)
})
if err = s.initLogging(); err != nil {
if err = s.platform.ReconfigureLogger(); err != nil {
mlog.Error("Error re-configuring logging after config change", mlog.Err(err))
return
}
@@ -539,7 +531,7 @@ func NewServer(options ...Option) (*Server, error) {
})
s.telemetryService = telemetry.New(New(ServerConnector(s.Channels())), s.Store, s.SearchEngine, s.Log)
s.telemetryService = telemetry.New(New(ServerConnector(s.Channels())), s.Store, s.SearchEngine, s.Log())
s.platform.SetTelemetryId(s.TelemetryId()) // TODO: move this into platform once telemetry service moved to platform.
emailService, err := email.NewService(email.ServiceConfig{
@@ -613,12 +605,12 @@ func NewServer(options ...Option) (*Server, error) {
}
}
s.removeUnlicensedLogTargets(license)
s.enableLoggingMetrics()
s.platform.RemoveUnlicensedLogTargets(license)
s.platform.EnableLoggingMetrics()
s.loggerLicenseListenerId = s.AddLicenseListener(func(oldLicense, newLicense *model.License) {
s.removeUnlicensedLogTargets(newLicense)
s.enableLoggingMetrics()
s.platform.RemoveUnlicensedLogTargets(newLicense)
s.platform.EnableLoggingMetrics()
})
// Enable developer settings if this is a "dev" build
@@ -642,7 +634,7 @@ func NewServer(options ...Option) (*Server, error) {
}
if err := s.platform.RestartMetrics(); err != nil {
s.Log.Error("Failed to reset metrics server", mlog.Err(err))
s.Log().Error("Failed to reset metrics server", mlog.Err(err))
}
})
@@ -668,7 +660,7 @@ func NewServer(options ...Option) (*Server, error) {
s.platform.AddConfigListener(func(old, new *model.Config) {
appInstance := New(ServerConnector(s.Channels()))
if *old.GuestAccountsSettings.Enable && !*new.GuestAccountsSettings.Enable {
c := request.EmptyContext(s.GetLogger())
c := request.EmptyContext(s.Log())
if appErr := appInstance.DeactivateGuests(c); appErr != nil {
mlog.Error("Unable to deactivate guest accounts", mlog.Err(appErr))
}
@@ -678,7 +670,7 @@ func NewServer(options ...Option) (*Server, error) {
// Disable active guest accounts on first run if guest accounts are disabled
if !*s.platform.Config().GuestAccountsSettings.Enable {
appInstance := New(ServerConnector(s.Channels()))
c := request.EmptyContext(s.GetLogger())
c := request.EmptyContext(s.Log())
if appErr := appInstance.DeactivateGuests(c); appErr != nil {
mlog.Error("Unable to deactivate guest accounts", mlog.Err(appErr))
}
@@ -786,70 +778,6 @@ func (s *Server) DatabaseTypeAndSchemaVersion() (string, string) {
return *s.platform.Config().SqlSettings.DriverName, strconv.Itoa(schemaVersion)
}
// initLogging initializes and configures the logger(s). This may be called more than once.
func (s *Server) initLogging() error {
var err error
// create the app logger if needed
if s.Log == nil {
s.Log, err = mlog.NewLogger()
if err != nil {
return err
}
}
// create notification logger if needed
if s.NotificationsLog == nil {
l, err := mlog.NewLogger()
if err != nil {
return err
}
s.NotificationsLog = l.With(mlog.String("logSource", "notifications"))
}
if err := s.platform.ConfigureLogger("logging", s.Log, &s.platform.Config().LogSettings, config.GetLogFileLocation); err != nil {
// if the config is locked then a unit test has already configured and locked the logger; not an error.
if !errors.Is(err, mlog.ErrConfigurationLock) {
// revert to default logger if the config is invalid
mlog.InitGlobalLogger(nil)
return err
}
}
// Redirect default Go logger to app logger.
s.Log.RedirectStdLog(mlog.LvlStdLog)
// Use the app logger as the global logger (eventually remove all instances of global logging).
mlog.InitGlobalLogger(s.Log)
notificationLogSettings := config.GetLogSettingsFromNotificationsLogSettings(&s.platform.Config().NotificationLogSettings)
if err := s.platform.ConfigureLogger("notification logging", s.NotificationsLog, notificationLogSettings, config.GetNotificationsLogFileLocation); err != nil {
if !errors.Is(err, mlog.ErrConfigurationLock) {
mlog.Error("Error configuring notification logger", mlog.Err(err))
return err
}
}
return nil
}
// removeUnlicensedLogTargets removes any unlicensed log target types.
func (s *Server) removeUnlicensedLogTargets(license *model.License) {
if license != nil && *license.Features.AdvancedLogging {
// advanced logging enabled via license; no need to remove any targets
return
}
timeoutCtx, cancelCtx := context.WithTimeout(context.Background(), time.Second*10)
defer cancelCtx()
s.Log.RemoveTargets(timeoutCtx, func(ti mlog.TargetInfo) bool {
return ti.Type != "*targets.Writer" && ti.Type != "*targets.File"
})
s.NotificationsLog.RemoveTargets(timeoutCtx, func(ti mlog.TargetInfo) bool {
return ti.Type != "*targets.Writer" && ti.Type != "*targets.File"
})
}
func (s *Server) startInterClusterServices(license *model.License) error {
if license == nil {
mlog.Debug("No license provided; Remote Cluster services disabled")
@@ -916,22 +844,6 @@ func (s *Server) startInterClusterServices(license *model.License) error {
return nil
}
func (s *Server) enableLoggingMetrics() {
if s.GetMetrics() == nil {
return
}
s.Log.SetMetricsCollector(s.GetMetrics().GetLoggerMetricsCollector(), mlog.DefaultMetricsUpdateFreqMillis)
// logging config needs to be reloaded when metrics collector is added or changed.
if err := s.initLogging(); err != nil {
mlog.Error("Error re-configuring logging for metrics")
return
}
mlog.Debug("Logging metrics enabled")
}
const TimeToWaitForConnectionsToCloseOnServerShutdown = time.Second
func (s *Server) StopHTTPServer() {
@@ -957,7 +869,7 @@ func (s *Server) StopHTTPServer() {
}
func (s *Server) Shutdown() {
s.Log.Info("Stopping Server...")
s.Log().Info("Stopping Server...")
defer sentry.Flush(2 * time.Second)
@@ -968,24 +880,24 @@ func (s *Server) Shutdown() {
if s.tracer != nil {
if err := s.tracer.Close(); err != nil {
s.Log.Warn("Unable to cleanly shutdown opentracing client", mlog.Err(err))
s.Log().Warn("Unable to cleanly shutdown opentracing client", mlog.Err(err))
}
}
err := s.telemetryService.Shutdown()
if err != nil {
s.Log.Warn("Unable to cleanly shutdown telemetry client", mlog.Err(err))
s.Log().Warn("Unable to cleanly shutdown telemetry client", mlog.Err(err))
}
s.serviceMux.RLock()
if s.sharedChannelService != nil {
if err = s.sharedChannelService.Shutdown(); err != nil {
s.Log.Error("Error shutting down shared channel services", mlog.Err(err))
s.Log().Error("Error shutting down shared channel services", mlog.Err(err))
}
}
if s.remoteClusterService != nil {
if err = s.remoteClusterService.Shutdown(); err != nil {
s.Log.Error("Error shutting down intercluster services", mlog.Err(err))
s.Log().Error("Error shutting down intercluster services", mlog.Err(err))
}
}
s.serviceMux.RUnlock()
@@ -1007,7 +919,7 @@ func (s *Server) Shutdown() {
s.platform.StopFeatureFlagUpdateJob()
if err = s.platform.ShutdownConfig(); err != nil {
s.Log.Warn("Failed to shut down config store", mlog.Err(err))
s.Log().Warn("Failed to shut down config store", mlog.Err(err))
}
if s.Cluster != nil {
@@ -1015,7 +927,7 @@ func (s *Server) Shutdown() {
}
if err = s.platform.ShutdownMetrics(); err != nil {
s.Log.Warn("Failed to stop metrics server", mlog.Err(err))
s.Log().Warn("Failed to stop metrics server", mlog.Err(err))
}
// This must be done after the cluster is stopped.
@@ -1024,10 +936,10 @@ func (s *Server) Shutdown() {
// before stopping them as both calls essentially become no-ops
// if nothing is running.
if err = s.Jobs.StopWorkers(); err != nil && !errors.Is(err, jobs.ErrWorkersNotRunning) {
s.Log.Warn("Failed to stop job server workers", mlog.Err(err))
s.Log().Warn("Failed to stop job server workers", mlog.Err(err))
}
if err = s.Jobs.StopSchedulers(); err != nil && !errors.Is(err, jobs.ErrSchedulersNotRunning) {
s.Log.Warn("Failed to stop job server schedulers", mlog.Err(err))
s.Log().Warn("Failed to stop job server schedulers", mlog.Err(err))
}
}
@@ -1036,7 +948,7 @@ func (s *Server) Shutdown() {
// on parent services.
for name, product := range s.products {
if err2 := product.Stop(); err2 != nil {
s.Log.Warn("Unable to cleanly stop product", mlog.String("name", name), mlog.Err(err2))
s.Log().Warn("Unable to cleanly stop product", mlog.String("name", name), mlog.Err(err2))
}
}
@@ -1046,19 +958,19 @@ func (s *Server) Shutdown() {
if s.CacheProvider != nil {
if err = s.CacheProvider.Close(); err != nil {
s.Log.Warn("Unable to cleanly shutdown cache", mlog.Err(err))
s.Log().Warn("Unable to cleanly shutdown cache", mlog.Err(err))
}
}
s.Log.Info("Server stopped")
s.Log().Info("Server stopped")
// shutdown main and notification loggers which will flush any remaining log records.
timeoutCtx, timeoutCancel := context.WithTimeout(context.Background(), time.Second*15)
defer timeoutCancel()
if err = s.NotificationsLog.ShutdownWithTimeout(timeoutCtx); err != nil {
if err = s.NotificationsLog().ShutdownWithTimeout(timeoutCtx); err != nil {
fmt.Fprintf(os.Stderr, "Error shutting down notification logger: %v", err)
}
if err = s.Log.ShutdownWithTimeout(timeoutCtx); err != nil {
if err = s.Log().ShutdownWithTimeout(timeoutCtx); err != nil {
fmt.Fprintf(os.Stderr, "Error shutting down main logger: %v", err)
}
}
@@ -1240,7 +1152,7 @@ func (s *Server) Start() error {
// If we have debugging of CORS turned on then forward messages to logs
if debug {
corsWrapper.Log = s.Log.With(mlog.String("source", "cors")).StdLogger(mlog.LvlDebug)
corsWrapper.Log = s.Log().With(mlog.String("source", "cors")).StdLogger(mlog.LvlDebug)
}
handler = corsWrapper.Handler(handler)
@@ -1260,7 +1172,7 @@ func (s *Server) Start() error {
s.Busy = NewBusy(s.Cluster)
// Creating a logger for logging errors from http.Server at error level
errStdLog := s.Log.With(mlog.String("source", "httpserver")).StdLogger(mlog.LvlError)
errStdLog := s.Log().With(mlog.String("source", "httpserver")).StdLogger(mlog.LvlError)
s.Server = &http.Server{
Handler: handler,
@@ -1305,7 +1217,7 @@ func (s *Server) Start() error {
server := &http.Server{
Addr: httpListenAddress,
Handler: m.HTTPHandler(nil),
ErrorLog: s.Log.With(mlog.String("source", "le_forwarder_server")).StdLogger(mlog.LvlError),
ErrorLog: s.Log().With(mlog.String("source", "le_forwarder_server")).StdLogger(mlog.LvlError),
}
go server.ListenAndServe()
} else {
@@ -1319,7 +1231,7 @@ func (s *Server) Start() error {
server := &http.Server{
Handler: http.HandlerFunc(handleHTTPRedirect),
ErrorLog: s.Log.With(mlog.String("source", "forwarder_server")).StdLogger(mlog.LvlError),
ErrorLog: s.Log().With(mlog.String("source", "forwarder_server")).StdLogger(mlog.LvlError),
}
server.Serve(redirectListener)
}()
@@ -1732,7 +1644,7 @@ func (s *Server) StartSearchEngine() (string, string) {
if s.SearchEngine.ElasticsearchEngine != nil && s.SearchEngine.ElasticsearchEngine.IsActive() {
s.Go(func() {
if err := s.SearchEngine.ElasticsearchEngine.Start(); err != nil {
s.Log.Error(err.Error())
s.Log().Error(err.Error())
}
})
}
@@ -1947,14 +1859,6 @@ func (s *Server) HTTPService() httpservice.HTTPService {
return s.httpService
}
func (s *Server) SetLog(l *mlog.Logger) {
s.Log = l
}
func (s *Server) GetLogger() mlog.LoggerIFace {
return s.Log
}
// GetStore returns the server's Store. Exposing via a method
// allows interfaces to be created with subsets of server APIs.
func (s *Server) GetStore() store.Store {
@@ -2118,3 +2022,11 @@ func (a *App) GetAppliedSchemaMigrations() ([]model.AppliedMigration, *model.App
func (s *Server) Platform() *platform.PlatformService {
return s.platform
}
func (s *Server) Log() *mlog.Logger {
return s.platform.Logger()
}
func (s *Server) NotificationsLog() *mlog.Logger {
return s.platform.NotificationsLogger()
}

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

@@ -405,12 +405,13 @@ func TestPanicLog(t *testing.T) {
logger.LockConfiguration()
// Creating a server with logger
s, err := NewServer(SetLogger(logger))
s, err := NewServer()
require.NoError(t, err)
s.Platform().SetLogger(logger)
// Route for just panicking
s.Router.HandleFunc("/panic", func(writer http.ResponseWriter, request *http.Request) {
s.Log.Info("inside panic handler")
s.Log().Info("inside panic handler")
panic("log this panic")
})

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

@@ -90,7 +90,7 @@ func (a *App) TotalWebsocketConnections() int {
func (s *Server) HubStart() {
// Total number of hubs is twice the number of CPUs.
numberOfHubs := runtime.NumCPU() * 2
s.Log.Info("Starting websocket hubs", mlog.Int("number_of_hubs", numberOfHubs))
s.Log().Info("Starting websocket hubs", mlog.Int("number_of_hubs", numberOfHubs))
hubs := make([]*Hub, numberOfHubs)